@mysterycode-liwen/dsh-credential-vault 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1956 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@mysterycode-liwen/dsh-credential-vault',
3
+ factory(require) {
4
+ var React = require('react');
5
+ var h = React.createElement;
6
+ var useState = React.useState;
7
+ var useEffect = React.useEffect;
8
+ var useRef = React.useRef;
9
+
10
+ var STORAGE_KEY = '@local/dsh-credential-vault:entries:v1';
11
+ var STORAGE_KEY_LEGACY = '@local/credential-vault:entries:v1';
12
+ var MASK = '••••••••••••';
13
+ var PANEL_ID = 'dsh-credential-vault';
14
+ // Same-origin path served by the Host half (index.js). Relative so it works
15
+ // whatever port the Web GUI is on.
16
+ var API = 'dsh-credential-vault/';
17
+ /** Plugin version shown in Settings; keep in sync with package.json on release. */
18
+ var VERSION = '1.2.0';
19
+
20
+ // Compare two semver-ish strings: -1 (left older), 0 (equal), 1 (left newer).
21
+ // Used to decide "update available" against THIS client's version, so the
22
+ // decision can't disagree with the version shown in the UI (host index.js
23
+ // may still hold an older CURRENT_VERSION until Harness is restarted).
24
+ function compareVersions(a, b) {
25
+ function parts(v) {
26
+ var m = String(v || '').trim().replace(/^v/i, '').match(/^(\d+)\.(\d+)\.(\d+)/);
27
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : [0, 0, 0];
28
+ }
29
+ var x = parts(a), y = parts(b);
30
+ for (var i = 0; i < 3; i++) {
31
+ if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
32
+ }
33
+ return 0;
34
+ }
35
+
36
+ var DICTS = {
37
+ en: {
38
+ title: 'Credential vault', subtitle: 'Your accounts, passwords & API keys in one place',
39
+ add: 'Add', items: 'items',
40
+ sort: 'Sort', sortRecent: 'Recently updated', sortTitle: 'Name (A–Z)', sortCategory: 'Type',
41
+ search: 'Search name, account, URL or notes…',
42
+ filterAll: 'All', filterAccount: 'Accounts', filterApikey: 'API keys', filterOther: 'Other',
43
+ localNotice: 'Stored locally in this browser (localStorage) on this device. Not synced or encrypted — avoid shared / public browsers.',
44
+ show: 'Show', hide: 'Hide', copy: 'Copy', visit: 'Visit', copied: 'Copied to clipboard', copyFail: 'Copy failed — select the text manually',
45
+ visitFail: 'Could not open the browser. Check the URL and try again.',
46
+ visitHint: 'Returning to the conversation to open the browser…',
47
+ edit: 'Edit', delete: 'Delete',
48
+ emptyTitle: 'No credentials yet', emptyText: 'Click “Add” to save your first account, password or API key.',
49
+ emptyFiltered: 'No matches',
50
+ editorNew: 'New credential', editorEdit: 'Edit credential',
51
+ fTitle: 'Name', fTitlePh: 'e.g. GitHub, Google', fTitlePhApikey: 'e.g. OpenAI, AWS, GitHub PAT', fTitlePhOther: 'e.g. Recovery codes, Wi-Fi, License',
52
+ fCategory: 'Type',
53
+ fAccount: 'Account / username', fAccountPh: 'user@example.com',
54
+ fPassword: 'Password', fPasswordPh: 'Enter password',
55
+ fUrl: 'Login URL (optional)', fUrlPh: 'https://…',
56
+ fProvider: 'Platform / provider', fProviderPh: 'e.g. OpenAI, Anthropic, AWS',
57
+ fApiKey: 'API key / token', fApiKeyPh: 'sk-… / ghp_… / paste token',
58
+ fEndpoint: 'API endpoint / base URL', fEndpointPh: 'https://api.openai.com/v1',
59
+ fExpiry: 'Expires on (optional)',
60
+ fContent: 'Content / secret', fContentPh: 'Recovery codes, license key, certificate, PIN…',
61
+ fNotes: 'Notes (optional)', fNotesPh: 'Any extra info…',
62
+ catAccount: 'Account', catApikey: 'API key', catOther: 'Other',
63
+ hintAccount: 'For website / app logins — username and password.',
64
+ hintApikey: 'For platform-issued API keys, tokens and endpoints.',
65
+ hintOther: 'For recovery codes, licenses, certificates or any free text.',
66
+ save: 'Save', cancel: 'Cancel', required: 'Please enter a name',
67
+ confirmDelete: 'Delete this credential? This cannot be undone.',
68
+ saved: 'Saved', deleted: 'Deleted', revealAll: 'Reveal all', hideAll: 'Hide all',
69
+ settingsNav: 'Credential vault',
70
+ secTitle: 'Access password', secDesc: 'Protect the vault with an access password. When enabled, you must enter it to view your credentials.',
71
+ secEnable: 'Require access password', secEnableHint: 'When on, the vault locks on open and after a period of inactivity.',
72
+ secSetPassword: 'Set / change access password', secCurrent: 'Current password', secNew: 'New password', secConfirm: 'Confirm new password',
73
+ secSavePassword: 'Save password', secPasswordOn: 'Access password is enabled', secPasswordOff: 'Access password is disabled',
74
+ secEnabledLocked: 'Access password enabled — the vault is now locked.',
75
+ secDisableHint: 'Enter your current access password to turn this off.', secDisableConfirm: 'Turn off',
76
+ secIdle: 'Auto-lock after inactivity', secIdleHint: 'When on, the vault re-locks after a period of inactivity (requires the access password).',
77
+ secIdleOn: 'Auto-lock is on', secIdleOff: 'Auto-lock is off', secIdleDuration: 'Lock after',
78
+ idleMinute: 'minute', idleMinutes: 'minutes', idleHour: 'hour', idleHours: 'hours',
79
+ secCompleteSetup: 'Before enabling, set a password and a security question so you can recover access.',
80
+ secNeedSetupFirst: 'Set a password and a security question before enabling.',
81
+ secQuestion: 'Security question', secAnswer: 'Security answer', secAnswerHint: 'Used to reset the access password if you forget it. Stored hashed, never shown again.',
82
+ secCustomQuestion: 'Custom question', secSaveQuestion: 'Save security question', secQuestionSet: 'Security question has been set.',
83
+ secQCurrentHint: 'Enter your current access password to change the security question.', secCurrentRequired: 'Please enter your current access password.',
84
+ secSetupRequired: 'Password and security question must both be set.',
85
+ secCurrentWrong: 'Current password is incorrect.', secMismatch: 'Passwords do not match.', secTooShort: 'Password must be at least 4 characters.',
86
+ secAnswerWrong: 'Security answer is incorrect.', secMinLength: 'At least 4 characters.',
87
+ lockTitle: 'Vault locked', lockDesc: 'Enter your access password to view your credentials.',
88
+ unlock: 'Unlock', unlockFail: 'Incorrect password. Try again.', forgot: 'Forgot password?',
89
+ resetTitle: 'Reset access password', resetDesc: 'Answer your security question to choose a new access password.',
90
+ resetAnswer: 'Your answer', resetNewPassword: 'New password', resetConfirm: 'Confirm new password',
91
+ resetSubmit: 'Reset password', resetFail: 'That answer does not match.', resetDone: 'Password has been reset. Please unlock again.',
92
+ resetUnavailable: 'No security question is configured. Restore from a backup or clear this browser\'s site data.',
93
+ lockIdle: 'Locked after inactivity',
94
+ updateTitle: 'Plugin updates', updateDesc: 'Check whether a newer version of the dsh-credential-vault plugin is available.',
95
+ updateCurrent: 'Current version', updateLatest: 'Latest version', updateCheck: 'Check for updates',
96
+ updateChecking: 'Checking…', updateAvailable: 'A newer version is available:', updateUpToDate: 'You are up to date.',
97
+ updateNoRelease: 'No Release published yet — update check is unavailable.', updateFail: 'Update check failed. Please try again later.',
98
+ updateHow: 'Update via the same way you installed this plugin.',
99
+ upgrade: 'Upgrade', upgrading: 'Upgrading…', upgradeCheckMarket: 'Checking plugin market…',
100
+ upgradeConfirm: 'Upgrade with dshmarket? It uses the same plugin manager that installed this plugin. DeepSeek Harness may need a restart afterwards.',
101
+ upgradeStarted: 'Upgrade started…', upgradePolling: 'Installing…', upgradeNoMarket: 'The plugin market (dshmarket) is not available here. Please update via the way you installed this plugin.',
102
+ upgradeSuccess: 'Upgrade installed.', upgradeRestart: 'Restart DeepSeek Harness to finish.', upgradeFail: 'Upgrade failed: ',
103
+ upgradeTitle: 'Confirm upgrade', upgradeGo: 'Upgrade',
104
+ export: 'Export', import: 'Import',
105
+ exportWarn: 'The backup file contains plaintext passwords and API keys. Keep it safe and delete it when no longer needed. Continue?',
106
+ exportDone: 'Backup downloaded', exportFail: 'Export failed', exportEmpty: 'Nothing to export',
107
+ exportTitle: 'Export credentials', exportConfirm: 'Export backup',
108
+ importTitle: 'Import credentials', importHint: 'Imported secrets are stored locally, just like the rest of your vault.',
109
+ importFound: 'Entries in file', importMode: 'Import mode',
110
+ importMerge: 'Merge (keep existing, skip duplicates)',
111
+ importReplace: 'Replace all existing entries',
112
+ importMergeHint: 'Existing entries are kept; entries whose ID already exists are skipped.',
113
+ importReplaceWarn: 'All current entries will be removed and replaced by the file contents. This cannot be undone.',
114
+ importConfirm: 'Import', importDone: 'Import complete',
115
+ importInvalid: 'Invalid backup file', importEmpty: 'No credentials in this file',
116
+ genButton: 'Generate password', genField: 'Generate a password for this field',
117
+ genTitle: 'Password generator', genHint: 'Generates a strong random password using your browser’s cryptographic random source. Nothing is stored or sent anywhere.',
118
+ genLength: 'Length', genUpper: 'Uppercase (A–Z)', genLower: 'Lowercase (a–z)', genDigits: 'Digits (0–9)',
119
+ genSymbols: 'Symbols (!@#…)', genAvoidAmbiguous: 'Avoid ambiguous characters (0/O, 1/l)',
120
+ genGenerate: 'Generate', genRegenerate: 'Regenerate', genCopy: 'Copy password', genUse: 'Use this password',
121
+ genError: 'Select at least one character type.', genStrength: 'Strength',
122
+ genWeak: 'Weak', genFair: 'Fair', genStrong: 'Strong',
123
+ auditButton: 'Security audit', auditTitle: 'Security audit',
124
+ auditHint: 'Checks every entry for weak or reused secrets, missing values and expiring keys. The audit runs locally — nothing leaves your device.',
125
+ auditRun: 'Run audit', auditScanning: 'Scanning…', auditClean: 'No issues found. Your vault looks good.',
126
+ auditSummary: 'entries scanned', auditIssues: 'issues found',
127
+ auditWeak: 'Weak password', auditWeakDesc: 'Password is short or too simple.',
128
+ auditReused: 'Reused secret', auditReusedDesc: 'This secret is also used in another entry.',
129
+ auditEmpty: 'Missing secret', auditEmptyDesc: 'This entry has no password / key saved.',
130
+ auditExpired: 'Expired key', auditExpiredDesc: 'The expiry date has passed.',
131
+ auditExpiring: 'Expiring soon', auditExpiringDesc: 'Expires within 30 days.',
132
+ auditEdit: 'Edit', auditHigh: 'High', auditMedium: 'Medium', auditLow: 'Low',
133
+ auditNote: 'Secrets are never shown in the audit — only entry names and issue types.',
134
+ auditFail: 'Audit could not run.'
135
+ },
136
+ zh: {
137
+ title: '凭据保险箱', subtitle: '集中管理你的账号、密码与 API Key',
138
+ add: '新增', items: '条',
139
+ sort: '排序', sortRecent: '最近更新', sortTitle: '名称(A–Z)', sortCategory: '类型',
140
+ search: '搜索名称、账号、网址或备注…',
141
+ filterAll: '全部', filterAccount: '账号密码', filterApikey: 'API Key', filterOther: '其他',
142
+ localNotice: '数据仅保存在本机浏览器的 localStorage 中,不跨设备同步、不加密,请避免在公用/共享浏览器使用。',
143
+ show: '显示', hide: '隐藏', copy: '复制', visit: '访问', copied: '已复制到剪贴板', copyFail: '复制失败,请手动选择文本',
144
+ visitFail: '无法打开浏览器,请检查网址后重试。',
145
+ visitHint: '正在返回对话以打开浏览器…',
146
+ edit: '编辑', delete: '删除',
147
+ emptyTitle: '还没有凭据', emptyText: '点击「新增」保存第一条账号、密码或 API Key。',
148
+ emptyFiltered: '没有匹配项',
149
+ editorNew: '新增凭据', editorEdit: '编辑凭据',
150
+ fTitle: '名称', fTitlePh: '例如:GitHub、Google', fTitlePhApikey: '例如:OpenAI、AWS、GitHub PAT', fTitlePhOther: '例如:恢复码、Wi-Fi、许可证',
151
+ fCategory: '类型',
152
+ fAccount: '账号 / 用户名', fAccountPh: 'user@example.com',
153
+ fPassword: '密码', fPasswordPh: '输入密码',
154
+ fUrl: '登录网址(可选)', fUrlPh: 'https://…',
155
+ fProvider: '平台 / 服务商', fProviderPh: '例如:OpenAI、Anthropic、AWS',
156
+ fApiKey: 'API Key / 令牌', fApiKeyPh: 'sk-… / ghp_… / 粘贴令牌',
157
+ fEndpoint: 'API 地址 / Base URL', fEndpointPh: 'https://api.openai.com/v1',
158
+ fExpiry: '到期日期(可选)',
159
+ fContent: '内容 / 密钥', fContentPh: '恢复码、许可证、证书、PIN…',
160
+ fNotes: '备注(可选)', fNotesPh: '其他信息…',
161
+ catAccount: '账号密码', catApikey: 'API Key', catOther: '其他',
162
+ hintAccount: '用于保存网站 / 应用的登录账号与密码。',
163
+ hintApikey: '用于保存平台签发的 API Key、令牌与接口地址。',
164
+ hintOther: '用于保存恢复码、许可证、证书等任意文本。',
165
+ save: '保存', cancel: '取消', required: '请输入名称',
166
+ confirmDelete: '确定删除这条凭据?此操作不可撤销。',
167
+ saved: '已保存', deleted: '已删除', revealAll: '全部显示', hideAll: '全部隐藏',
168
+ settingsNav: '凭据保险箱',
169
+ secTitle: '访问密码', secDesc: '使用访问密码保护保险箱。开启后,需要输入密码才能查看凭据。',
170
+ secEnable: '启用访问密码', secEnableHint: '开启后,保险箱在打开时和无操作一段时间后自动锁定。',
171
+ secSetPassword: '设置 / 修改访问密码', secCurrent: '当前密码', secNew: '新密码', secConfirm: '确认新密码',
172
+ secSavePassword: '保存密码', secPasswordOn: '访问密码已启用', secPasswordOff: '访问密码未启用',
173
+ secEnabledLocked: '访问密码已启用,保险箱现已锁定。',
174
+ secDisableHint: '请输入当前访问密码以关闭此选项。', secDisableConfirm: '关闭访问密码',
175
+ secIdle: '闲置自动锁定', secIdleHint: '开启后,一段时间无操作保险箱会自动重新锁定(需已启用访问密码)。',
176
+ secIdleOn: '自动锁定已开启', secIdleOff: '自动锁定已关闭', secIdleDuration: '锁定时长',
177
+ idleMinute: '分钟', idleMinutes: '分钟', idleHour: '小时', idleHours: '小时',
178
+ secCompleteSetup: '请先设置密码和密保问题,再开启访问密码。',
179
+ secNeedSetupFirst: '请先设置密码和密保问题,再开启此选项。',
180
+ secQuestion: '密保问题', secAnswer: '密保答案', secAnswerHint: '忘记密码时用于重置访问密码。仅保存哈希,不会再次显示。',
181
+ secCustomQuestion: '自定义问题', secSaveQuestion: '保存密保问题', secQuestionSet: '密保问题已设置。',
182
+ secQCurrentHint: '修改密保问题前请输入当前访问密码。', secCurrentRequired: '请输入当前访问密码。',
183
+ secSetupRequired: '密码和密保问题都必须先设置。',
184
+ secCurrentWrong: '当前密码不正确。', secMismatch: '两次输入的密码不一致。', secTooShort: '密码至少 4 个字符。',
185
+ secAnswerWrong: '密保答案不正确。', secMinLength: '至少 4 个字符。',
186
+ lockTitle: '保险箱已锁定', lockDesc: '请输入访问密码以查看凭据。',
187
+ unlock: '解锁', unlockFail: '密码错误,请重试。', forgot: '忘记密码?',
188
+ resetTitle: '重置访问密码', resetDesc: '回答密保问题以设置新的访问密码。',
189
+ resetAnswer: '你的答案', resetNewPassword: '新密码', resetConfirm: '确认新密码',
190
+ resetSubmit: '重置密码', resetFail: '密保答案不匹配。', resetDone: '密码已重置,请重新解锁。',
191
+ resetUnavailable: '尚未设置密保问题。请从备份恢复,或清除此浏览器的站点数据。',
192
+ lockIdle: '因长时间无操作已锁定',
193
+ updateTitle: '插件更新', updateDesc: '检查凭据保险箱插件是否有新版本可用。',
194
+ updateCurrent: '当前版本', updateLatest: '最新版本', updateCheck: '检查更新',
195
+ updateChecking: '检查中…', updateAvailable: '发现新版本:', updateUpToDate: '已是最新版本。',
196
+ updateNoRelease: '仓库尚未发布 Release,暂时无法检查更新。', updateFail: '检查更新失败,请稍后重试。',
197
+ updateHow: '请通过当初安装本插件的相同方式进行更新。',
198
+ upgrade: '升级', upgrading: '升级中…', upgradeCheckMarket: '正在检查插件市场…',
199
+ upgradeConfirm: '使用 dshmarket 升级?它会调用当初安装本插件的同一个插件管理器,升级后可能需要重启 DeepSeek Harness。',
200
+ upgradeStarted: '已开始升级…', upgradePolling: '正在安装…', upgradeNoMarket: '当前不可用插件市场(dshmarket),请通过当初安装本插件的方式进行更新。',
201
+ upgradeSuccess: '升级已安装。', upgradeRestart: '请重启 DeepSeek Harness 以完成升级。', upgradeFail: '升级失败:',
202
+ upgradeTitle: '确认升级', upgradeGo: '立即升级',
203
+ export: '导出', import: '导入',
204
+ exportWarn: '备份文件包含明文密码和 API Key,请妥善保管并在不需要时删除。是否继续?',
205
+ exportDone: '备份已下载', exportFail: '导出失败', exportEmpty: '没有可导出的凭据',
206
+ exportTitle: '导出凭据', exportConfirm: '导出备份',
207
+ importTitle: '导入凭据', importHint: '导入的密钥与保险箱其他数据一样仅保存在本机。',
208
+ importFound: '文件中的条目数', importMode: '导入方式',
209
+ importMerge: '合并(保留现有,跳过重复)',
210
+ importReplace: '替换所有现有条目',
211
+ importMergeHint: '保留现有条目;ID 已存在的条目将被跳过。',
212
+ importReplaceWarn: '当前所有条目将被删除并由文件内容替换,此操作不可撤销。',
213
+ importConfirm: '导入', importDone: '导入完成',
214
+ importInvalid: '备份文件无效', importEmpty: '文件中没有凭据',
215
+ genButton: '生成密码', genField: '为此字段生成密码',
216
+ genTitle: '密码生成器', genHint: '使用浏览器的加密随机源生成高强度随机密码,不会存储或上传任何数据。',
217
+ genLength: '长度', genUpper: '大写字母 (A–Z)', genLower: '小写字母 (a–z)', genDigits: '数字 (0–9)',
218
+ genSymbols: '符号 (!@#…)', genAvoidAmbiguous: '排除易混淆字符 (0/O, 1/l)',
219
+ genGenerate: '生成', genRegenerate: '重新生成', genCopy: '复制密码', genUse: '使用此密码',
220
+ genError: '请至少选择一种字符类型。', genStrength: '强度',
221
+ genWeak: '弱', genFair: '中', genStrong: '强',
222
+ auditButton: '健康审计', auditTitle: '健康审计',
223
+ auditHint: '检查每条记录的密码/密钥是否过弱、重复、缺失或即将过期。审计在本地进行,不会上传任何数据。',
224
+ auditRun: '开始审计', auditScanning: '扫描中…', auditClean: '未发现问题,保险箱状态良好。',
225
+ auditSummary: '条记录已扫描', auditIssues: '个问题',
226
+ auditWeak: '弱密码', auditWeakDesc: '密码过短或过于简单。',
227
+ auditReused: '重复使用', auditReusedDesc: '该密钥与另一条记录重复使用。',
228
+ auditEmpty: '缺少密钥', auditEmptyDesc: '该记录未保存密码 / 密钥。',
229
+ auditExpired: '已过期', auditExpiredDesc: '到期日期已过。',
230
+ auditExpiring: '即将过期', auditExpiringDesc: '将在 30 天内过期。',
231
+ auditEdit: '编辑', auditHigh: '高', auditMedium: '中', auditLow: '低',
232
+ auditNote: '审计中不会显示密钥明文,只显示记录名称和问题类型。',
233
+ auditFail: '审计运行失败。'
234
+ }
235
+ };
236
+
237
+ // Each credential type owns a DIFFERENT form. The schema drives the editor,
238
+ // the card layout and the search index, so the three types never look alike.
239
+ // type: text | textarea | secret | secretarea | date
240
+ var SCHEMAS = {
241
+ account: [
242
+ { key: 'title', label: 'fTitle', ph: 'fTitlePh', type: 'text', required: true },
243
+ { key: 'username', label: 'fAccount', ph: 'fAccountPh', type: 'text', mono: true },
244
+ { key: 'password', label: 'fPassword', ph: 'fPasswordPh', type: 'secret', mono: true, generatable: true },
245
+ { key: 'url', label: 'fUrl', ph: 'fUrlPh', type: 'text', isUrl: true },
246
+ { key: 'notes', label: 'fNotes', ph: 'fNotesPh', type: 'textarea' }
247
+ ],
248
+ apikey: [
249
+ { key: 'title', label: 'fTitle', ph: 'fTitlePhApikey', type: 'text', required: true },
250
+ { key: 'provider', label: 'fProvider', ph: 'fProviderPh', type: 'text' },
251
+ { key: 'apiKey', label: 'fApiKey', ph: 'fApiKeyPh', type: 'secret', mono: true },
252
+ { key: 'endpoint', label: 'fEndpoint', ph: 'fEndpointPh', type: 'text', mono: true, isUrl: true },
253
+ { key: 'expiry', label: 'fExpiry', type: 'date' },
254
+ { key: 'notes', label: 'fNotes', ph: 'fNotesPh', type: 'textarea' }
255
+ ],
256
+ other: [
257
+ { key: 'title', label: 'fTitle', ph: 'fTitlePhOther', type: 'text', required: true },
258
+ { key: 'content', label: 'fContent', ph: 'fContentPh', type: 'secretarea', mono: true },
259
+ { key: 'notes', label: 'fNotes', ph: 'fNotesPh', type: 'textarea' }
260
+ ]
261
+ };
262
+ var CATEGORIES = [
263
+ { k: 'account', label: 'catAccount', hint: 'hintAccount' },
264
+ { k: 'apikey', label: 'catApikey', hint: 'hintApikey' },
265
+ { k: 'other', label: 'catOther', hint: 'hintOther' }
266
+ ];
267
+ var FILTERS = [
268
+ { k: 'all', label: 'filterAll' },
269
+ { k: 'account', label: 'filterAccount' },
270
+ { k: 'apikey', label: 'filterApikey' },
271
+ { k: 'other', label: 'filterOther' }
272
+ ];
273
+ function schemaOf(cat) { return SCHEMAS[cat] || SCHEMAS.account; }
274
+ function isSecretField(f) { return f.type === 'secret' || f.type === 'secretarea'; }
275
+ function isMultilineField(f) { return f.type === 'secretarea' || f.type === 'textarea'; }
276
+
277
+ var CSS = [
278
+ '.cv-root{--cv-bg:var(--dsw-alias-bg-base,#fff);--cv-l1:var(--dsw-alias-bg-layer-1,#f6f7f9);--cv-l2:var(--dsw-alias-bg-layer-2,#eceef3);--cv-b1:var(--dsw-alias-border-l1,#e2e5eb);--cv-b2:var(--dsw-alias-border-l2,#c9cfd9);--cv-brand:var(--dsw-alias-brand-primary,#2563eb);--cv-t1:var(--dsw-alias-label-primary,#1d2129);--cv-t2:var(--dsw-alias-label-secondary,#6b7280);--cv-err:var(--dsw-alias-state-error-primary,#dc2626);--cv-ok:var(--dsw-alias-state-success-primary,#16a34a);color:var(--cv-t1);background:var(--cv-bg);font-family:inherit;font-size:14px;min-height:100%;box-sizing:border-box;position:relative}',
279
+ '.cv-root *{box-sizing:border-box}',
280
+ '.cv-wrap{max-width:940px;margin:0 auto;padding:28px 26px 60px}',
281
+ '.cv-head{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap}',
282
+ '.cv-head-left{display:flex;align-items:center;gap:14px}',
283
+ '.cv-head-icon{width:52px;height:52px;border-radius:14px;display:flex;align-items:center;justify-content:center;background:var(--cv-l1);border:1px solid var(--cv-b1)}',
284
+ '.cv-title{margin:0;font-size:21px;font-weight:650;letter-spacing:.2px}',
285
+ '.cv-sub{margin:3px 0 0;color:var(--cv-t2);font-size:13px}',
286
+ '.cv-notice{margin-top:18px;padding:10px 14px;border-radius:10px;background:var(--cv-l1);border:1px solid var(--cv-b1);color:var(--cv-t2);font-size:12.5px;line-height:1.6}',
287
+ '.cv-toolbar{margin-top:18px;display:flex;align-items:center;gap:12px;flex-wrap:wrap}',
288
+ '.cv-search{flex:1;min-width:220px;padding:9px 13px;border-radius:9px;border:1px solid var(--cv-b1);background:var(--cv-l1);color:var(--cv-t1);font-size:13px;outline:none}',
289
+ '.cv-search:focus{border-color:var(--cv-brand)}',
290
+ '.cv-chips{display:flex;gap:6px;flex-wrap:wrap}',
291
+ '.cv-chip{padding:7px 12px;border-radius:999px;border:1px solid var(--cv-b1);background:transparent;color:var(--cv-t2);font-size:12.5px;cursor:pointer;transition:background .16s,color .16s,border-color .16s,box-shadow .16s}',
292
+ '.cv-chip:active{transform:scale(.97)}',
293
+ '.cv-chip:hover{background:var(--cv-l2);color:var(--cv-t1)}',
294
+ '.cv-chip-on{background:var(--cv-brand);border-color:var(--cv-brand);color:var(--cv-bg)}',
295
+ '.cv-chip-on:hover{background:var(--cv-brand);border-color:var(--cv-brand);color:var(--cv-bg);box-shadow:0 2px 8px rgba(0,0,0,.18)}',
296
+ '.cv-reveal{display:flex;gap:6px;margin-left:auto}',
297
+ '.cv-sort{display:flex;align-items:center;gap:6px}',
298
+ '.cv-sort-label{color:var(--cv-t2);font-size:12px}',
299
+ '.cv-select{padding:7px 10px;border-radius:8px;border:1px solid var(--cv-b1);background:var(--cv-l1);color:var(--cv-t1);font-size:12.5px;cursor:pointer;outline:none}',
300
+ '.cv-select:focus{border-color:var(--cv-brand)}',
301
+ '.cv-btn{padding:9px 16px;border-radius:9px;border:1px solid var(--cv-b1);background:var(--cv-l1);color:var(--cv-t1);font-size:13px;font-weight:550;cursor:pointer;transition:background .16s,color .16s,border-color .16s,box-shadow .16s,transform .1s}',
302
+ '.cv-btn:hover{background:var(--cv-l2);color:var(--cv-t1);border-color:var(--cv-b2)}',
303
+ '.cv-btn:active{transform:translateY(1px) scale(.98);background:var(--cv-b1)}',
304
+ '.cv-btn-primary{background:var(--cv-brand);border-color:var(--cv-brand);color:var(--cv-bg)}',
305
+ '.cv-btn-primary:hover{background:var(--cv-brand);border-color:var(--cv-brand);color:var(--cv-bg);box-shadow:0 3px 12px rgba(0,0,0,.2)}',
306
+ '.cv-btn-primary:active{transform:translateY(1px) scale(.98);box-shadow:0 1px 4px rgba(0,0,0,.18)}',
307
+ '.cv-btn:disabled{opacity:.55;cursor:not-allowed;transform:none;box-shadow:none}',
308
+ '.cv-io{display:flex;gap:8px;align-items:center}',
309
+ '.cv-import-file{margin:4px 22px 0;padding:10px 12px;border-radius:9px;background:var(--cv-l1);border:1px solid var(--cv-b1);font-size:12.5px;color:var(--cv-t1);overflow-wrap:anywhere}',
310
+ '.cv-import-modes{display:flex;flex-direction:column;gap:10px}',
311
+ '.cv-import-opt{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border:1px solid var(--cv-b1);border-radius:9px;cursor:pointer;background:var(--cv-l1)}',
312
+ '.cv-import-opt input{margin-top:2px;accent-color:var(--cv-brand)}',
313
+ '.cv-import-opt-name{font-size:13px;font-weight:550;color:var(--cv-t1)}',
314
+ '.cv-import-opt-hint{font-size:12px;color:var(--cv-t2);margin-top:3px;line-height:1.45}',
315
+ '.cv-import-warn{color:var(--cv-err);font-weight:550}',
316
+ '.cv-mini{padding:4px 9px;border-radius:7px;border:1px solid var(--cv-b1);background:var(--cv-l1);color:var(--cv-t2);font-size:11.5px;cursor:pointer;white-space:nowrap;transition:background .16s,color .16s,border-color .16s,transform .1s}',
317
+ '.cv-mini:hover{color:var(--cv-t1);background:var(--cv-l2);border-color:var(--cv-b2)}',
318
+ '.cv-mini:active{transform:scale(.95);background:var(--cv-b1)}',
319
+ '.cv-count{margin:16px 2px 10px;color:var(--cv-t2);font-size:12.5px}',
320
+ '.cv-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:14px}',
321
+ '.cv-list-scroll{max-height:62vh;min-height:160px;overflow-y:auto;overflow-x:hidden;margin-top:4px;padding-right:6px;scrollbar-width:thin;scrollbar-color:var(--cv-b2) transparent}',
322
+ '.cv-list-scroll::-webkit-scrollbar{width:9px}',
323
+ '.cv-list-scroll::-webkit-scrollbar-track{background:transparent}',
324
+ '.cv-list-scroll::-webkit-scrollbar-thumb{background:var(--cv-b2);border-radius:8px;border:2px solid var(--cv-bg)}',
325
+ '.cv-list-scroll::-webkit-scrollbar-thumb:hover{background:var(--cv-t2)}',
326
+ '.cv-card{background:var(--cv-l1);border:1px solid var(--cv-b1);border-radius:12px;padding:14px 16px}',
327
+ '.cv-card-head{display:flex;align-items:center;gap:9px;border-bottom:1px solid var(--cv-b1);padding-bottom:10px;margin-bottom:8px}',
328
+ '.cv-badge{font-size:10.5px;font-weight:650;padding:3px 8px;border-radius:6px;white-space:nowrap;background:var(--cv-l2);color:var(--cv-t2)}',
329
+ '.cv-badge-apikey{background:var(--cv-brand);color:var(--cv-bg)}',
330
+ '.cv-badge-account{color:var(--cv-brand)}',
331
+ '.cv-badge-other{background:var(--cv-l2);color:var(--cv-t2)}',
332
+ '.cv-card-title{font-weight:600;font-size:14.5px;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
333
+ '.cv-card-actions{display:flex;gap:4px}',
334
+ '.cv-icon-btn{width:28px;height:28px;border-radius:7px;border:1px solid transparent;background:transparent;color:var(--cv-t2);cursor:pointer;font-size:14px;line-height:1;display:flex;align-items:center;justify-content:center}',
335
+ '.cv-icon-btn:hover{background:var(--cv-l2);color:var(--cv-t1)}',
336
+ '.cv-icon-btn.cv-danger:hover{background:var(--cv-l2);color:var(--cv-err)}',
337
+ '.cv-field{margin:7px 0}',
338
+ '.cv-field-label{font-size:11px;color:var(--cv-t2);margin-bottom:3px;text-transform:uppercase;letter-spacing:.4px}',
339
+ '.cv-field-row{display:flex;align-items:flex-start;gap:6px}',
340
+ '.cv-field-value{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;color:var(--cv-t1)}',
341
+ '.cv-field-multiline{white-space:pre-wrap;overflow-wrap:anywhere;max-height:110px;overflow:auto;line-height:1.5}',
342
+ '.cv-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12.5px;letter-spacing:.3px}',
343
+ '.cv-masked{letter-spacing:2px;color:var(--cv-t2)}',
344
+ '.cv-empty{grid-column:1/-1;text-align:center;padding:60px 20px;color:var(--cv-t2)}',
345
+ '.cv-empty-icon{display:inline-flex;color:var(--cv-b2);margin-bottom:12px}',
346
+ '.cv-empty h3{margin:0 0 6px;color:var(--cv-t1);font-size:16px}',
347
+ '.cv-empty p{margin:0;font-size:13px}',
348
+ '.cv-modal-backdrop{position:absolute;inset:0;background:rgba(0,0,0,.2);display:flex;align-items:flex-start;justify-content:center;z-index:9999;padding:20px}',
349
+ '.cv-modal{position:sticky;top:50vh;transform:translateY(-50%);width:fit-content;max-width:500px;min-width:320px;max-height:90vh;overflow:auto;background:var(--cv-bg);border:1px solid var(--cv-b1);border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,.28);outline:none}',
350
+ '.cv-modal.cv-modal-editor{min-width:500px;max-width:800px}',
351
+ '.cv-settings .cv-modal{max-width:100%;min-width:0}',
352
+ // Sidebar panel only: modals are positioned relative to the panel itself
353
+ // (flex-centered inside .cv-root) — the settings-page sticky float is untouched.
354
+ '.cv-panelroot>.cv-modal-backdrop{align-items:center}',
355
+ '.cv-panelroot .cv-modal{position:relative;top:auto;transform:none;min-width:0;max-width:100%;max-height:min(88vh,100%)}',
356
+ '.cv-modal-head{padding:18px 22px 0}',
357
+ '.cv-modal-head h2{margin:0;font-size:17px;font-weight:650}',
358
+ '.cv-modal-hint{margin:5px 22px 0;padding:8px 11px;border-radius:8px;background:var(--cv-l1);border:1px solid var(--cv-b1);color:var(--cv-t2);font-size:12px;line-height:1.5}',
359
+ '.cv-modal-body{padding:14px 22px 6px;display:flex;flex-direction:column;gap:12px}',
360
+ '.cv-form-row{display:flex;flex-direction:column;gap:5px}',
361
+ '.cv-form-label{font-size:12px;color:var(--cv-t2)}',
362
+ '.cv-input{width:100%;padding:9px 11px;border-radius:9px;border:1px solid var(--cv-b1);background:var(--cv-l1);color:var(--cv-t1);font-size:13px;outline:none;font-family:inherit}',
363
+ '.cv-input:focus{border-color:var(--cv-brand)}',
364
+ '.cv-textarea{min-height:64px;resize:vertical}',
365
+ '.cv-secret-input{display:flex;gap:6px;align-items:stretch}',
366
+ '.cv-secret-input .cv-input{flex:1;min-width:0}',
367
+ '.cv-secret-toggle{flex:none;display:inline-flex;align-items:center;justify-content:center;padding:0 13px;border:1px solid var(--cv-b1);border-radius:9px;background:var(--cv-l1);color:var(--cv-t2);font-size:13px;font-family:inherit;cursor:pointer;white-space:nowrap}',
368
+ '.cv-secret-toggle:hover{background:var(--cv-l2);color:var(--cv-t1)}',
369
+ '.cv-text-security{-webkit-text-security:disc}',
370
+ '.cv-modal-foot{display:flex;justify-content:flex-end;gap:10px;padding:16px 22px 20px}',
371
+ '.cv-toast{position:fixed;top:18px;left:50%;transform:translateX(-50%);background:var(--cv-t1);color:var(--cv-bg);padding:12px 22px;border-radius:12px;font-size:14px;font-weight:600;z-index:10000;box-shadow:0 12px 32px rgba(0,0,0,.3);animation:cv-toast-in .18s ease-out}',
372
+ '@keyframes cv-toast-in{from{opacity:0;transform:translateX(-50%) translateY(-10px)}to{opacity:1;transform:translateX(-50%) translateY(0)}}',
373
+ '.cv-lock{min-height:100%;display:flex;align-items:center;justify-content:center;padding:60px 20px}',
374
+ '.cv-lock-card{width:100%;max-width:400px;background:var(--cv-l1);border:1px solid var(--cv-b1);border-radius:18px;padding:32px 30px;text-align:center;box-shadow:0 12px 40px rgba(0,0,0,.12)}',
375
+ '.cv-lock-icon{display:inline-flex;color:var(--cv-brand);margin-bottom:14px}',
376
+ '.cv-lock-card h2{margin:0 0 6px;font-size:19px;font-weight:650}',
377
+ '.cv-lock-card p{margin:0 0 22px;color:var(--cv-t2);font-size:13px;line-height:1.5}',
378
+ '.cv-lock-form{display:flex;flex-direction:column;gap:12px;text-align:left}',
379
+ '.cv-lock-form .cv-input{text-align:left}',
380
+ '.cv-lock-actions{display:flex;flex-direction:column;gap:10px;margin-top:6px}',
381
+ '.cv-lock-actions .cv-btn-primary{width:100%}',
382
+ '.cv-link{background:none;border:none;padding:0;color:var(--cv-brand);font-size:12.5px;cursor:pointer;text-decoration:underline;font-family:inherit}',
383
+ '.cv-link:hover{opacity:.8}',
384
+ '.cv-lock-foot{margin-top:16px;color:var(--cv-t2);font-size:11px;line-height:1.5}',
385
+ '.cv-settings{max-width:820px;margin:0 auto;padding:28px 26px 60px;position:relative}',
386
+ '.cv-settings-head{margin-bottom:8px}',
387
+ '.cv-settings-head h2{margin:0;font-size:18px;font-weight:650}',
388
+ '.cv-settings-head p{margin:5px 0 0;color:var(--cv-t2);font-size:13px;line-height:1.5}',
389
+ '.cv-settings-card{margin-top:20px;background:var(--cv-l1);border:1px solid var(--cv-b1);border-radius:12px;padding:18px 20px}',
390
+ '.cv-settings-card h3{margin:0 0 4px;font-size:15px;font-weight:620}',
391
+ '.cv-settings-card .cv-card-sub{margin:0 0 16px;color:var(--cv-t2);font-size:12.5px;line-height:1.5}',
392
+ '.cv-update-row{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}',
393
+ '.cv-update-row .cv-form-label{color:var(--cv-t1);font-size:13px}',
394
+ '.cv-upgrade-status{margin-top:10px;font-size:12.5px;color:var(--cv-t2);line-height:1.6}',
395
+ '.cv-upgrade-status.cv-ok{color:var(--cv-ok)}',
396
+ '.cv-upgrade-status.cv-err{color:var(--cv-err)}',
397
+ '.cv-switch-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 0;border-top:1px solid var(--cv-b1)}',
398
+ '.cv-switch-row:first-of-type{border-top:none}',
399
+ '.cv-switch-label{font-size:13.5px;font-weight:550}',
400
+ '.cv-switch-hint{font-size:12px;color:var(--cv-t2);margin-top:3px;line-height:1.4}',
401
+ '.cv-switch{position:relative;width:44px;height:25px;flex:none;border-radius:999px;border:1px solid var(--cv-b2);background:var(--cv-l2);cursor:pointer;transition:background .15s,border-color .15s;padding:0}',
402
+ '.cv-switch[aria-checked="true"]{background:var(--cv-brand);border-color:var(--cv-brand)}',
403
+ '.cv-switch-knob{position:absolute;top:2px;left:2px;width:19px;height:19px;border-radius:50%;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.3);transition:transform .15s}',
404
+ '.cv-switch[aria-checked="true"] .cv-switch-knob{transform:translateX(19px)}',
405
+ '.cv-status{margin-top:12px;font-size:12.5px;color:var(--cv-ok)}',
406
+ '.cv-note{margin-top:10px;padding:9px 12px;border-radius:9px;font-size:13px;font-weight:550;display:flex;gap:8px;align-items:flex-start;animation:cv-note-in .18s ease-out}',
407
+ '.cv-note-ok{background:rgba(34,197,94,.12);color:var(--cv-ok);border:1px solid rgba(34,197,94,.4)}',
408
+ '.cv-note-err{background:rgba(239,68,68,.12);color:var(--cv-err);border:1px solid rgba(239,68,68,.4)}',
409
+ '@keyframes cv-note-in{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}',
410
+ '.cv-field-error{color:var(--cv-err);font-size:12px;margin-top:2px}',
411
+ '.cv-settings-fields{display:flex;flex-direction:column;gap:12px;margin-top:12px}',
412
+ // Password generator
413
+ '.cv-gen-secret{display:flex;gap:6px;align-items:stretch}',
414
+ '.cv-gen-secret .cv-input{flex:1;min-width:0}',
415
+ '.cv-gen-btn{flex:none;padding:0 12px;border:1px solid var(--cv-b1);border-radius:9px;background:var(--cv-l1);color:var(--cv-brand);font-size:12.5px;font-family:inherit;cursor:pointer;white-space:nowrap;transition:background .16s,border-color .16s,transform .1s}',
416
+ '.cv-gen-btn:hover{background:var(--cv-l2);color:var(--cv-brand)}',
417
+ '.cv-gen-btn:active{transform:scale(.95);background:var(--cv-b1)}',
418
+ '.cv-gen-preview{margin-top:6px;padding:12px 14px;border-radius:10px;background:var(--cv-l1);border:1px solid var(--cv-b1);font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:15px;letter-spacing:.5px;overflow-wrap:anywhere;user-select:all}',
419
+ '.cv-gen-opts{display:grid;grid-template-columns:1fr 1fr;gap:8px 14px}',
420
+ '.cv-gen-check{display:flex;align-items:center;gap:7px;font-size:12.5px;color:var(--cv-t1);cursor:pointer}',
421
+ '.cv-gen-check input{accent-color:var(--cv-brand);margin:0}',
422
+ '.cv-gen-strength{font-weight:650}',
423
+ '.cv-gen-strength.cv-weak{color:var(--cv-err)}',
424
+ '.cv-gen-strength.cv-fair{color:#b45309}',
425
+ '.cv-gen-strength.cv-strong{color:var(--cv-ok)}',
426
+ '.cv-gen-bar{height:5px;border-radius:4px;background:var(--cv-l2);margin-top:5px;overflow:hidden}',
427
+ '.cv-gen-bar span{display:block;height:100%;border-radius:4px;transition:width .2s}',
428
+ '.cv-gen-bar .cv-weak{background:var(--cv-err)}',
429
+ '.cv-gen-bar .cv-fair{background:#b45309}',
430
+ '.cv-gen-bar .cv-strong{background:var(--cv-ok)}',
431
+ // Security audit
432
+ '.cv-audit-summary{display:flex;gap:18px;flex-wrap:wrap;padding:12px 14px;border-radius:10px;background:var(--cv-l1);border:1px solid var(--cv-b1);font-size:13px}',
433
+ '.cv-audit-summary b{font-size:16px;color:var(--cv-t1)}',
434
+ '.cv-audit-clean{padding:20px;text-align:center;color:var(--cv-ok);font-size:13.5px;font-weight:550}',
435
+ '.cv-audit-list{margin-top:6px;display:flex;flex-direction:column;gap:8px;max-height:46vh;overflow-y:auto;scrollbar-width:thin}',
436
+ '.cv-audit-item{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border:1px solid var(--cv-b1);border-radius:9px;background:var(--cv-l1)}',
437
+ '.cv-audit-sev{flex:none;font-size:10.5px;font-weight:650;padding:2px 7px;border-radius:6px;white-space:nowrap;align-self:center}',
438
+ '.cv-audit-sev.cv-high{background:var(--cv-err);color:#fff}',
439
+ '.cv-audit-sev.cv-medium{background:#b45309;color:#fff}',
440
+ '.cv-audit-sev.cv-low{background:var(--cv-brand);color:#fff}',
441
+ '.cv-audit-body{flex:1;min-width:0}',
442
+ '.cv-audit-name{font-size:13px;font-weight:600;color:var(--cv-t1);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
443
+ '.cv-audit-desc{font-size:12px;color:var(--cv-t2);margin-top:2px;line-height:1.4}',
444
+ '.cv-audit-note{margin:12px 22px 0;font-size:11.5px;color:var(--cv-t2);line-height:1.5}'
445
+ ].join('\n');
446
+
447
+ // Migrate entries saved by the earlier single-form version.
448
+ function normalize(e) {
449
+ var n = Object.assign({}, e);
450
+ n.category = n.category || 'account';
451
+ if (n.secret != null && n.password == null && n.apiKey == null && n.content == null) {
452
+ if (n.category === 'apikey') n.apiKey = n.secret;
453
+ else if (n.category === 'other') n.content = n.secret;
454
+ else n.password = n.secret;
455
+ }
456
+ if (n.category === 'apikey') {
457
+ if (n.provider == null && n.username) n.provider = n.username;
458
+ if (n.endpoint == null && n.url) n.endpoint = n.url;
459
+ }
460
+ return n;
461
+ }
462
+ function loadEntries() {
463
+ try {
464
+ var raw = window.localStorage.getItem(STORAGE_KEY);
465
+ if (!raw) {
466
+ // One-time migration from the pre-rename storage key.
467
+ raw = window.localStorage.getItem(STORAGE_KEY_LEGACY);
468
+ if (raw) { try { window.localStorage.setItem(STORAGE_KEY, raw); } catch (e) {} }
469
+ }
470
+ if (!raw) return [];
471
+ var arr = JSON.parse(raw);
472
+ return Array.isArray(arr) ? arr.map(normalize) : [];
473
+ } catch (e) { return []; }
474
+ }
475
+ function saveEntries(arr) {
476
+ try { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(arr)); } catch (e) {}
477
+ syncToHost(arr);
478
+ }
479
+ // Mirror the vault to the Host so the Harness/Agent can read it via the
480
+ // dsh_credential_vault_read tool. Fire-and-forget: the browser stays usable
481
+ // even if the Host route is unavailable; localStorage is still authoritative.
482
+ // Large vaults: DEBOUNCE so a burst of edits results in one POST, not dozens
483
+ // of multi-megabyte payloads. A trailing timer always flushes the latest data.
484
+ var syncTimer = null;
485
+ var SYNC_DELAY = 400;
486
+ function syncToHost(arr, immediate) {
487
+ if (typeof window.fetch !== 'function') return;
488
+ function send() {
489
+ syncTimer = null;
490
+ try {
491
+ window.fetch(API + 'entries', {
492
+ method: 'POST',
493
+ credentials: 'same-origin',
494
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
495
+ body: JSON.stringify({ entries: arr })
496
+ }).catch(function () {});
497
+ } catch (e) {}
498
+ }
499
+ if (syncTimer !== null) { window.clearTimeout(syncTimer); syncTimer = null; }
500
+ if (immediate) { send(); return; }
501
+ syncTimer = window.setTimeout(send, SYNC_DELAY);
502
+ }
503
+ function uid() {
504
+ return Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
505
+ }
506
+
507
+ // ---- Password generator ---------------------------------------------
508
+ var GEN_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
509
+ var GEN_LOWER = 'abcdefghijklmnopqrstuvwxyz';
510
+ var GEN_DIGITS = '0123456789';
511
+ var GEN_SYMBOLS = '!@#$%^&*()-_=+[]{};:,.?/';
512
+ var GEN_AMBIGUOUS = '0O1lI|`\'\";:';
513
+ // Uniform random integer in [0, max) using rejection sampling, so every
514
+ // character is equally likely (no modulo bias).
515
+ function secureRandomInt(max) {
516
+ var crypto = (typeof window !== 'undefined' && window.crypto) || (typeof globalThis !== 'undefined' && globalThis.crypto);
517
+ if (!crypto || !crypto.getRandomValues) throw new Error('no-crypto');
518
+ var limit = Math.floor(4294967296 / max) * max; // 2^32 rounded down to a multiple of max
519
+ var buf = new Uint32Array(1);
520
+ var v;
521
+ do { crypto.getRandomValues(buf); v = buf[0]; } while (v >= limit);
522
+ return v % max;
523
+ }
524
+ function shuffleChars(arr) {
525
+ for (var i = arr.length - 1; i > 0; i--) {
526
+ var j = secureRandomInt(i + 1);
527
+ var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
528
+ }
529
+ return arr;
530
+ }
531
+ // opts: {length, upper, lower, digits, symbols, avoidAmbiguous}
532
+ function generatePassword(opts) {
533
+ var sets = [];
534
+ if (opts.upper) sets.push(GEN_UPPER);
535
+ if (opts.lower) sets.push(GEN_LOWER);
536
+ if (opts.digits) sets.push(GEN_DIGITS);
537
+ if (opts.symbols) sets.push(GEN_SYMBOLS);
538
+ if (sets.length === 0) return null;
539
+ var pool = sets.join('');
540
+ if (opts.avoidAmbiguous) {
541
+ pool = pool.split('').filter(function (c) { return GEN_AMBIGUOUS.indexOf(c) === -1; }).join('');
542
+ }
543
+ if (!pool) return null;
544
+ var len = Math.max(4, Math.min(128, Number(opts.length) || 16));
545
+ var out = [];
546
+ // Guarantee at least one character from every selected class.
547
+ sets.forEach(function (set) {
548
+ var s = opts.avoidAmbiguous ? set.split('').filter(function (c) { return GEN_AMBIGUOUS.indexOf(c) === -1; }).join('') : set;
549
+ if (s) out.push(s[secureRandomInt(s.length)]);
550
+ });
551
+ while (out.length < len) out.push(pool[secureRandomInt(pool.length)]);
552
+ return shuffleChars(out.slice(0, len)).join('');
553
+ }
554
+ // Entropy estimate in bits -> strength tier.
555
+ function passwordStrength(pw) {
556
+ if (!pw) return { tier: 'weak', bits: 0 };
557
+ var pool = 0;
558
+ if (/[a-z]/.test(pw)) pool += 26;
559
+ if (/[A-Z]/.test(pw)) pool += 26;
560
+ if (/[0-9]/.test(pw)) pool += 10;
561
+ if (/[^A-Za-z0-9]/.test(pw)) pool += 28;
562
+ if (!pool) pool = 10;
563
+ var bits = Math.round(pw.length * (Math.log(pool) / Math.LN2));
564
+ var tier = bits < 45 ? 'weak' : (bits < 65 ? 'fair' : 'strong');
565
+ return { tier: tier, bits: bits };
566
+ }
567
+
568
+ // ---- Security audit --------------------------------------------------
569
+ function secretOf(e) {
570
+ var cat = e.category || 'account';
571
+ if (cat === 'apikey') return String(e.apiKey || '');
572
+ if (cat === 'other') return String(e.content || '');
573
+ return String(e.password || '');
574
+ }
575
+ function runAudit(entries) {
576
+ var issues = [];
577
+ var bySecret = {};
578
+ // Count reuse of non-empty secrets across entries.
579
+ entries.forEach(function (e) {
580
+ var s = secretOf(e);
581
+ if (!s) return;
582
+ (bySecret[s] = bySecret[s] || []).push(e.id);
583
+ });
584
+ var now = Date.now();
585
+ var DAY = 24 * 60 * 60 * 1000;
586
+ entries.forEach(function (e) {
587
+ var cat = e.category || 'account';
588
+ var s = secretOf(e);
589
+ var name = e.title || '—';
590
+ function add(kind, sev) {
591
+ issues.push({ id: e.id, name: name, category: cat, kind: kind, severity: sev });
592
+ }
593
+ if (!s) { add('auditEmpty', 'high'); return; }
594
+ // Weak: short, or only a single character class with length < 12.
595
+ if (s.length < 8 || passwordStrength(s).tier === 'weak') add('auditWeak', s.length < 6 ? 'high' : 'medium');
596
+ // Reused secret (appears in more than one distinct entry).
597
+ if (bySecret[s] && bySecret[s].length > 1) add('auditReused', 'high');
598
+ // Expiry checks for API keys.
599
+ if (e.expiry) {
600
+ var t = Date.parse(e.expiry);
601
+ if (!isNaN(t)) {
602
+ if (t < now) add('auditExpired', 'medium');
603
+ else if (t - now < 30 * DAY) add('auditExpiring', 'low');
604
+ }
605
+ }
606
+ });
607
+ var order = { high: 0, medium: 1, low: 2 };
608
+ issues.sort(function (a, b) { return order[a.severity] - order[b.severity]; });
609
+ return { scanned: entries.length, issues: issues };
610
+ }
611
+
612
+ // ---- Backup: export / import ----------------------------------------
613
+ // The backup is a plain JSON file so it is portable. It deliberately
614
+ // contains the real secret values (masked data would be useless to restore).
615
+ var BACKUP_FORMAT = 'dsh-credential-vault-backup';
616
+ var BACKUP_VERSION = 1;
617
+ function buildBackup(arr) {
618
+ return {
619
+ format: BACKUP_FORMAT,
620
+ version: BACKUP_VERSION,
621
+ exportedAt: new Date().toISOString(),
622
+ app: 'dsh-credential-vault',
623
+ entries: arr.map(function (e) { return normalize(e); })
624
+ };
625
+ }
626
+ function exportBackup(arr) {
627
+ if (!arr || arr.length === 0) return false;
628
+ try {
629
+ var payload = JSON.stringify(buildBackup(arr), null, 2);
630
+ var blob = new Blob([payload], { type: 'application/json;charset=utf-8' });
631
+ var url = URL.createObjectURL(blob);
632
+ var a = document.createElement('a');
633
+ var d = new Date();
634
+ function pad(n) { return n < 10 ? '0' + n : '' + n; }
635
+ var stamp = d.getFullYear() + pad(d.getMonth() + 1) + pad(d.getDate()) + '-' + pad(d.getHours()) + pad(d.getMinutes());
636
+ a.href = url;
637
+ a.download = '凭据保险箱-' + stamp + '.json';
638
+ document.body.appendChild(a);
639
+ a.click();
640
+ document.body.removeChild(a);
641
+ setTimeout(function () { try { URL.revokeObjectURL(url); } catch (e) {} }, 1000);
642
+ return true;
643
+ } catch (e) { return false; }
644
+ }
645
+ // Returns { entries: [...] } or throws a recognisable error.
646
+ function parseBackup(text) {
647
+ var data;
648
+ try { data = JSON.parse(text); } catch (e) { throw new Error('parse'); }
649
+ var arr = null;
650
+ if (data && Array.isArray(data.entries)) arr = data.entries;
651
+ else if (Array.isArray(data)) arr = data; // tolerate a bare array
652
+ if (!arr) throw new Error('shape');
653
+ var clean = arr.filter(function (e) { return e && typeof e === 'object'; }).map(normalize);
654
+ return clean;
655
+ }
656
+
657
+ // ---- Access-password security store ---------------------------------
658
+ var SEC_KEY = '@local/dsh-credential-vault:security:v1';
659
+ var SEC_KEY_LEGACY = '@local/credential-vault:security:v1';
660
+ var IDLE_MS = 15 * 60 * 1000; // fallback duration when idleMs is absent
661
+ var DEFAULT_SECURITY = { enabled: false, salt: '', passwordHash: null, question: null, answerHash: null, idleEnabled: false, idleMs: IDLE_MS };
662
+ var securityCache = null;
663
+ var securityListeners = [];
664
+ var unlockedAt = 0; // 0 = locked; timestamp = last successful unlock
665
+
666
+ function loadSecurity() {
667
+ try {
668
+ var raw = window.localStorage.getItem(SEC_KEY);
669
+ if (!raw) {
670
+ // One-time migration from the pre-rename storage key.
671
+ raw = window.localStorage.getItem(SEC_KEY_LEGACY);
672
+ if (raw) { try { window.localStorage.setItem(SEC_KEY, raw); } catch (e) {} }
673
+ }
674
+ if (!raw) return Object.assign({}, DEFAULT_SECURITY);
675
+ var s = JSON.parse(raw);
676
+ return Object.assign({}, DEFAULT_SECURITY, s || {});
677
+ } catch (e) { return Object.assign({}, DEFAULT_SECURITY); }
678
+ }
679
+ function getSecurity() {
680
+ if (!securityCache) securityCache = loadSecurity();
681
+ return securityCache;
682
+ }
683
+ function saveSecurity(s) {
684
+ securityCache = s;
685
+ try { window.localStorage.setItem(SEC_KEY, JSON.stringify(s)); } catch (e) {}
686
+ securityListeners.forEach(function (fn) { try { fn(); } catch (e) {} });
687
+ }
688
+ function subscribeSecurity(fn) {
689
+ securityListeners.push(fn);
690
+ return function () {
691
+ var i = securityListeners.indexOf(fn);
692
+ if (i >= 0) securityListeners.splice(i, 1);
693
+ };
694
+ }
695
+ function makeSalt() {
696
+ try {
697
+ var bytes = new Uint8Array(16);
698
+ window.crypto.getRandomValues(bytes);
699
+ var out = '';
700
+ for (var i = 0; i < bytes.length; i++) out += ('0' + bytes[i].toString(16)).slice(-2);
701
+ return out;
702
+ } catch (e) {
703
+ return Date.now().toString(36) + Math.random().toString(36).slice(2);
704
+ }
705
+ }
706
+ function simpleHash(s) {
707
+ var h = 5381;
708
+ for (var i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0;
709
+ return (h >>> 0).toString(16);
710
+ }
711
+ function hashValue(text) {
712
+ try {
713
+ if (window.crypto && window.crypto.subtle && window.crypto.subtle.digest && typeof TextEncoder !== 'undefined') {
714
+ var data = new TextEncoder().encode(String(text));
715
+ return window.crypto.subtle.digest('SHA-256', data).then(function (buf) {
716
+ var bytes = new Uint8Array(buf), out = '';
717
+ for (var i = 0; i < bytes.length; i++) out += ('0' + bytes[i].toString(16)).slice(-2);
718
+ return 'sha256$' + out;
719
+ }).catch(function () { return 'simple$' + simpleHash(text); });
720
+ }
721
+ } catch (e) {}
722
+ return Promise.resolve('simple$' + simpleHash(text));
723
+ }
724
+ function hashWithSalt(salt, value) { return hashValue(salt + ':' + value); }
725
+ function normalizeAnswer(s) { return String(s == null ? '' : s).trim().toLowerCase(); }
726
+ function verifyPassword(sec, input) {
727
+ if (!sec || !sec.passwordHash) return Promise.resolve(false);
728
+ return hashWithSalt(sec.salt, input).then(function (h) { return h === sec.passwordHash; });
729
+ }
730
+ function verifyAnswer(sec, input) {
731
+ if (!sec || !sec.answerHash) return Promise.resolve(false);
732
+ return hashWithSalt(sec.salt, normalizeAnswer(input)).then(function (h) { return h === sec.answerHash; });
733
+ }
734
+ function isVaultLocked() {
735
+ var sec = getSecurity();
736
+ if (!sec.enabled) return false;
737
+ if (!unlockedAt) return true;
738
+ // Auto-lock only when the feature is on; otherwise an unlocked vault stays unlocked.
739
+ if (sec.idleEnabled) {
740
+ var limit = sec.idleMs || IDLE_MS;
741
+ if (Date.now() - unlockedAt > limit) { unlockedAt = 0; return true; }
742
+ }
743
+ return false;
744
+ }
745
+ function markUnlocked() { unlockedAt = Date.now(); }
746
+ function lockVault() { unlockedAt = 0; }
747
+ function noteActivity() {
748
+ var sec = getSecurity();
749
+ if (sec.enabled && sec.idleEnabled && unlockedAt) unlockedAt = Date.now();
750
+ }
751
+ function hasSetup() {
752
+ var sec = getSecurity();
753
+ return !!(sec.passwordHash && sec.question && sec.answerHash);
754
+ }
755
+ var SECURITY_QUESTIONS = [
756
+ { k: 'pet', en: 'What was the name of your first pet?', zh: '你第一只宠物的名字是什么?' },
757
+ { k: 'school', en: 'What was the name of your primary school?', zh: '你就读的第一所学校叫什么名字?' },
758
+ { k: 'city', en: 'In which city were you born?', zh: '你在哪个城市出生?' },
759
+ { k: 'mother', en: 'What is your mother’s maiden name?', zh: '你母亲的姓名是什么?' },
760
+ { k: 'custom', en: 'Custom question…', zh: '自定义问题…' }
761
+ ];
762
+
763
+ function detectLang(svc) {
764
+ if (svc) {
765
+ try {
766
+ var snap = typeof svc.getLocale === 'function' ? svc.getLocale()
767
+ : (typeof svc.getSnapshot === 'function' ? svc.getSnapshot() : null);
768
+ if (snap) {
769
+ var id = snap.id || snap.locale || snap.lang || snap.language || (typeof snap === 'string' ? snap : null);
770
+ if (id) return String(id).toLowerCase().indexOf('zh') === 0 ? 'zh' : 'en';
771
+ }
772
+ } catch (e) {}
773
+ }
774
+ try { return String(navigator.language || '').toLowerCase().indexOf('zh') === 0 ? 'zh' : 'en'; }
775
+ catch (e) { return 'en'; }
776
+ }
777
+ function searchText(e) {
778
+ var parts = [e.title || ''];
779
+ schemaOf(e.category).forEach(function (f) {
780
+ if (f.key === 'title' || isSecretField(f)) return;
781
+ if (e[f.key]) parts.push(e[f.key]);
782
+ });
783
+ return parts.join(' ').toLowerCase();
784
+ }
785
+ function emptyDraft(cat) {
786
+ return {
787
+ id: '', title: '', category: cat || 'account',
788
+ username: '', password: '', url: '',
789
+ provider: '', apiKey: '', endpoint: '', expiry: '',
790
+ content: '', notes: ''
791
+ };
792
+ }
793
+
794
+ var layout = null, locale = null, lang0 = 'en';
795
+ var sidebarRight = null, ctxRef = null;
796
+ function tr(k) { return (DICTS[lang0] && DICTS[lang0][k]) || DICTS.en[k] || k; }
797
+
798
+ function Shield(size) {
799
+ var s = size || 20;
800
+ return h('svg', { viewBox: '0 0 64 64', width: s, height: s, 'aria-hidden': true, style: { display: 'block' } },
801
+ h('path', { d: 'M32 6 L52 13 V30 C52 43 43 52 32 58 C21 52 12 43 12 30 V13 Z', fill: 'currentColor', opacity: 0.14 }),
802
+ h('path', { d: 'M32 6 L52 13 V30 C52 43 43 52 32 58 C21 52 12 43 12 30 V13 Z', fill: 'none', stroke: 'currentColor', strokeWidth: 3, strokeLinejoin: 'round' }),
803
+ h('circle', { cx: 32, cy: 27, r: 4.6, fill: 'currentColor' }),
804
+ h('rect', { x: 29.4, y: 30, width: 5.2, height: 11, rx: 2.6, fill: 'currentColor' })
805
+ );
806
+ }
807
+
808
+ function PanelIcon(props) {
809
+ var onClick = function (e) {
810
+ if (props && typeof props.onClick === 'function') { try { props.onClick(e); } catch (_) {} }
811
+ try { if (layout && typeof layout.selectPanel === 'function') layout.selectPanel(PANEL_ID); } catch (_) {}
812
+ };
813
+ return h('span', {
814
+ className: 'cv-rail-icon', title: tr('title'), role: 'button', tabIndex: 0,
815
+ onClick: onClick,
816
+ onKeyDown: function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(e); } },
817
+ style: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 22, height: 22, color: 'var(--dsw-alias-label-primary, #1d2129)', cursor: 'pointer' }
818
+ }, Shield(20));
819
+ }
820
+
821
+ function looksLikeUrl(v) { return /^https?:\/\//i.test(String(v || '').trim()); }
822
+ function copyToClipboard(text) {
823
+ try {
824
+ if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(String(text));
825
+ } catch (e) {}
826
+ return Promise.reject(new Error('no-clipboard'));
827
+ }
828
+
829
+ function Field(props) {
830
+ var t = props.t;
831
+ var isSecret = !!props.secret;
832
+ var revealed = !!props.revealed;
833
+ var display = (isSecret && !revealed) ? MASK : (props.value || '');
834
+ var masked = isSecret && !revealed;
835
+ var visitable = !!props.isUrl && looksLikeUrl(props.value);
836
+ return h('div', { className: 'cv-field' },
837
+ h('div', { className: 'cv-field-label' }, t(props.label)),
838
+ h('div', { className: 'cv-field-row' },
839
+ h('span', {
840
+ className: 'cv-field-value' + (props.mono ? ' cv-mono' : '') + (masked ? ' cv-masked' : '') + (props.multiline ? ' cv-field-multiline' : ''),
841
+ title: masked ? '' : (props.value || '')
842
+ }, display || '—'),
843
+ visitable ? h('button', { className: 'cv-mini', onClick: function () { props.onVisit(props.value); }, title: t('visit') }, t('visit')) : null,
844
+ isSecret ? h('button', { className: 'cv-mini', onClick: props.onToggle, title: revealed ? t('hide') : t('show') }, revealed ? t('hide') : t('show')) : null,
845
+ props.value ? h('button', { className: 'cv-mini', onClick: function () { props.onCopy(props.value); }, title: t('copy') }, t('copy')) : null
846
+ )
847
+ );
848
+ }
849
+
850
+ function Card(props) {
851
+ var e = props.entry, t = props.t;
852
+ var cat = e.category || 'account';
853
+ var catLabel = cat === 'apikey' ? t('catApikey') : (cat === 'other' ? t('catOther') : t('catAccount'));
854
+ return h('div', { className: 'cv-card' },
855
+ h('div', { className: 'cv-card-head' },
856
+ h('span', { className: 'cv-badge cv-badge-' + cat }, catLabel),
857
+ h('span', { className: 'cv-card-title', title: e.title }, e.title),
858
+ h('div', { className: 'cv-card-actions' },
859
+ h('button', { className: 'cv-icon-btn', onClick: props.onEdit, title: t('edit'), 'aria-label': t('edit') }, '✎'),
860
+ h('button', { className: 'cv-icon-btn cv-danger', onClick: props.onDelete, title: t('delete'), 'aria-label': t('delete') }, '🗑')
861
+ )
862
+ ),
863
+ h('div', { className: 'cv-card-body' },
864
+ schemaOf(cat).slice(1).map(function (f) {
865
+ if (!e[f.key]) return null;
866
+ return h(Field, {
867
+ key: f.key, t: t, label: f.label, value: e[f.key],
868
+ mono: !!f.mono, secret: isSecretField(f), multiline: isMultilineField(f), isUrl: !!f.isUrl,
869
+ revealed: !!props.revealed, onToggle: props.onToggle, onCopy: props.onCopy, onVisit: props.onVisit
870
+ });
871
+ })
872
+ )
873
+ );
874
+ }
875
+
876
+ function EditorModal(props) {
877
+ var d = props.draft, t = props.t, onChange = props.onChange;
878
+ var ss = useState(false), showSecret = ss[0], setShowSecret = ss[1];
879
+ var cat = d.category || 'account';
880
+ var meta = CATEGORIES.filter(function (c) { return c.k === cat; })[0] || CATEGORIES[0];
881
+ var fields = schemaOf(cat);
882
+
883
+ function baseInput(f, extra) {
884
+ return Object.assign({
885
+ className: 'cv-input', value: d[f.key] || '',
886
+ placeholder: f.ph ? t(f.ph) : '',
887
+ autoFocus: !!f.required,
888
+ onChange: function (ev) { onChange(f.key, ev.target.value); }
889
+ }, extra || {});
890
+ }
891
+ function renderField(f) {
892
+ var control;
893
+ if (f.type === 'text' || f.type === 'date') {
894
+ control = h('input', baseInput(f, { type: f.type === 'date' ? 'date' : 'text' }));
895
+ } else if (f.type === 'textarea') {
896
+ control = h('textarea', baseInput(f, { className: 'cv-input cv-textarea' }));
897
+ } else if (f.type === 'secret') {
898
+ control = h('div', { className: 'cv-secret-input' },
899
+ h('input', baseInput(f, { type: showSecret ? 'text' : 'password' })),
900
+ (f.generatable && typeof props.onGenerate === 'function') ? h('button', { type: 'button', className: 'cv-gen-btn', title: t('genField'), onClick: function () { props.onGenerate(f.key); } }, '⚙ ' + t('genButton')) : null,
901
+ h('button', { type: 'button', className: 'cv-secret-toggle', onClick: function () { setShowSecret(!showSecret); } }, showSecret ? t('hide') : t('show'))
902
+ );
903
+ } else if (f.type === 'secretarea') {
904
+ control = h('div', { className: 'cv-secret-input' },
905
+ h('textarea', baseInput(f, {
906
+ className: 'cv-input cv-textarea cv-mono' + (showSecret ? '' : ' cv-text-security'),
907
+ spellCheck: false
908
+ })),
909
+ (f.generatable && typeof props.onGenerate === 'function') ? h('button', { type: 'button', className: 'cv-gen-btn', title: t('genField'), onClick: function () { props.onGenerate(f.key); } }, '⚙ ' + t('genButton')) : null,
910
+ h('button', { type: 'button', className: 'cv-secret-toggle', onClick: function () { setShowSecret(!showSecret); } }, showSecret ? t('hide') : t('show'))
911
+ );
912
+ }
913
+ return h('label', { key: f.key, className: 'cv-form-row' },
914
+ h('span', { className: 'cv-form-label' }, t(f.label)),
915
+ control
916
+ );
917
+ }
918
+
919
+ return h('div', { className: 'cv-modal-backdrop', onMouseDown: function (e) { if (e.target === e.currentTarget) props.onCancel(); } },
920
+ h('div', {
921
+ className: 'cv-modal cv-modal-editor', role: 'dialog', 'aria-modal': 'true', 'aria-label': t(props.titleKey), tabIndex: -1,
922
+ onKeyDown: function (e) { if (e.key === 'Escape') props.onCancel(); }
923
+ },
924
+ h('div', { className: 'cv-modal-head' }, h('h2', null, t(props.titleKey) + ' · ' + t(meta.label))),
925
+ h('div', { className: 'cv-modal-hint' }, t(meta.hint)),
926
+ h('div', { className: 'cv-modal-body' },
927
+ h('label', { className: 'cv-form-row' },
928
+ h('span', { className: 'cv-form-label' }, t('fCategory')),
929
+ h('select', { className: 'cv-input', value: cat, onChange: function (ev) { onChange('category', ev.target.value); } },
930
+ CATEGORIES.map(function (c) { return h('option', { key: c.k, value: c.k }, t(c.label)); })
931
+ )
932
+ ),
933
+ fields.map(renderField)
934
+ ),
935
+ h('div', { className: 'cv-modal-foot' },
936
+ h('button', { className: 'cv-btn', onClick: props.onCancel }, t('cancel')),
937
+ h('button', { className: 'cv-btn cv-btn-primary', onClick: props.onSave }, t('save'))
938
+ )
939
+ )
940
+ );
941
+ }
942
+
943
+ // IME-friendly masked input: a plain text field styled with
944
+ // -webkit-text-security so Chinese/Japanese input methods can compose
945
+ // (type="password" disables IME composition in Chromium/Electron).
946
+ function SecretInput(props) {
947
+ var showState = useState(false);
948
+ var show = showState[0], setShow = showState[1];
949
+ return h('div', { className: 'cv-secret-input' },
950
+ h('input', {
951
+ className: 'cv-input' + (show ? '' : ' cv-text-security'),
952
+ type: 'text',
953
+ autoComplete: 'off',
954
+ spellCheck: false,
955
+ autoFocus: props.autoFocus,
956
+ value: props.value,
957
+ placeholder: props.placeholder,
958
+ onChange: props.onChange,
959
+ onKeyDown: props.onKeyDown
960
+ }),
961
+ h('button', { type: 'button', className: 'cv-secret-toggle', onClick: function () { setShow(!show); } },
962
+ show ? props.t('hide') : props.t('show'))
963
+ );
964
+ }
965
+
966
+ function ResetModal(props) {
967
+ var t = props.t;
968
+ var answerState = useState(''), answer = answerState[0], setAnswer = answerState[1];
969
+ var pwState = useState(''), pw = pwState[0], setPw = pwState[1];
970
+ var cfState = useState(''), cf = cfState[0], setCf = cfState[1];
971
+ var errState = useState(''), err = errState[0], setErr = errState[1];
972
+ var sec = getSecurity();
973
+ var hasAnswer = !!(sec && sec.answerHash);
974
+ function submit() {
975
+ if (!hasAnswer) { setErr(t('resetUnavailable')); return; }
976
+ if (!cf || cf !== pw) { setErr(t('secMismatch')); return; }
977
+ if (!pw || String(pw).length < 4) { setErr(t('secTooShort')); return; }
978
+ verifyAnswer(sec, answer).then(function (ok) {
979
+ if (!ok) { setErr(t('resetFail')); return; }
980
+ var s = Object.assign({}, getSecurity());
981
+ s.salt = s.salt || makeSalt();
982
+ return hashWithSalt(s.salt, pw).then(function (h) {
983
+ s.passwordHash = h;
984
+ saveSecurity(s);
985
+ props.onDone();
986
+ });
987
+ }).catch(function () { setErr(t('resetFail')); });
988
+ }
989
+ return h('div', { className: 'cv-modal-backdrop', onMouseDown: function (e) { if (e.target === e.currentTarget) props.onCancel(); } },
990
+ h('div', { className: 'cv-modal', role: 'dialog', 'aria-modal': 'true', tabIndex: -1,
991
+ onKeyDown: function (e) { if (e.key === 'Escape') props.onCancel(); } },
992
+ h('div', { className: 'cv-modal-head' }, h('h2', null, t('resetTitle'))),
993
+ h('div', { className: 'cv-modal-body' },
994
+ h('p', { className: 'cv-card-sub' }, t('resetDesc')),
995
+ hasAnswer ? h('label', { className: 'cv-form-row' },
996
+ h('span', { className: 'cv-form-label' }, (sec.question && sec.question.label) || sec.question || t('secQuestion')),
997
+ h(SecretInput, { t: t, autoFocus: true, value: answer, placeholder: t('resetAnswer'), onChange: function (ev) { setAnswer(ev.target.value); setErr(''); } })
998
+ ) : h('p', { className: 'cv-field-error' }, t('resetUnavailable')),
999
+ h('label', { className: 'cv-form-row' },
1000
+ h('span', { className: 'cv-form-label' }, t('resetNewPassword')),
1001
+ h(SecretInput, { t: t, value: pw, placeholder: t('secMinLength'), onChange: function (ev) { setPw(ev.target.value); setErr(''); } })
1002
+ ),
1003
+ h('label', { className: 'cv-form-row' },
1004
+ h('span', { className: 'cv-form-label' }, t('resetConfirm')),
1005
+ h(SecretInput, { t: t, value: cf, onChange: function (ev) { setCf(ev.target.value); setErr(''); },
1006
+ onKeyDown: function (e) { if (e.key === 'Enter') submit(); } })
1007
+ ),
1008
+ err ? h('div', { className: 'cv-field-error', role: 'alert' }, err) : null
1009
+ ),
1010
+ h('div', { className: 'cv-modal-foot' },
1011
+ h('button', { className: 'cv-btn', onClick: props.onCancel }, t('cancel')),
1012
+ h('button', { className: 'cv-btn cv-btn-primary', onClick: submit }, t('resetSubmit'))
1013
+ )
1014
+ )
1015
+ );
1016
+ }
1017
+
1018
+ function ConfirmModal(props) {
1019
+ var t = props.t;
1020
+ var msg = Array.isArray(props.message)
1021
+ ? props.message.map(function (line, i) { return h('div', { key: i }, line); })
1022
+ : props.message;
1023
+ return h('div', { className: 'cv-modal-backdrop', onMouseDown: function (e) { if (e.target === e.currentTarget) props.onCancel(); } },
1024
+ h('div', { className: 'cv-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': props.title, tabIndex: -1,
1025
+ onKeyDown: function (e) { if (e.key === 'Escape') props.onCancel(); } },
1026
+ h('div', { className: 'cv-modal-head' }, h('h2', null, props.title)),
1027
+ h('div', { className: 'cv-modal-hint' }, msg),
1028
+ h('div', { className: 'cv-modal-foot' },
1029
+ h('button', { className: 'cv-btn', onClick: props.onCancel }, t('cancel')),
1030
+ h('button', { className: 'cv-btn cv-btn-primary', onClick: props.onConfirm }, props.confirmLabel)
1031
+ )
1032
+ )
1033
+ );
1034
+ }
1035
+
1036
+ function ImportModal(props) {
1037
+ var t = props.t;
1038
+ var fileState = useState(null), fileInfo = fileState[0], setFileInfo = fileState[1];
1039
+ var entriesState = useState(null), pending = entriesState[0], setPending = entriesState[1];
1040
+ var modeState = useState('merge'), mode = modeState[0], setMode = modeState[1];
1041
+ var errState = useState(''), err = errState[0], setErr = errState[1];
1042
+ var inputRef = useState({})[0];
1043
+
1044
+ function onFile(ev) {
1045
+ var f = ev.target.files && ev.target.files[0];
1046
+ if (!f) return;
1047
+ setErr(''); setPending(null);
1048
+ setFileInfo({ name: f.name, size: f.size });
1049
+ if (typeof FileReader === 'undefined') { setErr(t('importInvalid')); return; }
1050
+ var reader = new FileReader();
1051
+ reader.onload = function () {
1052
+ try {
1053
+ var clean = parseBackup(String(reader.result || ''));
1054
+ setPending(clean);
1055
+ if (clean.length === 0) setErr(t('importEmpty'));
1056
+ } catch (e) { setErr(t('importInvalid')); setPending(null); }
1057
+ };
1058
+ reader.onerror = function () { setErr(t('importInvalid')); setPending(null); };
1059
+ reader.readAsText(f, 'utf-8');
1060
+ }
1061
+ function submit() {
1062
+ if (!pending || pending.length === 0) { setErr(t('importEmpty')); return; }
1063
+ props.onImport(pending, mode);
1064
+ }
1065
+ return h('div', { className: 'cv-modal-backdrop', onMouseDown: function (e) { if (e.target === e.currentTarget) props.onCancel(); } },
1066
+ h('div', { className: 'cv-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('importTitle'), tabIndex: -1,
1067
+ onKeyDown: function (e) { if (e.key === 'Escape') props.onCancel(); } },
1068
+ h('div', { className: 'cv-modal-head' }, h('h2', null, t('importTitle'))),
1069
+ h('div', { className: 'cv-modal-hint' }, t('importHint')),
1070
+ h('div', { className: 'cv-modal-body' },
1071
+ h('input', {
1072
+ ref: function (el) { inputRef.el = el; },
1073
+ type: 'file', accept: '.json,application/json', style: { display: 'none' },
1074
+ onChange: onFile
1075
+ }),
1076
+ h('button', { type: 'button', className: 'cv-btn', onClick: function () { if (inputRef.el) inputRef.el.click(); } },
1077
+ fileInfo ? '📄 ' + fileInfo.name : t('import')),
1078
+ fileInfo ? h('div', { className: 'cv-import-file' },
1079
+ t('importFound') + ':' + (pending ? pending.length : '…')) : null,
1080
+ h('div', { className: 'cv-form-label' }, t('importMode')),
1081
+ h('div', { className: 'cv-import-modes' },
1082
+ h('label', { className: 'cv-import-opt' },
1083
+ h('input', { type: 'radio', name: 'cv-import-mode', checked: mode === 'merge', onChange: function () { setMode('merge'); } }),
1084
+ h('div', null,
1085
+ h('div', { className: 'cv-import-opt-name' }, t('importMerge')),
1086
+ h('div', { className: 'cv-import-opt-hint' }, t('importMergeHint'))
1087
+ )
1088
+ ),
1089
+ h('label', { className: 'cv-import-opt' + (mode === 'replace' ? ' cv-import-warn' : '') },
1090
+ h('input', { type: 'radio', name: 'cv-import-mode', checked: mode === 'replace', onChange: function () { setMode('replace'); } }),
1091
+ h('div', null,
1092
+ h('div', { className: 'cv-import-opt-name' }, t('importReplace')),
1093
+ h('div', { className: 'cv-import-opt-hint' }, t('importReplaceWarn'))
1094
+ )
1095
+ )
1096
+ ),
1097
+ err ? h('div', { className: 'cv-field-error', role: 'alert' }, err) : null
1098
+ ),
1099
+ h('div', { className: 'cv-modal-foot' },
1100
+ h('button', { className: 'cv-btn', onClick: props.onCancel }, t('cancel')),
1101
+ h('button', { className: 'cv-btn cv-btn-primary', disabled: !pending || pending.length === 0, onClick: submit }, t('importConfirm'))
1102
+ )
1103
+ )
1104
+ );
1105
+ }
1106
+
1107
+ function LockScreen(props) {
1108
+ var t = props.t;
1109
+ var pwState = useState(''), pw = pwState[0], setPw = pwState[1];
1110
+ var errState = useState(''), err = errState[0], setErr = errState[1];
1111
+ var resetState = useState(false), resetting = resetState[0], setResetting = resetState[1];
1112
+ function submit() {
1113
+ verifyPassword(getSecurity(), pw).then(function (ok) {
1114
+ if (ok) { markUnlocked(); props.onUnlocked(); }
1115
+ else { setErr(t('unlockFail')); setPw(''); }
1116
+ });
1117
+ }
1118
+ return h('div', { className: 'cv-root' },
1119
+ h('style', null, CSS),
1120
+ h('div', { className: 'cv-lock' },
1121
+ h('div', { className: 'cv-lock-card' },
1122
+ h('div', { className: 'cv-lock-icon' }, Shield(38)),
1123
+ h('h2', null, t('lockTitle')),
1124
+ h('p', null, t('lockDesc')),
1125
+ h('div', { className: 'cv-lock-form' },
1126
+ h(SecretInput, { t: t, autoFocus: true, value: pw, placeholder: t('secCurrent'),
1127
+ onChange: function (ev) { setPw(ev.target.value); setErr(''); },
1128
+ onKeyDown: function (e) { if (e.key === 'Enter') submit(); } }),
1129
+ err ? h('div', { className: 'cv-field-error', role: 'alert' }, err) : null,
1130
+ h('div', { className: 'cv-lock-actions' },
1131
+ h('button', { className: 'cv-btn cv-btn-primary', onClick: submit }, t('unlock')),
1132
+ hasSetup() ? h('button', { className: 'cv-link', onClick: function () { setResetting(true); } }, t('forgot')) : null
1133
+ )
1134
+ ),
1135
+ h('div', { className: 'cv-lock-foot' }, t('secAnswerHint'))
1136
+ )
1137
+ ),
1138
+ resetting ? h(ResetModal, { t: t, onCancel: function () { setResetting(false); }, onDone: function () { setResetting(false); setErr(''); setPw(''); } }) : null
1139
+ );
1140
+ }
1141
+
1142
+ function SettingsSection(props) {
1143
+ var langState = useState(function () { return detectLang(locale); });
1144
+ var lang = langState[0], setLang = langState[1];
1145
+ function t(k) { return (DICTS[lang] && DICTS[lang][k]) || DICTS.en[k] || k; }
1146
+ var secState = useState(function () { return Object.assign({}, getSecurity()); });
1147
+ var sec = secState[0], setSec = secState[1];
1148
+ function refresh() { setSec(Object.assign({}, getSecurity())); }
1149
+ useEffect(function () { return subscribeSecurity(refresh); }, []);
1150
+ useEffect(function () {
1151
+ if (locale && typeof locale.subscribe === 'function') {
1152
+ var un = null;
1153
+ try { un = locale.subscribe(function () { setLang(detectLang(locale)); }); } catch (e) {}
1154
+ return function () { try { if (un) un(); } catch (e) {} };
1155
+ }
1156
+ }, []);
1157
+ var pwState = useState(''), pw = pwState[0], setPw = pwState[1];
1158
+ var currentState = useState(''), current = currentState[0], setCurrent = currentState[1];
1159
+ var confirmState = useState(''), confirm = confirmState[0], setConfirm = confirmState[1];
1160
+ var disablePwState = useState(''), disablePw = disablePwState[0], setDisablePw = disablePwState[1];
1161
+ var qState = useState(function () { return (getSecurity().question && getSecurity().question.k) || 'pet'; });
1162
+ var q = qState[0], setQ = qState[1];
1163
+ var customQState = useState(''), customQ = customQState[0], setCustomQ = customQState[1];
1164
+ var answerState = useState(''), answer = answerState[0], setAnswer = answerState[1];
1165
+ var qCurrentState = useState(''), qCurrent = qCurrentState[0], setQCurrent = qCurrentState[1];
1166
+ var msgState = useState(null), msg = msgState[0], setMsg = msgState[1];
1167
+ var updateState = useState(null), updateInfo = updateState[0], setUpdateInfo = updateState[1];
1168
+ var checkingState = useState(false), checking = checkingState[0], setChecking = checkingState[1];
1169
+ var upgradingState = useState(false), upgrading = upgradingState[0], setUpgrading = upgradingState[1];
1170
+ var upgradeMsgState = useState(null), upgradeMsg = upgradeMsgState[0], setUpgradeMsg = upgradeMsgState[1];
1171
+ var upgradeConfirmState = useState(null), upgradeConfirmDlg = upgradeConfirmState[0], setUpgradeConfirmDlg = upgradeConfirmState[1];
1172
+ var pollRef = useRef(null);
1173
+ // Inline card messages: shown inside the settings card where the action
1174
+ // happened, so feedback lands exactly where the user is looking.
1175
+ function notify(area, text, kind) { setMsg({ area: area, text: text, kind: kind || 'ok' }); }
1176
+ useEffect(function () {
1177
+ if (!msg) return;
1178
+ var id = setTimeout(function () { setMsg(null); }, 4000);
1179
+ return function () { clearTimeout(id); };
1180
+ }, [msg]);
1181
+ // Clear any running poll timer when the settings page unmounts.
1182
+ useEffect(function () {
1183
+ return function () { if (pollRef.current) { clearTimeout(pollRef.current); pollRef.current = null; } };
1184
+ }, []);
1185
+
1186
+ function checkUpdate() {
1187
+ if (checking) return;
1188
+ setChecking(true);
1189
+ setUpdateInfo(null);
1190
+ window.fetch(API + 'update-check', { credentials: 'same-origin', headers: { accept: 'application/json' } })
1191
+ .then(function (r) { return r.json(); })
1192
+ .then(function (body) {
1193
+ if (!body || body.ok !== true) {
1194
+ var msg = body && body.error ? body.error : t('updateFail');
1195
+ setUpdateInfo({ ok: false, error: msg });
1196
+ return;
1197
+ }
1198
+ // Recompute against THIS client's version so the "new version"
1199
+ // verdict always agrees with the version number shown in the UI.
1200
+ // The host's CURRENT_VERSION may be stale until Harness restarts.
1201
+ body.updateAvailable = compareVersions(VERSION, body.latestVersion) < 0;
1202
+ setUpdateInfo(body);
1203
+ })
1204
+ .catch(function () { setUpdateInfo({ ok: false, error: t('updateFail') }); })
1205
+ .then(function () { setChecking(false); });
1206
+ }
1207
+
1208
+ // Upgrade goes through dshmarket's documented public update API v1 — the
1209
+ // plugin market drives the same package manager that installed this plugin,
1210
+ // so we never spawn a package manager ourselves.
1211
+ function marketFetchJson(url, init) {
1212
+ return window.fetch(url, Object.assign({ credentials: 'same-origin', headers: { accept: 'application/json' } }, init || {}))
1213
+ .then(function (r) { return r.json(); });
1214
+ }
1215
+
1216
+ function pollOperation(operationId) {
1217
+ marketFetchJson('dsh-market/api/v1/operations?operationId=' + encodeURIComponent(operationId) + '&_=' + Date.now())
1218
+ .then(function (body) {
1219
+ var op = body && body.operation;
1220
+ if (!op) { setUpgradeMsg({ kind: 'err', text: t('upgradeFail') + 'operation not found' }); setUpgrading(false); return; }
1221
+ var state = op.state;
1222
+ if (state === 'succeeded') {
1223
+ var installed = op.installedVersion || '';
1224
+ var restart = op.outcome && op.outcome.restartRequired;
1225
+ setUpgradeMsg({ kind: 'ok', text: t('upgradeSuccess') + (installed ? '(' + installed + ')' : '') + (restart ? ' ' + t('upgradeRestart') : '') });
1226
+ setUpgrading(false);
1227
+ setUpdateInfo(null);
1228
+ checkUpdate();
1229
+ return;
1230
+ }
1231
+ if (state === 'failed' || state === 'cancelled' || state === 'rolled-back') {
1232
+ var failure = op.failure || {};
1233
+ setUpgradeMsg({ kind: 'err', text: t('upgradeFail') + (failure.message || failure.code || state) });
1234
+ setUpgrading(false);
1235
+ return;
1236
+ }
1237
+ // queued / running: keep polling
1238
+ var phase = op.progress && op.progress.phase ? ' · ' + op.progress.phase : '';
1239
+ setUpgradeMsg({ kind: '', text: t('upgradePolling') + phase });
1240
+ pollRef.current = setTimeout(function () { pollOperation(operationId); }, 1200);
1241
+ })
1242
+ .catch(function () {
1243
+ setUpgradeMsg({ kind: 'err', text: t('upgradeFail') + 'network' });
1244
+ setUpgrading(false);
1245
+ });
1246
+ }
1247
+
1248
+ function startUpgrade() {
1249
+ if (upgrading) return;
1250
+ setUpgradeConfirmDlg({
1251
+ title: t('upgradeTitle'), message: t('upgradeConfirm'), confirmLabel: t('upgradeGo'),
1252
+ onConfirm: function () { setUpgradeConfirmDlg(null); runUpgrade(); }
1253
+ });
1254
+ }
1255
+
1256
+ function runUpgrade() {
1257
+ setUpgrading(true);
1258
+ setUpgradeMsg({ kind: '', text: t('upgradeCheckMarket') });
1259
+ // Discover the market API and feature-detect the mutation endpoint.
1260
+ marketFetchJson('dsh-market/api/v1/capabilities')
1261
+ .then(function (cap) {
1262
+ if (!cap || cap.schema !== 'dsh-market/update-api/v1' || !(cap.features && cap.features.update)) {
1263
+ throw new Error('no-market');
1264
+ }
1265
+ setUpgradeMsg({ kind: '', text: t('upgradeStarted') });
1266
+ return marketFetchJson(cap.endpoints.updates, {
1267
+ method: 'POST',
1268
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
1269
+ body: JSON.stringify({ packageName: 'dsh-credential-vault' })
1270
+ });
1271
+ })
1272
+ .then(function (res) {
1273
+ var op = res && res.operation;
1274
+ if (res && res.schema === 'dsh-market/update-api/v1' && op && op.operationId) {
1275
+ if (op.state === 'succeeded') {
1276
+ setUpgradeMsg({ kind: 'ok', text: t('upgradeSuccess') + ' ' + t('upgradeRestart') });
1277
+ setUpgrading(false);
1278
+ setUpdateInfo(null); checkUpdate();
1279
+ return;
1280
+ }
1281
+ if (op.state === 'failed' || op.state === 'cancelled' || op.state === 'rolled-back') {
1282
+ var f = op.failure || {};
1283
+ setUpgradeMsg({ kind: 'err', text: t('upgradeFail') + (f.message || f.code || op.state) });
1284
+ setUpgrading(false);
1285
+ return;
1286
+ }
1287
+ setUpgradeMsg({ kind: '', text: t('upgradePolling') });
1288
+ pollOperation(op.operationId);
1289
+ return;
1290
+ }
1291
+ var err = (res && (res.error || (res.failure && res.failure.message))) || t('upgradeFail');
1292
+ if (/not installed|404/i.test(String(err))) err = t('upgradeNoMarket');
1293
+ setUpgradeMsg({ kind: 'err', text: t('upgradeFail') + err });
1294
+ setUpgrading(false);
1295
+ })
1296
+ .catch(function (e) {
1297
+ var msg = e && e.message === 'no-market' ? t('upgradeNoMarket') : t('upgradeFail') + (e && e.message ? e.message : '');
1298
+ setUpgradeMsg({ kind: 'err', text: msg });
1299
+ setUpgrading(false);
1300
+ });
1301
+ }
1302
+
1303
+ function setPassword() {
1304
+ if (!pw || String(pw).length < 4) { notify('password', t('secTooShort'), 'err'); return; }
1305
+ if (pw !== confirm) { notify('password', t('secMismatch'), 'err'); return; }
1306
+ var s = Object.assign({}, getSecurity());
1307
+ function commit() {
1308
+ s.salt = s.salt || makeSalt();
1309
+ return hashWithSalt(s.salt, pw).then(function (h) {
1310
+ s.passwordHash = h;
1311
+ saveSecurity(s);
1312
+ refresh(); setPw(''); setConfirm(''); notify('password', t('secPasswordOn'));
1313
+ });
1314
+ }
1315
+ if (s.passwordHash) {
1316
+ verifyPassword(s, current).then(function (ok) {
1317
+ if (!ok) { notify('password', t('secCurrentWrong'), 'err'); return; }
1318
+ return commit();
1319
+ });
1320
+ } else commit();
1321
+ }
1322
+ function saveQuestion() {
1323
+ if (!answer) { notify('question', t('secAnswer'), 'err'); return; }
1324
+ var s = Object.assign({}, getSecurity());
1325
+ var chosen = SECURITY_QUESTIONS.filter(function (x) { return x.k === q; })[0] || SECURITY_QUESTIONS[0];
1326
+ var label = q === 'custom' ? (customQ || '') : (chosen[lang] || chosen.en);
1327
+ if (q === 'custom' && !customQ.trim()) { notify('question', t('secQuestion'), 'err'); return; }
1328
+ // Once a question is set, changing it must be authorized with the current access password.
1329
+ function commit() {
1330
+ hashWithSalt(s.salt || (s.salt = makeSalt()), normalizeAnswer(answer)).then(function (h) {
1331
+ s.question = { k: q, label: label };
1332
+ s.answerHash = h;
1333
+ saveSecurity(s);
1334
+ refresh(); setAnswer(''); setQCurrent(''); notify('question', t('secQuestionSet'));
1335
+ });
1336
+ }
1337
+ if (s.passwordHash && s.question && s.answerHash) {
1338
+ if (!qCurrent) { notify('question', t('secCurrentRequired'), 'err'); return; }
1339
+ verifyPassword(s, qCurrent).then(function (ok) {
1340
+ if (!ok) { notify('question', t('secCurrentWrong'), 'err'); return; }
1341
+ return commit();
1342
+ });
1343
+ } else commit();
1344
+ }
1345
+ function toggleEnabled() {
1346
+ if (!sec.enabled && !hasSetup()) { notify('enable', t('secNeedSetupFirst'), 'err'); return; }
1347
+ var enabling = !sec.enabled;
1348
+ if (!enabling) {
1349
+ // Disabling the access password must be confirmed with the current password.
1350
+ if (!disablePw) { notify('enable', t('secDisableHint'), 'err'); return; }
1351
+ verifyPassword(getSecurity(), disablePw).then(function (ok) {
1352
+ if (!ok) { notify('enable', t('secCurrentWrong'), 'err'); return; }
1353
+ var s = Object.assign({}, getSecurity(), { enabled: false });
1354
+ lockVault();
1355
+ saveSecurity(s);
1356
+ setDisablePw('');
1357
+ refresh();
1358
+ notify('enable', t('secPasswordOff'));
1359
+ });
1360
+ return;
1361
+ }
1362
+ // Enabling must lock immediately so the password actually protects the vault.
1363
+ var s = Object.assign({}, getSecurity(), { enabled: true });
1364
+ lockVault();
1365
+ saveSecurity(s);
1366
+ refresh();
1367
+ notify('enable', t('secEnabledLocked'));
1368
+ }
1369
+ function toggleIdle() {
1370
+ var enabling = !sec.idleEnabled;
1371
+ if (enabling && !sec.enabled) { notify('idle', t('secNeedSetupFirst'), 'err'); return; }
1372
+ var s = Object.assign({}, getSecurity(), { idleEnabled: enabling });
1373
+ if (enabling) {
1374
+ // Turning auto-lock on locks the vault right away so the policy takes effect.
1375
+ lockVault();
1376
+ if (!s.idleMs) s.idleMs = IDLE_MS;
1377
+ }
1378
+ saveSecurity(s);
1379
+ refresh();
1380
+ notify('idle', t(enabling ? 'secIdleOn' : 'secIdleOff'));
1381
+ }
1382
+ function setIdleMs(ms) {
1383
+ var s = Object.assign({}, getSecurity(), { idleMs: ms });
1384
+ saveSecurity(s);
1385
+ refresh();
1386
+ }
1387
+
1388
+ var questionLabel = sec.question ? (sec.question.label || t('secQuestion')) : null;
1389
+ var qNeedsCurrent = !!(sec.passwordHash && sec.question && sec.answerHash);
1390
+ // Inline note inside the card where the action happened (kind: 'ok'|'err').
1391
+ function CardNote(area) {
1392
+ if (!msg || msg.area !== area) return null;
1393
+ var err = msg.kind === 'err';
1394
+ return h('div', { className: 'cv-note ' + (err ? 'cv-note-err' : 'cv-note-ok'), role: 'status' },
1395
+ h('span', null, err ? '⚠' : '✓'), h('span', null, msg.text));
1396
+ }
1397
+ return h('div', { className: 'cv-root' },
1398
+ h('style', null, CSS),
1399
+ h('div', { className: 'cv-settings' },
1400
+ h('div', { className: 'cv-settings-head' },
1401
+ h('h2', null, t('secTitle')),
1402
+ h('p', null, t('secDesc'))
1403
+ ),
1404
+ h('div', { className: 'cv-settings-card' },
1405
+ h('h3', null, t('secEnable')),
1406
+ h('div', { className: 'cv-switch-row' },
1407
+ h('div', null,
1408
+ h('div', { className: 'cv-switch-label' }, t('secEnable')),
1409
+ h('div', { className: 'cv-switch-hint' }, t('secEnableHint'))
1410
+ ),
1411
+ h('button', { type: 'button', className: 'cv-switch', role: 'switch', 'aria-checked': sec.enabled ? 'true' : 'false',
1412
+ 'aria-label': t('secEnable'), onClick: toggleEnabled },
1413
+ h('span', { className: 'cv-switch-knob' })
1414
+ )
1415
+ ),
1416
+ h('div', { className: 'cv-status' + (sec.enabled ? '' : ' cv-switch-hint') }, sec.enabled ? '✓ ' + t('secPasswordOn') : t('secPasswordOff')),
1417
+ CardNote('enable'),
1418
+ sec.enabled ? h('div', { className: 'cv-settings-fields', style: { marginTop: 12 } },
1419
+ h('p', { className: 'cv-card-sub', style: { marginTop: 0 } }, t('secDisableHint')),
1420
+ h(SecretInput, { t: t, value: disablePw, placeholder: t('secCurrent'), onChange: function (ev) { setDisablePw(ev.target.value); },
1421
+ onKeyDown: function (e) { if (e.key === 'Enter') toggleEnabled(); } }),
1422
+ h('div', null, h('button', { type: 'button', className: 'cv-btn', onClick: toggleEnabled }, t('secDisableConfirm')))
1423
+ ) : null,
1424
+ !hasSetup() ? h('p', { className: 'cv-card-sub', style: { marginTop: 12, marginBottom: 0 } }, t('secCompleteSetup')) : null
1425
+ ),
1426
+ h('div', { className: 'cv-settings-card' },
1427
+ h('h3', null, t('secIdle')),
1428
+ h('div', { className: 'cv-switch-row' },
1429
+ h('div', null,
1430
+ h('div', { className: 'cv-switch-label' }, t('secIdle')),
1431
+ h('div', { className: 'cv-switch-hint' }, t('secIdleHint'))
1432
+ ),
1433
+ h('button', { type: 'button', className: 'cv-switch', role: 'switch', 'aria-checked': sec.idleEnabled ? 'true' : 'false',
1434
+ 'aria-label': t('secIdle'), onClick: toggleIdle },
1435
+ h('span', { className: 'cv-switch-knob' })
1436
+ )
1437
+ ),
1438
+ h('div', { className: 'cv-status' + (sec.idleEnabled ? '' : ' cv-switch-hint') }, sec.idleEnabled ? '✓ ' + t('secIdleOn') : t('secIdleOff')),
1439
+ CardNote('idle'),
1440
+ sec.idleEnabled ? h('label', { className: 'cv-form-row', style: { marginTop: 10 } },
1441
+ h('span', { className: 'cv-form-label' }, t('secIdleDuration')),
1442
+ h('select', { className: 'cv-input', value: String(sec.idleMs || IDLE_MS), onChange: function (ev) { setIdleMs(Number(ev.target.value)); } },
1443
+ h('option', { value: String(1 * 60 * 1000) }, '1 ' + t('idleMinute')),
1444
+ h('option', { value: String(5 * 60 * 1000) }, '5 ' + t('idleMinutes')),
1445
+ h('option', { value: String(15 * 60 * 1000) }, '15 ' + t('idleMinutes')),
1446
+ h('option', { value: String(30 * 60 * 1000) }, '30 ' + t('idleMinutes')),
1447
+ h('option', { value: String(60 * 60 * 1000) }, '1 ' + t('idleHour')),
1448
+ h('option', { value: String(4 * 60 * 60 * 1000) }, '4 ' + t('idleHours'))
1449
+ )
1450
+ ) : null
1451
+ ),
1452
+ h('div', { className: 'cv-settings-card' },
1453
+ h('h3', null, t('secSetPassword')),
1454
+ h('p', { className: 'cv-card-sub' }, sec.passwordHash ? t('secNew') : t('secCompleteSetup')),
1455
+ h('div', { className: 'cv-settings-fields' },
1456
+ sec.passwordHash ? h('label', { className: 'cv-form-row' },
1457
+ h('span', { className: 'cv-form-label' }, t('secCurrent')),
1458
+ h(SecretInput, { t: t, value: current, onChange: function (ev) { setCurrent(ev.target.value); } })
1459
+ ) : null,
1460
+ h('label', { className: 'cv-form-row' },
1461
+ h('span', { className: 'cv-form-label' }, sec.passwordHash ? t('secNew') : t('secNew')),
1462
+ h(SecretInput, { t: t, value: pw, placeholder: t('secMinLength'), onChange: function (ev) { setPw(ev.target.value); } })
1463
+ ),
1464
+ h('label', { className: 'cv-form-row' },
1465
+ h('span', { className: 'cv-form-label' }, t('secConfirm')),
1466
+ h(SecretInput, { t: t, value: confirm, onChange: function (ev) { setConfirm(ev.target.value); },
1467
+ onKeyDown: function (e) { if (e.key === 'Enter') setPassword(); } })
1468
+ ),
1469
+ h('div', null, h('button', { className: 'cv-btn cv-btn-primary', onClick: setPassword }, t('secSavePassword'))),
1470
+ CardNote('password')
1471
+ )
1472
+ ),
1473
+ h('div', { className: 'cv-settings-card' },
1474
+ h('h3', null, t('secQuestion')),
1475
+ h('p', { className: 'cv-card-sub' }, qNeedsCurrent ? t('secQCurrentHint') : t('secAnswerHint')),
1476
+ questionLabel ? h('div', { className: 'cv-status' }, '✓ ' + t('secQuestionSet') + ':' + questionLabel) : null,
1477
+ h('div', { className: 'cv-settings-fields' },
1478
+ qNeedsCurrent ? h('label', { className: 'cv-form-row' },
1479
+ h('span', { className: 'cv-form-label' }, t('secCurrent')),
1480
+ h(SecretInput, { t: t, value: qCurrent, placeholder: t('secCurrent'), onChange: function (ev) { setQCurrent(ev.target.value); } })
1481
+ ) : null,
1482
+ h('label', { className: 'cv-form-row' },
1483
+ h('span', { className: 'cv-form-label' }, t('secQuestion')),
1484
+ h('select', { className: 'cv-input', value: q, onChange: function (ev) { setQ(ev.target.value); } },
1485
+ SECURITY_QUESTIONS.map(function (x) { return h('option', { key: x.k, value: x.k }, x[lang] || x.en); })
1486
+ )
1487
+ ),
1488
+ q === 'custom' ? h('label', { className: 'cv-form-row' },
1489
+ h('span', { className: 'cv-form-label' }, t('secCustomQuestion')),
1490
+ h('input', { className: 'cv-input', type: 'text', value: customQ, onChange: function (ev) { setCustomQ(ev.target.value); } })
1491
+ ) : null,
1492
+ h('label', { className: 'cv-form-row' },
1493
+ h('span', { className: 'cv-form-label' }, t('secAnswer')),
1494
+ h(SecretInput, { t: t, value: answer, placeholder: t('secAnswer'), onChange: function (ev) { setAnswer(ev.target.value); } })
1495
+ ),
1496
+ h('div', null, h('button', { className: 'cv-btn', onClick: saveQuestion }, t('secSaveQuestion'))),
1497
+ CardNote('question')
1498
+ )
1499
+ ),
1500
+ h('div', { className: 'cv-settings-card' },
1501
+ h('h3', null, t('updateTitle')),
1502
+ h('p', { className: 'cv-card-sub' }, t('updateDesc')),
1503
+ h('div', { className: 'cv-update-row' },
1504
+ h('span', { className: 'cv-form-label' }, t('updateCurrent') + ':' + VERSION),
1505
+ h('button', { type: 'button', className: 'cv-btn', disabled: checking, onClick: checkUpdate }, checking ? t('updateChecking') : t('updateCheck'))
1506
+ ),
1507
+ updateInfo ? h('div', { className: 'cv-card-sub', style: { marginTop: 10, marginBottom: 0 } },
1508
+ updateInfo.ok === true
1509
+ ? (updateInfo.updateAvailable
1510
+ ? t('updateAvailable') + ' ' + updateInfo.latestVersion + ' — ' + t('updateHow') + ' ' + updateInfo.releaseUrl
1511
+ : t('updateUpToDate') + '(' + t('updateLatest') + ':' + updateInfo.latestVersion + ')')
1512
+ : (/release|404/i.test(String(updateInfo.error)) ? t('updateNoRelease') : t('updateFail'))
1513
+ ) : null,
1514
+ updateInfo && updateInfo.ok === true && updateInfo.updateAvailable
1515
+ ? h('div', { className: 'cv-update-row', style: { marginTop: 10 } },
1516
+ h('button', { type: 'button', className: 'cv-btn cv-btn-primary', disabled: upgrading, onClick: startUpgrade }, upgrading ? t('upgrading') : t('upgrade'))
1517
+ )
1518
+ : null,
1519
+ upgradeMsg ? h('div', { className: 'cv-upgrade-status' + (upgradeMsg.kind === 'ok' ? ' cv-ok' : upgradeMsg.kind === 'err' ? ' cv-err' : ''), role: 'status' }, upgradeMsg.text) : null
1520
+ ),
1521
+ upgradeConfirmDlg ? h(ConfirmModal, {
1522
+ t: t, title: upgradeConfirmDlg.title, message: upgradeConfirmDlg.message, confirmLabel: upgradeConfirmDlg.confirmLabel,
1523
+ onConfirm: upgradeConfirmDlg.onConfirm, onCancel: function () { setUpgradeConfirmDlg(null); }
1524
+ }) : null
1525
+ )
1526
+ );
1527
+ }
1528
+
1529
+ function SettingsIcon(props) {
1530
+ return h('span', { style: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 22, height: 22, color: 'var(--dsw-alias-label-primary, #1d2129)' } }, Shield(18));
1531
+ }
1532
+
1533
+ // ---- Password generator modal ---------------------------------------
1534
+ function PasswordGeneratorModal(props) {
1535
+ var t = props.t;
1536
+ var lenState = useState(16), length = lenState[0], setLength = lenState[1];
1537
+ var upperState = useState(true), upper = upperState[0], setUpper = upperState[1];
1538
+ var lowerState = useState(true), lower = lowerState[0], setLower = lowerState[1];
1539
+ var digitsState = useState(true), digits = digitsState[0], setDigits = digitsState[1];
1540
+ var symbolsState = useState(true), symbols = symbolsState[0], setSymbols = symbolsState[1];
1541
+ var avoidState = useState(true), avoid = avoidState[0], setAvoid = avoidState[1];
1542
+ var valueState = useState(''), value = valueState[0], setValue = valueState[1];
1543
+ var errState = useState(''), err = errState[0], setErr = errState[1];
1544
+
1545
+ function regen() {
1546
+ var pw = generatePassword({ length: length, upper: upper, lower: lower, digits: digits, symbols: symbols, avoidAmbiguous: avoid });
1547
+ if (!pw) { setErr(t('genError')); setValue(''); return; }
1548
+ setErr(''); setValue(pw);
1549
+ }
1550
+ function doUse() {
1551
+ if (!value) { regen(); return; }
1552
+ props.onUse(value);
1553
+ }
1554
+ var strength = value ? passwordStrength(value) : null;
1555
+ var strengthLabel = strength ? (strength.tier === 'strong' ? t('genStrong') : strength.tier === 'fair' ? t('genFair') : t('genWeak')) : '';
1556
+ return h('div', { className: 'cv-modal-backdrop', onMouseDown: function (e) { if (e.target === e.currentTarget) props.onCancel(); } },
1557
+ h('div', { className: 'cv-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('genTitle'), tabIndex: -1,
1558
+ onKeyDown: function (e) { if (e.key === 'Escape') props.onCancel(); } },
1559
+ h('div', { className: 'cv-modal-head' }, h('h2', null, t('genTitle'))),
1560
+ h('div', { className: 'cv-modal-hint' }, t('genHint')),
1561
+ h('div', { className: 'cv-modal-body' },
1562
+ h('label', { className: 'cv-form-row' },
1563
+ h('span', { className: 'cv-form-label' }, t('genLength') + ':' + length),
1564
+ h('input', { className: 'cv-input', type: 'range', min: 4, max: 64, value: length,
1565
+ onChange: function (ev) { setLength(Number(ev.target.value)); } })
1566
+ ),
1567
+ h('div', { className: 'cv-gen-opts' },
1568
+ h('label', { className: 'cv-gen-check' }, h('input', { type: 'checkbox', checked: upper, onChange: function (ev) { setUpper(ev.target.checked); } }), t('genUpper')),
1569
+ h('label', { className: 'cv-gen-check' }, h('input', { type: 'checkbox', checked: lower, onChange: function (ev) { setLower(ev.target.checked); } }), t('genLower')),
1570
+ h('label', { className: 'cv-gen-check' }, h('input', { type: 'checkbox', checked: digits, onChange: function (ev) { setDigits(ev.target.checked); } }), t('genDigits')),
1571
+ h('label', { className: 'cv-gen-check' }, h('input', { type: 'checkbox', checked: symbols, onChange: function (ev) { setSymbols(ev.target.checked); } }), t('genSymbols')),
1572
+ h('label', { className: 'cv-gen-check', style: { gridColumn: '1 / -1' } }, h('input', { type: 'checkbox', checked: avoid, onChange: function (ev) { setAvoid(ev.target.checked); } }), t('genAvoidAmbiguous'))
1573
+ ),
1574
+ value ? h('div', null,
1575
+ h('div', { className: 'cv-gen-preview' }, value),
1576
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 } },
1577
+ h('span', { className: 'cv-form-label' }, t('genStrength') + ':'),
1578
+ h('span', { className: 'cv-gen-strength cv-' + strength.tier }, strengthLabel + ' (' + strength.bits + ' bit)')
1579
+ ),
1580
+ h('div', { className: 'cv-gen-bar' }, h('span', { className: strength.tier, style: { width: (strength.bits < 45 ? 33 : strength.bits < 65 ? 66 : 100) + '%' } }))
1581
+ ) : null,
1582
+ err ? h('div', { className: 'cv-field-error', role: 'alert' }, err) : null
1583
+ ),
1584
+ h('div', { className: 'cv-modal-foot' },
1585
+ h('button', { className: 'cv-btn', onClick: props.onCancel }, t('cancel')),
1586
+ value ? h('button', { className: 'cv-btn', onClick: function () { copyToClipboard(value).then(function () { if (props.onCopied) props.onCopied(); }).catch(function () {}); } }, t('genCopy')) : null,
1587
+ value ? h('button', { className: 'cv-btn', onClick: regen }, t('genRegenerate')) : null,
1588
+ h('button', { className: 'cv-btn cv-btn-primary', onClick: doUse }, value ? t('genUse') : t('genGenerate'))
1589
+ )
1590
+ )
1591
+ );
1592
+ }
1593
+
1594
+ // ---- Security audit modal -------------------------------------------
1595
+ function AuditModal(props) {
1596
+ var t = props.t;
1597
+ var resultState = useState(null), result = resultState[0], setResult = resultState[1];
1598
+ var scanningState = useState(false), scanning = scanningState[0], setScanning = scanningState[1];
1599
+ var errState = useState(''), scanErr = errState[0], setScanErr = errState[1];
1600
+ function run() {
1601
+ setScanning(true);
1602
+ setScanErr('');
1603
+ try {
1604
+ // Run synchronously: a deferred setState may not repaint in the
1605
+ // embedded client runtime, which made the audit look like it never ran.
1606
+ setResult(runAudit(props.entries));
1607
+ } catch (e) {
1608
+ setResult(null);
1609
+ setScanErr(String((e && e.message) || e || t('auditFail')));
1610
+ }
1611
+ setScanning(false);
1612
+ }
1613
+ // Auto-run as soon as the panel opens so results are visible immediately.
1614
+ useEffect(function () { run(); }, []);
1615
+ function sevLabel(s) { return s === 'high' ? t('auditHigh') : s === 'medium' ? t('auditMedium') : t('auditLow'); }
1616
+ return h('div', { className: 'cv-modal-backdrop', onMouseDown: function (e) { if (e.target === e.currentTarget) props.onCancel(); } },
1617
+ h('div', { className: 'cv-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('auditTitle'), tabIndex: -1,
1618
+ onKeyDown: function (e) { if (e.key === 'Escape') props.onCancel(); } },
1619
+ h('div', { className: 'cv-modal-head' }, h('h2', null, t('auditTitle'))),
1620
+ h('div', { className: 'cv-modal-hint' }, t('auditHint')),
1621
+ h('div', { className: 'cv-modal-body' },
1622
+ scanErr ? h('div', { className: 'cv-audit-clean', style: { color: 'var(--cv-err)' } }, scanErr) : null,
1623
+ result ? h('div', { className: 'cv-audit-summary' },
1624
+ h('span', null, h('b', null, result.scanned), ' ' + t('auditSummary')),
1625
+ h('span', null, h('b', null, result.issues.length), ' ' + t('auditIssues'))
1626
+ ) : null,
1627
+ result && result.issues.length === 0 ? h('div', { className: 'cv-audit-clean' }, '✓ ' + t('auditClean')) : null,
1628
+ result && result.issues.length > 0 ? h('div', { className: 'cv-audit-list' },
1629
+ result.issues.map(function (issue, i) {
1630
+ return h('div', { className: 'cv-audit-item', key: i },
1631
+ h('span', { className: 'cv-audit-sev cv-' + issue.severity }, sevLabel(issue.severity)),
1632
+ h('div', { className: 'cv-audit-body' },
1633
+ h('div', { className: 'cv-audit-name' }, issue.name),
1634
+ h('div', { className: 'cv-audit-desc' }, t(issue.kind) + ' — ' + t(issue.kind + 'Desc'))
1635
+ ),
1636
+ h('button', { className: 'cv-mini', onClick: function () { props.onEdit(issue.id); } }, t('auditEdit'))
1637
+ );
1638
+ })
1639
+ ) : null,
1640
+ result ? h('p', { className: 'cv-audit-note' }, 'ⓘ ', t('auditNote')) : null
1641
+ ),
1642
+ h('div', { className: 'cv-modal-foot' },
1643
+ h('button', { className: 'cv-btn', onClick: props.onCancel }, t('cancel')),
1644
+ h('button', { className: 'cv-btn cv-btn-primary', disabled: scanning, onClick: run }, scanning ? t('auditScanning') : (result ? t('auditRun') : t('auditRun')))
1645
+ )
1646
+ )
1647
+ );
1648
+ }
1649
+
1650
+ function VaultPanel() {
1651
+ var langState = useState(function () { return detectLang(locale); });
1652
+ var lang = langState[0], setLang = langState[1];
1653
+ function t(k) { return (DICTS[lang] && DICTS[lang][k]) || DICTS.en[k] || k; }
1654
+
1655
+ var entriesState = useState([]), entries = entriesState[0], setEntries = entriesState[1];
1656
+ var loadedState = useState(false), loaded = loadedState[0], setLoaded = loadedState[1];
1657
+ var queryState = useState(''), query = queryState[0], setQuery = queryState[1];
1658
+ var filterState = useState('all'), filter = filterState[0], setFilter = filterState[1];
1659
+ var sortState = useState('recent'), sort = sortState[0], setSort = sortState[1];
1660
+ var revealedState = useState({}), revealed = revealedState[0], setRevealed = revealedState[1];
1661
+ var editingState = useState(null), editing = editingState[0], setEditing = editingState[1];
1662
+ var toastState = useState(''), toast = toastState[0], setToast = toastState[1];
1663
+ var secRevState = useState(0), secRev = secRevState[0], setSecRev = secRevState[1];
1664
+ var importState = useState(false), importing = importState[0], setImporting = importState[1];
1665
+ var genState = useState(null), genTarget = genState[0], setGenTarget = genState[1];
1666
+ var auditState = useState(false), auditing = auditState[0], setAuditing = auditState[1];
1667
+ var confirmState = useState(null), confirmDlg = confirmState[0], setConfirmDlg = confirmState[1];
1668
+
1669
+ useEffect(function () {
1670
+ var initial = loadEntries();
1671
+ setEntries(initial);
1672
+ setLoaded(true);
1673
+ syncToHost(initial, true); // seed the Host snapshot on mount (immediate)
1674
+ }, []);
1675
+ useEffect(function () {
1676
+ return subscribeSecurity(function () { setSecRev(function (n) { return n + 1; }); });
1677
+ }, []);
1678
+ // Idle auto-lock: reset the last-activity timestamp on real user activity,
1679
+ // and tick once a second so the lock gate is re-evaluated when the timeout ends.
1680
+ useEffect(function () {
1681
+ var events = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll', 'wheel'];
1682
+ var last = 0;
1683
+ function activity() {
1684
+ var now = Date.now();
1685
+ if (now - last < 1000) return; // throttle; timestamp is in-memory and cheap
1686
+ last = now;
1687
+ noteActivity();
1688
+ }
1689
+ events.forEach(function (ev) { window.addEventListener(ev, activity, { passive: true }); });
1690
+ var tick = setInterval(function () { setSecRev(function (n) { return n + 1; }); }, 1000);
1691
+ return function () {
1692
+ events.forEach(function (ev) { window.removeEventListener(ev, activity, { passive: true }); });
1693
+ clearInterval(tick);
1694
+ };
1695
+ }, []);
1696
+ useEffect(function () { if (loaded) saveEntries(entries); }, [entries, loaded]);
1697
+ useEffect(function () {
1698
+ if (locale && typeof locale.subscribe === 'function') {
1699
+ var un = null;
1700
+ try { un = locale.subscribe(function () { setLang(detectLang(locale)); }); } catch (e) {}
1701
+ return function () { try { if (un) un(); } catch (e) {} };
1702
+ }
1703
+ }, []);
1704
+ useEffect(function () {
1705
+ if (!toast) return;
1706
+ var id = setTimeout(function () { setToast(''); }, 2200);
1707
+ return function () { clearTimeout(id); };
1708
+ }, [toast]);
1709
+
1710
+ function copyText(text) {
1711
+ try {
1712
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1713
+ navigator.clipboard.writeText(String(text)).then(
1714
+ function () { setToast(t('copied')); },
1715
+ function () { setToast(t('copyFail')); }
1716
+ );
1717
+ } else { setToast(t('copyFail')); }
1718
+ } catch (e) { setToast(t('copyFail')); }
1719
+ }
1720
+ function visitUrl(url) {
1721
+ var target = String(url || '').trim();
1722
+ if (!looksLikeUrl(target)) { setToast(t('visitFail')); return; }
1723
+ var sr = sidebarRight || (typeof ctxRef !== 'undefined' && ctxRef && ctxRef.get ? ctxRef.get('sidebarRight') : null);
1724
+ var lay = layout || (typeof ctxRef !== 'undefined' && ctxRef && ctxRef.get ? ctxRef.get('layout') : null);
1725
+ // The vault is a keyed main panel that replaces the Conversation, so the
1726
+ // sidebar-right controller has no mounted session surface while we are
1727
+ // selected; openTab() throws in that state. Return to the Conversation
1728
+ // first, then retry until the surface is mounted (bounded to ~1.2s).
1729
+ try { if (lay && typeof lay.selectPanel === 'function') lay.selectPanel(null); } catch (e) {}
1730
+ setToast(t('visitHint'));
1731
+ var attempts = 0;
1732
+ function openWhenReady() {
1733
+ var right = sr || (typeof ctxRef !== 'undefined' && ctxRef && ctxRef.get ? ctxRef.get('sidebarRight') : null);
1734
+ try {
1735
+ if (right && typeof right.openTab === 'function') {
1736
+ right.openTab('browser', { params: { url: target } });
1737
+ return;
1738
+ }
1739
+ } catch (e) {}
1740
+ if (++attempts < 12) { setTimeout(openWhenReady, 100); return; }
1741
+ try {
1742
+ var w = window.open(target, '_blank', 'noopener,noreferrer');
1743
+ if (!w) setToast(t('visitFail'));
1744
+ } catch (e) { setToast(t('visitFail')); }
1745
+ }
1746
+ setTimeout(openWhenReady, 50);
1747
+ }
1748
+ function toggleReveal(id) {
1749
+ setRevealed(function (prev) { var n = Object.assign({}, prev); n[id] = !n[id]; return n; });
1750
+ }
1751
+ function revealAll() { var n = {}; entries.forEach(function (e) { n[e.id] = true; }); setRevealed(n); }
1752
+ function hideAll() { setRevealed({}); }
1753
+ function allRevealed() { return entries.length > 0 && entries.every(function (e) { return !!revealed[e.id]; }); }
1754
+ function toggleAll() { if (allRevealed()) hideAll(); else revealAll(); }
1755
+ function openNew() {
1756
+ setEditing({ mode: 'new', draft: emptyDraft(filter !== 'all' ? filter : 'account') });
1757
+ }
1758
+ function openEdit(e) { setEditing({ mode: 'edit', draft: Object.assign(emptyDraft(e.category), e) }); }
1759
+ function setDraftField(field, value) {
1760
+ setEditing(function (prev) {
1761
+ var nd = Object.assign({}, prev.draft); nd[field] = value;
1762
+ return { mode: prev.mode, draft: nd };
1763
+ });
1764
+ }
1765
+ function saveDraft() {
1766
+ var d = editing.draft;
1767
+ if (!d.title || !String(d.title).trim()) { setToast(t('required')); return; }
1768
+ var item = Object.assign({}, d, {
1769
+ id: editing.mode === 'new' ? uid() : (d.id || uid()),
1770
+ title: String(d.title).trim(),
1771
+ category: d.category || 'account',
1772
+ createdAt: editing.mode === 'new' ? Date.now() : (d.createdAt || Date.now()),
1773
+ updatedAt: Date.now()
1774
+ });
1775
+ setEntries(function (prev) {
1776
+ if (editing.mode === 'new') return prev.concat([item]);
1777
+ return prev.map(function (x) { return x.id === item.id ? item : x; });
1778
+ });
1779
+ setEditing(null); setToast(t('saved'));
1780
+ }
1781
+ function delEntry(id) {
1782
+ if (!window.confirm(t('confirmDelete'))) return;
1783
+ setEntries(function (prev) { return prev.filter(function (x) { return x.id !== id; }); });
1784
+ setToast(t('deleted'));
1785
+ }
1786
+ function doExport() {
1787
+ if (entries.length === 0) { setToast(t('exportEmpty')); return; }
1788
+ setConfirmDlg({
1789
+ title: t('exportTitle'), message: t('exportWarn'), confirmLabel: t('exportConfirm'),
1790
+ onConfirm: function () {
1791
+ setConfirmDlg(null);
1792
+ setToast(exportBackup(entries) ? t('exportDone') : t('exportFail'));
1793
+ }
1794
+ });
1795
+ }
1796
+ function doImport(incoming, mode) {
1797
+ setEntries(function (prev) {
1798
+ if (mode === 'replace') return incoming.map(function (e) {
1799
+ var n = Object.assign({}, e); n.id = n.id || uid(); return n;
1800
+ });
1801
+ var byId = {};
1802
+ prev.forEach(function (e) { byId[e.id] = true; });
1803
+ var added = incoming.filter(function (e) {
1804
+ var id = e.id || uid();
1805
+ if (byId[id]) return false;
1806
+ byId[id] = true; return true;
1807
+ }).map(function (e) { return Object.assign({}, e, { id: e.id || uid() }); });
1808
+ return prev.concat(added);
1809
+ });
1810
+ setImporting(false);
1811
+ setToast(t('importDone'));
1812
+ }
1813
+ function useGeneratedPassword(pw) {
1814
+ if (genTarget && genTarget.field) setDraftField(genTarget.field, pw);
1815
+ setGenTarget(null);
1816
+ setToast(t('copied'));
1817
+ }
1818
+ function auditEditEntry(id) {
1819
+ var e = entries.filter(function (x) { return x.id === id; })[0];
1820
+ setAuditing(false);
1821
+ if (e) openEdit(e);
1822
+ }
1823
+
1824
+ var q = String(query).trim().toLowerCase();
1825
+ var list = entries.filter(function (e) {
1826
+ if (filter !== 'all' && (e.category || 'account') !== filter) return false;
1827
+ if (!q) return true;
1828
+ return searchText(e).indexOf(q) !== -1;
1829
+ });
1830
+ if (sort === 'title') {
1831
+ list.sort(function (a, b) { return String(a.title || '').localeCompare(String(b.title || '')); });
1832
+ } else if (sort === 'category') {
1833
+ list.sort(function (a, b) {
1834
+ var c = String(a.category || '').localeCompare(String(b.category || ''));
1835
+ return c !== 0 ? c : String(a.title || '').localeCompare(String(b.title || ''));
1836
+ });
1837
+ } else {
1838
+ list.sort(function (a, b) { return (b.updatedAt || b.createdAt || 0) - (a.updatedAt || a.createdAt || 0); });
1839
+ }
1840
+
1841
+ // Access-password gate: read secRev so lock changes re-render.
1842
+ if (isVaultLocked()) {
1843
+ return h(LockScreen, { t: t, idle: false, onUnlocked: function () { setSecRev(function (n) { return n + 1; }); } });
1844
+ }
1845
+
1846
+ return h('div', { className: 'cv-root cv-panelroot' },
1847
+ h('style', null, CSS),
1848
+ h('div', { className: 'cv-wrap' },
1849
+ h('div', { className: 'cv-head' },
1850
+ h('div', { className: 'cv-head-left' },
1851
+ h('div', { className: 'cv-head-icon', style: { color: 'var(--cv-brand)' } }, Shield(30)),
1852
+ h('div', null,
1853
+ h('h1', { className: 'cv-title' }, t('title')),
1854
+ h('p', { className: 'cv-sub' }, t('subtitle'))
1855
+ )
1856
+ ),
1857
+ h('div', { className: 'cv-io' },
1858
+ h('button', { className: 'cv-btn', onClick: function () { setAuditing(true); } }, '🛡 ' + t('auditButton')),
1859
+ h('button', { className: 'cv-btn', onClick: doExport }, t('export')),
1860
+ h('button', { className: 'cv-btn', onClick: function () { setImporting(true); } }, t('import')),
1861
+ h('button', { className: 'cv-btn cv-btn-primary', onClick: openNew }, '+ ' + t('add'))
1862
+ )
1863
+ ),
1864
+ h('div', { className: 'cv-notice' }, 'ⓘ ', t('localNotice')),
1865
+ h('div', { className: 'cv-toolbar' },
1866
+ h('input', { className: 'cv-search', placeholder: t('search'), value: query, onChange: function (ev) { setQuery(ev.target.value); } }),
1867
+ h('div', { className: 'cv-chips' }, FILTERS.map(function (f) {
1868
+ return h('button', { key: f.k, className: 'cv-chip' + (filter === f.k ? ' cv-chip-on' : ''), onClick: function () { setFilter(f.k); } }, t(f.label));
1869
+ })),
1870
+ h('div', { className: 'cv-sort' },
1871
+ h('span', { className: 'cv-sort-label' }, t('sort')),
1872
+ h('select', { className: 'cv-select', value: sort, onChange: function (ev) { setSort(ev.target.value); } },
1873
+ h('option', { value: 'recent' }, t('sortRecent')),
1874
+ h('option', { value: 'title' }, t('sortTitle')),
1875
+ h('option', { value: 'category' }, t('sortCategory'))
1876
+ )
1877
+ ),
1878
+ h('div', { className: 'cv-reveal' },
1879
+ h('button', { className: 'cv-mini', onClick: toggleAll }, allRevealed() ? t('hideAll') : t('revealAll'))
1880
+ )
1881
+ ),
1882
+ h('div', { className: 'cv-count' }, list.length + ' ' + t('items')),
1883
+ h('div', { className: 'cv-list-scroll' },
1884
+ h('div', { className: 'cv-list' },
1885
+ list.length === 0
1886
+ ? h('div', { className: 'cv-empty' },
1887
+ h('div', { className: 'cv-empty-icon' }, Shield(44)),
1888
+ h('h3', null, entries.length === 0 ? t('emptyTitle') : t('emptyFiltered')),
1889
+ h('p', null, entries.length === 0 ? t('emptyText') : t('search'))
1890
+ )
1891
+ : list.map(function (e) {
1892
+ return h(Card, {
1893
+ key: e.id, entry: e, t: t, revealed: !!revealed[e.id],
1894
+ onToggle: function () { toggleReveal(e.id); },
1895
+ onEdit: function () { openEdit(e); },
1896
+ onDelete: function () { delEntry(e.id); },
1897
+ onCopy: copyText,
1898
+ onVisit: visitUrl
1899
+ });
1900
+ })
1901
+ )
1902
+ )
1903
+ ),
1904
+ editing ? h(EditorModal, {
1905
+ t: t, draft: editing.draft, titleKey: editing.mode === 'new' ? 'editorNew' : 'editorEdit',
1906
+ onChange: setDraftField, onSave: saveDraft, onCancel: function () { setEditing(null); },
1907
+ onGenerate: function (field) { setGenTarget({ field: field }); }
1908
+ }) : null,
1909
+ importing ? h(ImportModal, {
1910
+ t: t, onImport: doImport, onCancel: function () { setImporting(false); }
1911
+ }) : null,
1912
+ auditing ? h(AuditModal, {
1913
+ t: t, entries: entries, onEdit: auditEditEntry, onCancel: function () { setAuditing(false); }
1914
+ }) : null,
1915
+ genTarget ? h(PasswordGeneratorModal, {
1916
+ t: t, onUse: useGeneratedPassword, onCopied: function () { setToast(t('copied')); },
1917
+ onCancel: function () { setGenTarget(null); }
1918
+ }) : null,
1919
+ confirmDlg ? h(ConfirmModal, {
1920
+ t: t, title: confirmDlg.title, message: confirmDlg.message, confirmLabel: confirmDlg.confirmLabel,
1921
+ onConfirm: confirmDlg.onConfirm, onCancel: function () { setConfirmDlg(null); }
1922
+ }) : null,
1923
+ toast ? h('div', { className: 'cv-toast', role: 'status' }, toast) : null
1924
+ );
1925
+ }
1926
+
1927
+ return {
1928
+ inject: ['slots'],
1929
+ apply(ctx) {
1930
+ ctxRef = ctx;
1931
+ layout = (ctx.get && ctx.get('layout')) || null;
1932
+ locale = (ctx.get && ctx.get('locale')) || null;
1933
+ sidebarRight = (ctx.get && ctx.get('sidebarRight')) || null;
1934
+ lang0 = detectLang(locale);
1935
+ if (locale && typeof locale.register === 'function') {
1936
+ try { locale.register('@local/dsh-credential-vault/ui', { en: DICTS.en, zh: DICTS.zh }); } catch (e) {}
1937
+ }
1938
+ ctx.slots.inject('sidebar.panellist', function () {
1939
+ return ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 20, label: tr('title') }, PanelIcon);
1940
+ });
1941
+ ctx.slots.inject('main', function () {
1942
+ return ctx.slots.register({ name: 'main', key: PANEL_ID }, VaultPanel);
1943
+ });
1944
+ ctx.slots.inject('settings.section', function () {
1945
+ return ctx.slots.register(
1946
+ { name: 'settings.section', id: PANEL_ID, order: 30, label: function () { return tr('title'); } },
1947
+ SettingsSection
1948
+ );
1949
+ });
1950
+ ctx.slots.inject('settings.section.icon', function () {
1951
+ return ctx.slots.register({ name: 'settings.section.icon', id: PANEL_ID }, SettingsIcon);
1952
+ });
1953
+ }
1954
+ };
1955
+ }
1956
+ });