dsh-memory-vault/client.js

646 lines
32 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Browser half of @itmarkovnpm/dsh-memory-vault.
*
* Настройки хранилища (volatile Config) и менеджер паролей в визуальном языке
* DeepSeek Harness: классы .dshmem-*, токены --dsw-alias-*, радиусы --dsw-radius-*.
*/
window.__ModuleLoader__.load({
id: '@itmarkovnpm/dsh-memory-vault',
factory(require) {
const React = require('react')
const h = React.createElement
const NS = 'plugins.memory'
const ENTRY = 'memory'
const API = '/api/dsh-memory'
const ru = {
title: 'Память и сейф',
mode: 'Хранилище для чтения',
modeLocal: 'Локальная SQLite',
modeServer: 'PostgreSQL на сервере',
host: 'Хост',
port: 'Порт',
database: 'База',
user: 'Пользователь',
password: 'Пароль',
passwordKeep: 'оставьте пустым, чтобы не менять',
autoFallback: 'Если сервер недоступен — читать локальную базу',
save: 'Сохранить',
saving: 'Сохраняем…',
saved: 'Сохранено',
failed: 'Не удалось сохранить',
unavailable: 'Настройки недоступны: плагин не запущен в этом профиле.',
loading: 'Загружаем настройки…',
hint: 'Запись всегда идёт в локальную SQLite и в PostgreSQL, когда сервер доступен. Чтение: сначала сервер, если там пусто — локальная база, найденное досылается на сервер. Пока сервер недоступен, всё работает локально и догоняется позже.',
secretsTitle: 'Пароли и ключи',
secretsCount: 'записей',
searchPlaceholder: 'Поиск по названию, логину или сайту',
secretsEmptyTitle: 'Пока пусто',
secretsEmptyText: 'Добавьте пароль, токен или ключ — он сохранится в обеих базах.',
noResultsTitle: 'Ничего не найдено',
noResultsText: 'Попробуйте другое название, логин или сайт.',
secretsGuide: 'Пароли, токены и ключи: добавить, изменить, удалить, показать.',
secretsLoading: 'Загружаем…',
secretsUnavailable: 'Менеджер паролей доступен только в веб-интерфейсе по http.',
addSecret: 'Добавить',
edit: 'Изменить',
remove: 'Удалить',
reveal: 'Показать',
hide: 'Скрыть',
copy: 'Копировать',
back: 'Назад',
nameLabel: 'Название',
loginLabel: 'Логин',
valueLabel: 'Пароль / ключ',
urlLabel: 'Сайт или сервис',
notesLabel: 'Заметка',
tagsLabel: 'Теги через запятую',
saveSecret: 'Сохранить',
cancel: 'Отмена',
confirmDelete: 'Удалить секрет без возможности восстановления?',
revealWarning: 'Значение скрывается через 30 секунд. Не пересылайте скриншоты; если покажете его агенту в чате — оно останется в логе сессии.',
syncLocal: 'не синхронизировано',
synced: 'синхронизировано',
error: 'Ошибка',
nameRequired: 'Укажите название',
valueRequired: 'Укажите пароль или ключ',
}
const en = {
title: 'Memory & Vault',
mode: 'Storage to read from',
modeLocal: 'Local SQLite',
modeServer: 'PostgreSQL on the server',
host: 'Host',
port: 'Port',
database: 'Database',
user: 'User',
password: 'Password',
passwordKeep: 'leave empty to keep the current one',
autoFallback: 'Fall back to the local base while the server is unavailable',
save: 'Save',
saving: 'Saving…',
saved: 'Saved',
failed: 'Save failed',
unavailable: 'Settings are unavailable: the plugin is not running in this profile.',
loading: 'Loading settings…',
hint: 'Every write goes to the local SQLite base and to PostgreSQL when the server is reachable. Reads ask the server first, fall back to the local base, and backfill what they find. While the server is down everything keeps working locally and syncs later.',
secretsTitle: 'Passwords and keys',
secretsCount: 'items',
searchPlaceholder: 'Search by name, login, or site',
secretsEmptyTitle: 'Nothing here yet',
secretsEmptyText: 'Add a password, token, or key — it is stored in both databases.',
noResultsTitle: 'Nothing found',
noResultsText: 'Try another name, login, or site.',
secretsGuide: 'Passwords, tokens, and keys: add, edit, delete, reveal.',
secretsLoading: 'Loading…',
secretsUnavailable: 'The password manager works only in the HTTP web interface.',
addSecret: 'Add',
edit: 'Edit',
remove: 'Delete',
reveal: 'Show',
hide: 'Hide',
copy: 'Copy',
back: 'Back',
nameLabel: 'Name',
loginLabel: 'Login',
valueLabel: 'Password / key',
urlLabel: 'Site or service',
notesLabel: 'Note',
tagsLabel: 'Tags, comma separated',
saveSecret: 'Save',
cancel: 'Cancel',
confirmDelete: 'Delete this secret permanently?',
revealWarning: 'The value hides after 30 seconds. Keep screenshots private; showing it to the agent in chat leaves it in the session log.',
syncLocal: 'not synced',
synced: 'synced',
error: 'Error',
nameRequired: 'Name is required',
valueRequired: 'Password or key is required',
}
/**
* Стили на токенах DSH. Имена классов с префиксом dshmem-, чтобы не
* пересекаться с хостом; цвета и радиусы — только через --dsw-*.
*/
const CSS = `
.dshmem { color: var(--dsw-alias-label-primary); font-family: var(--dsw-font-family); }
.dshmem-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
.dshmem-title { font-size: 14px; font-weight: 600; margin: 0; }
.dshmem-caption { font-size: 12px; color: var(--dsw-alias-label-tertiary); }
.dshmem-saved { color: var(--dsw-alias-state-success-primary); }
.dshmem-search { display: flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px;
border-radius: var(--dsw-radius-sm); background: var(--dsw-specific-selector);
color: var(--dsw-alias-label-tertiary); margin-bottom: 12px; }
.dshmem-search input { flex: 1; min-width: 0; border: 0; outline: 0; background: transparent;
color: var(--dsw-alias-label-primary); font: inherit; font-size: 13px; }
.dshmem-search input::placeholder { color: var(--dsw-alias-label-caption); }
.dshmem-btn { display: inline-flex; align-items: center; gap: 6px; height: 32px; padding: 0 12px;
border-radius: var(--dsw-radius-sm); border: 1px solid transparent; font: inherit; font-size: 13px;
font-weight: 500; cursor: pointer; transition: background var(--ds-transition-duration-fast) var(--ds-ease-in-out),
border-color var(--ds-transition-duration-fast) var(--ds-ease-in-out); }
.dshmem-btn-primary { background: var(--dsw-alias-button-primary-fill); color: var(--dsw-alias-label-primary-inverted); }
.dshmem-btn-primary:hover { background: var(--dsw-alias-button-primary-hover); }
.dshmem-btn-ghost { background: transparent; color: var(--dsw-alias-label-primary);
border-color: var(--dsw-alias-border-l2); }
.dshmem-btn-ghost:hover { background: var(--dsw-alias-interactive-bg-hover); }
.dshmem-btn:disabled { opacity: .5; cursor: default; }
.dshmem-icon-btn { display: inline-flex; align-items: center; justify-content: center;
width: 28px; height: 28px; padding: 0; border: 0; border-radius: var(--dsw-radius-xs);
background: transparent; color: var(--dsw-alias-label-secondary); cursor: pointer;
transition: background var(--ds-transition-duration-fast) var(--ds-ease-in-out); }
.dshmem-icon-btn:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
.dshmem-icon-btn-danger:hover { background: var(--dsw-alias-interactive-bg-hover-danger);
color: var(--dsw-alias-state-error-primary); }
.dshmem-row { display: flex; align-items: center; gap: 12px; padding: 10px 12px;
border-radius: var(--dsw-radius-md); background: var(--dsw-alias-card-fill);
border: 1px solid var(--dsw-alias-border-l1); margin-bottom: 8px; }
.dshmem-row:hover { background: var(--dsw-alias-card-fill-hover); }
.dshmem-avatar { width: 36px; height: 36px; flex: none; border-radius: 50%;
display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 600;
background: var(--dsw-alias-bg-layer-3); color: var(--dsw-alias-label-secondary); }
.dshmem-row-main { flex: 1; min-width: 0; }
.dshmem-row-name { font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dshmem-row-sub { font-size: 12px; color: var(--dsw-alias-label-tertiary);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dshmem-tags { display: flex; gap: 4px; margin-top: 4px; flex-wrap: wrap; }
.dshmem-tag { font-size: 11px; padding: 1px 8px; border-radius: var(--dsw-radius-xs);
background: var(--dsw-alias-markdown-tag); color: var(--dsw-alias-label-tertiary); }
.dshmem-value { display: flex; align-items: center; gap: 8px; margin-top: 6px; padding: 6px 10px;
border-radius: var(--dsw-radius-sm); border: 1px solid var(--dsw-alias-border-l2);
background: var(--dsw-alias-markdown-code-block); font-family: var(--ds-font-family-code);
font-size: 12px; word-break: break-all; }
.dshmem-value code { flex: 1; min-width: 0; color: var(--dsw-alias-label-primary); }
.dshmem-warn { font-size: 11px; color: var(--dsw-alias-label-caption); margin-top: 4px; }
.dshmem-dot { width: 7px; height: 7px; border-radius: 50%; flex: none; }
.dshmem-dot-ok { background: var(--dsw-alias-state-success-primary); }
.dshmem-dot-pending { background: var(--dsw-alias-state-warn-primary); }
.dshmem-form { padding: 14px; border-radius: var(--dsw-radius-md); border: 1px solid var(--dsw-alias-border-l2);
background: var(--dsw-alias-bg-layer-2); margin-bottom: 12px; }
.dshmem-form-head { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
.dshmem-form-title { font-size: 13px; font-weight: 600; }
.dshmem-grid { display: flex; gap: 10px; }
.dshmem-field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; min-width: 0; }
.dshmem-label { font-size: 12px; color: var(--dsw-alias-label-secondary); }
.dshmem-input { height: 34px; box-sizing: border-box; width: 100%; padding: 0 10px;
border-radius: var(--dsw-radius-sm); border: 1px solid var(--dsw-alias-border-l2);
background: var(--dsw-specific-input-major); color: var(--dsw-alias-label-primary);
font: inherit; font-size: 13px; outline: none; }
.dshmem-input::placeholder { color: var(--dsw-alias-label-caption); }
.dshmem-input:focus { border-color: var(--dsw-alias-border-selected); }
.dshmem-empty { text-align: center; padding: 28px 12px; border-radius: var(--dsw-radius-md);
border: 1px dashed var(--dsw-alias-border-l2); color: var(--dsw-alias-label-tertiary); }
.dshmem-empty-icon { display: flex; justify-content: center; margin-bottom: 8px; }
.dshmem-empty-title { font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-secondary); }
.dshmem-empty-text { font-size: 12px; margin-top: 4px; }
.dshmem-error { font-size: 12px; color: var(--dsw-alias-state-error-primary); }
.dshmem-hint { font-size: 12px; line-height: 1.5; color: var(--dsw-alias-label-tertiary); margin: 0 0 10px; }
.dshmem-actions { display: flex; align-items: center; gap: 8px; }
.dshmem-check { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 12px; }
`
const icon = (paths, size = 16) => h('svg', {
viewBox: '0 0 24 24', width: size, height: size, fill: 'none',
stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
'aria-hidden': true, style: { display: 'block', flex: 'none' },
}, paths.map((d, index) => h('path', { key: index, d })))
const icons = {
search: icon(['M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14z', 'M20 20l-3.5-3.5']),
plus: icon(['M12 5v14', 'M5 12h14']),
eye: icon(['M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6z', 'M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z']),
eyeOff: icon(['M3 3l18 18', 'M10.6 5.2A10.8 10.8 0 0 1 12 5c6.5 0 10 7 10 7a17 17 0 0 1-3.2 4.1', 'M6.3 6.5A17 17 0 0 0 2 12s3.5 7 10 7c1.6 0 3-.4 4.3-1']),
copy: icon(['M9 9h10v10H9z', 'M5 15V5h10']),
edit: icon(['M4 20h4l10-10-4-4L4 16v4z', 'M13.5 6.5l4 4']),
trash: icon(['M4 7h16', 'M9 7V5h6v2', 'M6 7l1 13h10l1-13']),
lock: icon(['M6 11h12v9H6z', 'M9 11V8a3 3 0 0 1 6 0v3'], 22),
back: icon(['M15 5l-7 7 7 7']),
check: icon(['M4 12l5 5L20 6']),
}
const avatarLetter = (name) => {
const match = /[a-zа-яё0-9]/i.exec(name)
return match === null ? '?' : match[0].toUpperCase()
}
const apiAvailable = () => typeof location !== 'undefined' && location.protocol !== 'file:'
async function api(action, body) {
const response = await fetch(`${API}?action=${encodeURIComponent(action)}`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-dsh-memory': '1' },
body: JSON.stringify(body ?? {}),
})
const data = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(data.error ?? `HTTP ${response.status}`)
return data
}
function textField(t, label, control) {
return h('label', { className: 'dshmem-field' },
h('span', { className: 'dshmem-label' }, label), control)
}
function textInput(value, onChange, options = {}) {
return h('input', {
className: 'dshmem-input',
type: options.type ?? 'text', value, placeholder: options.placeholder,
autoComplete: 'off', spellCheck: false,
onChange: event => onChange(event.target.value),
})
}
// ------------------------------------------------------------------
// Настройки хранилища
function fromSnapshot(value) {
const source = value !== null && typeof value === 'object' ? value : {}
return {
mode: source.mode === 'server' ? 'server' : 'local',
host: typeof source.host === 'string' ? source.host : '192.168.31.4',
port: typeof source.port === 'number' ? String(source.port) : '5434',
database: typeof source.database === 'string' ? source.database : 'dsh_memory',
user: typeof source.user === 'string' ? source.user : 'dsh_memory',
password: '',
autoFallback: source.autoFallback !== false,
}
}
function MemorySettings(props) {
const form = props.form
const t = props.t ?? (key => ru[key] ?? key)
const subscribe = React.useCallback(callback => (form === undefined ? () => {} : form.subscribe(callback)), [form])
const snapshot = React.useSyncExternalStore(
subscribe,
() => (form === undefined ? { status: 'unavailable' } : form.getSnapshot()),
() => ({ status: 'unavailable' }),
)
const [draft, setDraft] = React.useState(null)
const [notice, setNotice] = React.useState('')
const [busy, setBusy] = React.useState(false)
if (props.view !== 'page') return null
if (form === undefined || snapshot.status === 'unavailable') return h('p', { className: 'dshmem-caption' }, t('unavailable'))
if (snapshot.status === 'loading') return h('p', { className: 'dshmem-caption' }, t('loading'))
const value = snapshot.value !== null && typeof snapshot.value === 'object' ? snapshot.value : {}
const state = draft ?? fromSnapshot(value)
const patch = (key, next) => setDraft({ ...state, [key]: next })
const save = async () => {
if (busy) return
setBusy(true)
setNotice('')
const current = fromSnapshot(value)
const ops = []
const put = (key, next) => { if (next !== current[key]) ops.push({ op: 'set', path: [key], value: next }) }
put('mode', state.mode)
put('host', state.host.trim())
put('port', Number.parseInt(state.port, 10))
put('database', state.database.trim())
put('user', state.user.trim())
put('autoFallback', state.autoFallback)
if (state.password.length > 0) ops.push({ op: 'set', path: ['password'], value: state.password })
if (ops.length === 0) { setBusy(false); setNotice(t('saved')); return }
try {
const accepted = await form.mutate(ops, snapshot.revision)
setNotice(accepted ? t('saved') : t('failed'))
if (accepted) setDraft(null)
} catch (error) {
setNotice(`${t('failed')}: ${String(error?.message ?? error)}`)
} finally {
setBusy(false)
}
}
const serverFields = state.mode === 'server'
? h('div', null,
h('div', { className: 'dshmem-grid' },
textField(t, t('host'), textInput(state.host, next => patch('host', next))),
textField(t, t('port'), textInput(state.port, next => patch('port', next), { type: 'number' }))),
h('div', { className: 'dshmem-grid' },
textField(t, t('database'), textInput(state.database, next => patch('database', next))),
textField(t, t('user'), textInput(state.user, next => patch('user', next)))),
textField(t, t('password'), textInput(state.password, next => patch('password', next), { type: 'password', placeholder: t('passwordKeep') })),
h('label', { className: 'dshmem-check' },
h('input', { type: 'checkbox', checked: state.autoFallback, onChange: event => patch('autoFallback', event.target.checked) }),
t('autoFallback')))
: null
return h('div', { className: 'dshmem', style: { paddingBottom: '10px' } },
h('h4', { className: 'dshmem-title', style: { marginBottom: '10px' } }, t('title')),
textField(t, t('mode'), h('select', {
className: 'dshmem-input', value: state.mode,
onChange: event => patch('mode', event.target.value),
},
h('option', { value: 'local' }, t('modeLocal')),
h('option', { value: 'server' }, t('modeServer')))),
serverFields,
h('p', { className: 'dshmem-hint' }, t('hint')),
h('div', { className: 'dshmem-actions' },
h('button', { type: 'button', className: 'dshmem-btn dshmem-btn-primary', disabled: busy, onClick: save },
busy ? t('saving') : t('save')),
notice.length > 0 ? h('span', { className: 'dshmem-caption' }, notice) : null))
}
// ------------------------------------------------------------------
// Менеджер паролей
const EMPTY_FORM = { id: null, name: '', username: '', value: '', url: '', notes: '', tags: '' }
function SecretsManager(props) {
const t = props.t ?? (key => ru[key] ?? key)
const [rows, setRows] = React.useState(null)
const [error, setError] = React.useState('')
const [busy, setBusy] = React.useState(false)
const [form, setForm] = React.useState(null)
const [formError, setFormError] = React.useState('')
const [query, setQuery] = React.useState('')
const [revealed, setRevealed] = React.useState({})
const [copied, setCopied] = React.useState('')
const [flash, setFlash] = React.useState('')
const timers = React.useRef({})
const available = apiAvailable()
const load = React.useCallback(async () => {
if (!available) { setRows([]); return }
try {
const data = await api('list', { limit: 200 })
setRows(Array.isArray(data.secrets) ? data.secrets : [])
setError('')
} catch (loadError) {
setError(String(loadError?.message ?? loadError))
setRows([])
}
}, [available])
React.useEffect(() => { load() }, [load])
React.useEffect(() => () => { Object.values(timers.current).forEach(clearTimeout) }, [])
const scheduleHide = (id) => {
if (timers.current[id] !== undefined) clearTimeout(timers.current[id])
timers.current[id] = setTimeout(() => {
setRevealed(current => {
const next = { ...current }
delete next[id]
return next
})
delete timers.current[id]
}, 30000)
}
const run = async (action, body) => {
setBusy(true)
setError('')
try {
const data = await api(action, body)
await load()
return data
} catch (actionError) {
setError(String(actionError?.message ?? actionError))
return undefined
} finally {
setBusy(false)
}
}
const startEdit = (row) => {
setFormError('')
setForm({
id: row.id, name: row.name, username: row.username ?? '', value: '',
url: row.url ?? '', notes: row.notes ?? '', tags: (row.tags ?? []).join(', '),
})
}
const saveForm = async () => {
if (form === null) return
if (form.name.trim().length === 0) { setFormError(t('nameRequired')); return }
let value = form.value
if (form.id !== null && value.length === 0) {
const data = await run('get', { match: form.id })
value = data?.secret?.value ?? ''
if (value.length === 0) { setFormError(t('valueRequired')); return }
}
if (form.id === null && value.length === 0) { setFormError(t('valueRequired')); return }
const saved = await run('save', {
name: form.name.trim(), value,
username: form.username || undefined,
url: form.url || undefined,
notes: form.notes || undefined,
tags: form.tags.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0),
})
if (saved !== undefined) {
setForm(null)
setFormError('')
setFlash(t('saved'))
setTimeout(() => setFlash(''), 1800)
}
}
const remove = async (row) => {
if (typeof window !== 'undefined' && !window.confirm(t('confirmDelete'))) return
await run('forget', { match: row.id })
}
const reveal = async (row) => {
if (revealed[row.id] !== undefined) {
if (timers.current[row.id] !== undefined) clearTimeout(timers.current[row.id])
delete timers.current[row.id]
const next = { ...revealed }
delete next[row.id]
setRevealed(next)
return
}
const data = await run('get', { match: row.id })
if (data?.secret !== undefined) {
setRevealed({ ...revealed, [row.id]: data.secret.value })
scheduleHide(row.id)
}
}
const copyValue = async (row) => {
try {
const data = await api('get', { match: row.id })
const value = data?.secret?.value ?? ''
if (value.length === 0) return
if (typeof navigator !== 'undefined' && navigator.clipboard !== undefined) {
await navigator.clipboard.writeText(value)
}
setCopied(row.id)
setTimeout(() => setCopied(current => (current === row.id ? '' : current)), 1600)
} catch (copyError) {
setError(String(copyError?.message ?? copyError))
}
}
if (!available) return h('p', { className: 'dshmem-caption' }, t('secretsUnavailable'))
const needle = query.trim().toLowerCase()
const visible = (rows ?? []).filter(row => needle.length === 0
|| row.name.toLowerCase().includes(needle)
|| String(row.username ?? '').toLowerCase().includes(needle)
|| String(row.url ?? '').toLowerCase().includes(needle)
|| (Array.isArray(row.tags) && row.tags.some(tag => tag.includes(needle))))
const header = h('div', { className: 'dshmem-head' },
h('div', null,
h('div', { style: { display: 'flex', alignItems: 'baseline', gap: '8px' } },
h('h4', { className: 'dshmem-title' }, t('secretsTitle')),
h('span', { className: 'dshmem-caption' }, `${rows === null ? '—' : rows.length} ${t('secretsCount')}`)),
flash.length > 0 ? h('div', { className: 'dshmem-caption dshmem-saved' }, flash) : null),
h('button', {
type: 'button', className: 'dshmem-btn dshmem-btn-primary',
onClick: () => { setFormError(''); setForm({ ...EMPTY_FORM }) },
}, icons.plus, t('addSecret')))
const search = h('label', { className: 'dshmem-search' },
icons.search,
h('input', {
value: query, placeholder: t('searchPlaceholder'),
onChange: event => setQuery(event.target.value),
}))
const formView = form === null ? null : h('div', { className: 'dshmem-form' },
h('div', { className: 'dshmem-form-head' },
h('button', {
type: 'button', className: 'dshmem-icon-btn', 'aria-label': t('back'),
onClick: () => { setForm(null); setFormError('') },
}, icons.back),
h('span', { className: 'dshmem-form-title' }, form.id === null ? t('addSecret') : t('edit'))),
h('div', { className: 'dshmem-grid' },
textField(t, t('nameLabel'), textInput(form.name, next => setForm({ ...form, name: next }))),
textField(t, t('loginLabel'), textInput(form.username, next => setForm({ ...form, username: next })))),
textField(t, t('valueLabel'), textInput(form.value, next => setForm({ ...form, value: next }), {
type: 'password', placeholder: form.id === null ? '' : t('passwordKeep'),
})),
h('div', { className: 'dshmem-grid' },
textField(t, t('urlLabel'), textInput(form.url, next => setForm({ ...form, url: next }))),
textField(t, t('tagsLabel'), textInput(form.tags, next => setForm({ ...form, tags: next })))),
textField(t, t('notesLabel'), textInput(form.notes, next => setForm({ ...form, notes: next }))),
formError.length > 0 ? h('p', { className: 'dshmem-error' }, formError) : null,
h('div', { className: 'dshmem-actions' },
h('button', { type: 'button', className: 'dshmem-btn dshmem-btn-primary', disabled: busy, onClick: saveForm }, t('saveSecret')),
h('button', { type: 'button', className: 'dshmem-btn dshmem-btn-ghost', onClick: () => { setForm(null); setFormError('') } }, t('cancel'))))
const rowView = (row) => {
const value = revealed[row.id]
const subtitle = [row.username ? `login: ${row.username}` : null, row.url ?? null].filter(Boolean).join(' · ')
return h('div', { key: row.id, className: 'dshmem-row' },
h('div', { className: 'dshmem-avatar' }, avatarLetter(row.name)),
h('div', { className: 'dshmem-row-main' },
h('div', { className: 'dshmem-row-name' }, row.name),
h('div', { className: 'dshmem-row-sub' }, subtitle.length > 0 ? subtitle : '—'),
Array.isArray(row.tags) && row.tags.length > 0
? h('div', { className: 'dshmem-tags' }, row.tags.map(tag => h('span', { key: tag, className: 'dshmem-tag' }, `#${tag}`)))
: null,
value !== undefined
? h('div', null,
h('div', { className: 'dshmem-value' },
h('code', null, value),
h('button', {
type: 'button', className: 'dshmem-icon-btn', title: t('copy'),
onClick: () => copyValue(row),
}, copied === row.id ? icons.check : icons.copy)),
h('div', { className: 'dshmem-warn' }, t('revealWarning')))
: null),
h('div', { className: 'dshmem-actions' },
h('button', {
type: 'button', className: 'dshmem-icon-btn', title: value !== undefined ? t('hide') : t('reveal'),
onClick: () => reveal(row),
}, value !== undefined ? icons.eyeOff : icons.eye),
h('button', {
type: 'button', className: 'dshmem-icon-btn', title: t('copy'),
onClick: () => copyValue(row),
}, copied === row.id ? icons.check : icons.copy),
h('button', { type: 'button', className: 'dshmem-icon-btn', title: t('edit'), onClick: () => startEdit(row) }, icons.edit),
h('button', {
type: 'button', className: 'dshmem-icon-btn dshmem-icon-btn-danger',
title: t('remove'), disabled: busy, onClick: () => remove(row),
}, icons.trash)),
h('span', {
title: row.synced === false ? t('syncLocal') : t('synced'),
className: `dshmem-dot ${row.synced === false ? 'dshmem-dot-pending' : 'dshmem-dot-ok'}`,
}))
}
const empty = rows !== null && visible.length === 0
? h('div', { className: 'dshmem-empty' },
h('div', { className: 'dshmem-empty-icon' }, needle.length > 0 ? icons.search : icons.lock),
h('div', { className: 'dshmem-empty-title' }, needle.length > 0 ? t('noResultsTitle') : t('secretsEmptyTitle')),
h('div', { className: 'dshmem-empty-text' }, needle.length > 0 ? t('noResultsText') : t('secretsEmptyText')))
: null
return h('div', { className: 'dshmem', style: { paddingBottom: '10px' } },
h('style', null, CSS),
header,
form !== null ? formView : null,
form === null ? search : null,
error.length > 0 ? h('p', { className: 'dshmem-error' }, `${t('error')}: ${error}`) : null,
rows === null
? h('p', { className: 'dshmem-caption' }, t('secretsLoading'))
: h('div', null, visible.map(rowView), empty))
}
// ------------------------------------------------------------------
const TYPE_ID = '@itmarkovnpm/dsh-memory-vault/secrets'
const KIND = 'memory-secrets'
function SecretsPane(props) {
const t = props.t ?? (key => ru[key] ?? key)
return h('div', {
style: { padding: '12px', overflowY: 'auto', height: '100%', boxSizing: 'border-box' },
}, h(SecretsManager, { t }))
}
return {
inject: ['slots', 'configForms', 'locale'],
apply(ctx) {
let t = (key) => ru[key] ?? key
try {
ctx.locale.register(NS, { ru, en })
const bound = ctx.locale.bind(NS)
if (typeof bound === 'function') t = bound
} catch {}
const tabs = ctx.get('sidebarRightTabs')
if (tabs !== undefined && typeof tabs.register === 'function') {
try {
ctx.effect(() => tabs.register({
id: TYPE_ID,
kind: KIND,
title: () => t('secretsTitle'),
guide: [{
id: 'secrets',
order: 25,
title: () => t('secretsTitle'),
description: () => t('secretsGuide'),
}],
}))
ctx.effect(() => ctx.slots.register({
name: 'sidebar.right.pane.tab',
key: TYPE_ID,
locale: NS,
inject: () => ({ t }),
}, SecretsPane))
} catch {}
}
let form
try { form = ctx.configForms.get(ENTRY) } catch {}
try {
ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
name: 'plugins.bundle.config',
key: '@itmarkovnpm/dsh-memory-vault',
locale: NS,
inject: () => ({ form, t }),
}, function MemoryCard(props) {
return h('div', null,
h(MemorySettings, props),
h(SecretsManager, { t: props.t }))
}))
} catch {}
},
}
},
})