@tavlo-dsh/dsh-plugin-hooks 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +29 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +5 -0
- package/index.js +793 -0
- package/lib/client.js +5 -0
- package/lib/client.js.LEGAL.txt +4 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +72 -4
- package/src/config-store.js +804 -0
- package/src/default-scripts.js +193 -0
- package/src/dsh-hook-bridge.js +999 -0
- package/src/event-hub.js +198 -0
- package/src/hook-catalog.js +359 -0
- package/src/notification-dispatcher.js +486 -0
- package/src/script-runner.js +671 -0
- package/src/sound-manager.js +403 -0
- package/src/system-notifier.js +549 -0
- package/src/third-party-providers.js +1137 -0
|
@@ -0,0 +1,804 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent configuration and encrypted/credential-backed secret store.
|
|
3
|
+
* Uses `ctx.storageDomain` for non-secret settings (with atomic JSON file fallback)
|
|
4
|
+
* and `ctx.credentials` (`GrantRecord`) for third-party webhook tokens/secrets.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
8
|
+
import { chmod, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { credentialKey } from '@deepseek-ai/dsh-credentials'
|
|
11
|
+
import { defineDomain } from '@deepseek-ai/dsh-storage-domain'
|
|
12
|
+
import { z } from 'zod'
|
|
13
|
+
import {
|
|
14
|
+
createDefaultCategoryEvents,
|
|
15
|
+
HOOK_MOUNT_POINTS,
|
|
16
|
+
NOTIFICATION_CATEGORIES,
|
|
17
|
+
getMountPoint,
|
|
18
|
+
} from './hook-catalog.js'
|
|
19
|
+
import { ensureDefaultScripts, getDefaultScriptById } from './default-scripts.js'
|
|
20
|
+
import { clampTimeoutSeconds, deleteCustomScriptFile } from './script-runner.js'
|
|
21
|
+
import { getCustomSoundInfo } from './sound-manager.js'
|
|
22
|
+
import {
|
|
23
|
+
getSecretFieldKeys,
|
|
24
|
+
PROVIDER_DEFINITIONS,
|
|
25
|
+
PROVIDER_IDS,
|
|
26
|
+
validateProviderConfig,
|
|
27
|
+
} from './third-party-providers.js'
|
|
28
|
+
|
|
29
|
+
export const MAX_THIRD_PARTY_TARGETS = 20
|
|
30
|
+
export const SECRET_CREDENTIAL_KEY = credentialKey('tavlo-hooks', 'third-party-secrets')
|
|
31
|
+
|
|
32
|
+
const storedConfigEnvelopeSchema = z.object({
|
|
33
|
+
version: z.literal(1),
|
|
34
|
+
revision: z.number().int().nonnegative(),
|
|
35
|
+
config: z.record(z.string(), z.unknown()),
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
export const hooksConfigDomain = defineDomain({
|
|
39
|
+
name: 'tavlo_hooks_config',
|
|
40
|
+
version: 1,
|
|
41
|
+
layout: 'single',
|
|
42
|
+
global: {
|
|
43
|
+
initial: { version: 1, revision: 0, config: {} },
|
|
44
|
+
schema: storedConfigEnvelopeSchema,
|
|
45
|
+
},
|
|
46
|
+
tables: {},
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
export class ConfigStoreError extends Error {
|
|
50
|
+
constructor(code, message) {
|
|
51
|
+
super(message)
|
|
52
|
+
this.code = code
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function maskSecretPreview(value) {
|
|
57
|
+
if (typeof value !== 'string' || !value) return ''
|
|
58
|
+
if (value.length <= 4) return '••••'
|
|
59
|
+
return `••••${value.slice(-4)}`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function clampAutoCloseSeconds(raw) {
|
|
63
|
+
const n = Math.round(Number(raw))
|
|
64
|
+
if (!Number.isFinite(n)) return 60
|
|
65
|
+
return Math.min(3600, Math.max(5, n))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function clampFlashCount(raw) {
|
|
69
|
+
const n = Math.round(Number(raw))
|
|
70
|
+
if (!Number.isFinite(n)) return 5
|
|
71
|
+
return Math.min(20, Math.max(1, n))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function normalizeCategoryEvents(rawEvents) {
|
|
75
|
+
const defaults = createDefaultCategoryEvents()
|
|
76
|
+
const out = {}
|
|
77
|
+
for (const cat of NOTIFICATION_CATEGORIES) {
|
|
78
|
+
out[cat] = typeof rawEvents?.[cat] === 'boolean' ? rawEvents[cat] : defaults[cat]
|
|
79
|
+
}
|
|
80
|
+
return out
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function buildDefaultScriptsForMountPoint(mp) {
|
|
84
|
+
const scripts = []
|
|
85
|
+
for (const scriptId of mp.defaultScriptIds) {
|
|
86
|
+
const def = getDefaultScriptById(scriptId)
|
|
87
|
+
if (!def) continue
|
|
88
|
+
scripts.push({
|
|
89
|
+
id: def.id,
|
|
90
|
+
kind: 'default',
|
|
91
|
+
name: def.nameZh,
|
|
92
|
+
filename: def.filename,
|
|
93
|
+
enabled: Boolean(mp.defaultEnabled && def.enabledByDefault),
|
|
94
|
+
matcher: '',
|
|
95
|
+
timeoutSeconds: 10,
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
return scripts
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function buildDefaultConfig() {
|
|
102
|
+
const mountPoints = {}
|
|
103
|
+
for (const mp of HOOK_MOUNT_POINTS) {
|
|
104
|
+
mountPoints[mp.id] = {
|
|
105
|
+
enabled: Boolean(mp.defaultEnabled),
|
|
106
|
+
bellEnabled: Boolean(mp.defaultBell),
|
|
107
|
+
scripts: buildDefaultScriptsForMountPoint(mp),
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
inApp: {
|
|
112
|
+
enabled: true,
|
|
113
|
+
autoCloseEnabled: true,
|
|
114
|
+
autoCloseSeconds: 60,
|
|
115
|
+
},
|
|
116
|
+
systemNotifications: {
|
|
117
|
+
enabled: true,
|
|
118
|
+
suppressWhenFocused: true,
|
|
119
|
+
taskbarAttentionEnabled: true,
|
|
120
|
+
taskbarAttentionMode: 'finite',
|
|
121
|
+
taskbarAttentionFlashCount: 5,
|
|
122
|
+
customSoundFilename: null,
|
|
123
|
+
},
|
|
124
|
+
thirdParty: {
|
|
125
|
+
enabled: true,
|
|
126
|
+
targets: [],
|
|
127
|
+
},
|
|
128
|
+
mountPoints,
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function normalizeScriptItem(raw, fallbackMountPoint) {
|
|
133
|
+
if (!raw || typeof raw !== 'object') return null
|
|
134
|
+
if (raw.kind === 'default') {
|
|
135
|
+
const def = getDefaultScriptById(raw.id)
|
|
136
|
+
if (!def) return null
|
|
137
|
+
return {
|
|
138
|
+
id: def.id,
|
|
139
|
+
kind: 'default',
|
|
140
|
+
name: typeof raw.name === 'string' && raw.name.trim() ? raw.name.trim().slice(0, 120) : def.nameZh,
|
|
141
|
+
filename: def.filename,
|
|
142
|
+
enabled:
|
|
143
|
+
typeof raw.enabled === 'boolean'
|
|
144
|
+
? raw.enabled
|
|
145
|
+
: Boolean(fallbackMountPoint.defaultEnabled && def.enabledByDefault),
|
|
146
|
+
matcher: typeof raw.matcher === 'string' ? raw.matcher.trim().slice(0, 256) : '',
|
|
147
|
+
timeoutSeconds: clampTimeoutSeconds(raw.timeoutSeconds),
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (raw.kind === 'custom' && typeof raw.id === 'string' && typeof raw.filename === 'string') {
|
|
151
|
+
return {
|
|
152
|
+
id: raw.id,
|
|
153
|
+
kind: 'custom',
|
|
154
|
+
name: typeof raw.name === 'string' && raw.name.trim() ? raw.name.trim().slice(0, 120) : raw.filename,
|
|
155
|
+
filename: raw.filename,
|
|
156
|
+
...(typeof raw.originalFilename === 'string' ? { originalFilename: raw.originalFilename } : {}),
|
|
157
|
+
enabled: typeof raw.enabled === 'boolean' ? raw.enabled : true,
|
|
158
|
+
matcher: typeof raw.matcher === 'string' ? raw.matcher.trim().slice(0, 256) : '',
|
|
159
|
+
timeoutSeconds: clampTimeoutSeconds(raw.timeoutSeconds),
|
|
160
|
+
...(typeof raw.createdAt === 'string' ? { createdAt: raw.createdAt } : {}),
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return null
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function normalizeConfig(raw) {
|
|
167
|
+
const defaults = buildDefaultConfig()
|
|
168
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
169
|
+
|
|
170
|
+
const inAppSrc = src.inApp && typeof src.inApp === 'object' ? src.inApp : {}
|
|
171
|
+
const sysSrc = src.systemNotifications && typeof src.systemNotifications === 'object' ? src.systemNotifications : {}
|
|
172
|
+
const tpSrc = src.thirdParty && typeof src.thirdParty === 'object' ? src.thirdParty : {}
|
|
173
|
+
const mpSrc = src.mountPoints && typeof src.mountPoints === 'object' ? src.mountPoints : {}
|
|
174
|
+
|
|
175
|
+
const rawTargets = Array.isArray(tpSrc.targets) ? tpSrc.targets.slice(0, MAX_THIRD_PARTY_TARGETS) : []
|
|
176
|
+
const targets = []
|
|
177
|
+
for (const row of rawTargets) {
|
|
178
|
+
if (!row || typeof row !== 'object') continue
|
|
179
|
+
if (!PROVIDER_IDS.includes(row.provider)) continue
|
|
180
|
+
const id = typeof row.id === 'string' && row.id.trim() ? row.id.trim() : `tp_${randomUUID()}`
|
|
181
|
+
const name = typeof row.name === 'string' && row.name.trim() ? row.name.trim().slice(0, 64) : row.provider
|
|
182
|
+
const secretKeys = new Set(getSecretFieldKeys(row.provider) ?? [])
|
|
183
|
+
const cleanConfig = {}
|
|
184
|
+
if (row.config && typeof row.config === 'object') {
|
|
185
|
+
for (const [k, v] of Object.entries(row.config)) {
|
|
186
|
+
if (!secretKeys.has(k) && v !== undefined) {
|
|
187
|
+
cleanConfig[k] = v
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
targets.push({
|
|
192
|
+
id,
|
|
193
|
+
name,
|
|
194
|
+
provider: row.provider,
|
|
195
|
+
enabled: typeof row.enabled === 'boolean' ? row.enabled : true,
|
|
196
|
+
events: normalizeCategoryEvents(row.events),
|
|
197
|
+
config: cleanConfig,
|
|
198
|
+
})
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const mountPoints = {}
|
|
202
|
+
for (const mp of HOOK_MOUNT_POINTS) {
|
|
203
|
+
const existing = mpSrc[mp.id] && typeof mpSrc[mp.id] === 'object' ? mpSrc[mp.id] : null
|
|
204
|
+
if (!existing) {
|
|
205
|
+
mountPoints[mp.id] = defaults.mountPoints[mp.id]
|
|
206
|
+
continue
|
|
207
|
+
}
|
|
208
|
+
const existingScripts = Array.isArray(existing.scripts)
|
|
209
|
+
? existing.scripts.map((s) => normalizeScriptItem(s, mp)).filter(Boolean)
|
|
210
|
+
: []
|
|
211
|
+
const seenIds = new Set(existingScripts.map((s) => s.id))
|
|
212
|
+
for (const defScript of buildDefaultScriptsForMountPoint(mp)) {
|
|
213
|
+
if (!seenIds.has(defScript.id)) {
|
|
214
|
+
existingScripts.unshift(defScript)
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
mountPoints[mp.id] = {
|
|
218
|
+
enabled: typeof existing.enabled === 'boolean' ? existing.enabled : Boolean(mp.defaultEnabled),
|
|
219
|
+
bellEnabled: typeof existing.bellEnabled === 'boolean' ? existing.bellEnabled : Boolean(mp.defaultBell),
|
|
220
|
+
scripts: existingScripts,
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
inApp: {
|
|
226
|
+
enabled: typeof inAppSrc.enabled === 'boolean' ? inAppSrc.enabled : defaults.inApp.enabled,
|
|
227
|
+
autoCloseEnabled:
|
|
228
|
+
typeof inAppSrc.autoCloseEnabled === 'boolean'
|
|
229
|
+
? inAppSrc.autoCloseEnabled
|
|
230
|
+
: defaults.inApp.autoCloseEnabled,
|
|
231
|
+
autoCloseSeconds:
|
|
232
|
+
inAppSrc.autoCloseSeconds !== undefined
|
|
233
|
+
? clampAutoCloseSeconds(inAppSrc.autoCloseSeconds)
|
|
234
|
+
: defaults.inApp.autoCloseSeconds,
|
|
235
|
+
},
|
|
236
|
+
systemNotifications: {
|
|
237
|
+
enabled: typeof sysSrc.enabled === 'boolean' ? sysSrc.enabled : defaults.systemNotifications.enabled,
|
|
238
|
+
suppressWhenFocused:
|
|
239
|
+
typeof sysSrc.suppressWhenFocused === 'boolean'
|
|
240
|
+
? sysSrc.suppressWhenFocused
|
|
241
|
+
: defaults.systemNotifications.suppressWhenFocused,
|
|
242
|
+
taskbarAttentionEnabled:
|
|
243
|
+
typeof sysSrc.taskbarAttentionEnabled === 'boolean'
|
|
244
|
+
? sysSrc.taskbarAttentionEnabled
|
|
245
|
+
: defaults.systemNotifications.taskbarAttentionEnabled,
|
|
246
|
+
taskbarAttentionMode:
|
|
247
|
+
sysSrc.taskbarAttentionMode === 'untilFocused' ? 'untilFocused' : 'finite',
|
|
248
|
+
taskbarAttentionFlashCount:
|
|
249
|
+
sysSrc.taskbarAttentionFlashCount !== undefined
|
|
250
|
+
? clampFlashCount(sysSrc.taskbarAttentionFlashCount)
|
|
251
|
+
: defaults.systemNotifications.taskbarAttentionFlashCount,
|
|
252
|
+
customSoundFilename:
|
|
253
|
+
typeof sysSrc.customSoundFilename === 'string' && sysSrc.customSoundFilename.trim()
|
|
254
|
+
? sysSrc.customSoundFilename.trim()
|
|
255
|
+
: null,
|
|
256
|
+
},
|
|
257
|
+
thirdParty: {
|
|
258
|
+
enabled: typeof tpSrc.enabled === 'boolean' ? tpSrc.enabled : defaults.thirdParty.enabled,
|
|
259
|
+
targets,
|
|
260
|
+
},
|
|
261
|
+
mountPoints,
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function atomicWriteJson(filePath, data, mode) {
|
|
266
|
+
await mkdir(path.dirname(filePath), { recursive: true })
|
|
267
|
+
const tmpPath = `${filePath}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`
|
|
268
|
+
try {
|
|
269
|
+
await writeFile(tmpPath, JSON.stringify(data, null, 2), 'utf8')
|
|
270
|
+
if (mode !== undefined && process.platform !== 'win32') {
|
|
271
|
+
await chmod(tmpPath, mode).catch(() => {})
|
|
272
|
+
}
|
|
273
|
+
await rename(tmpPath, filePath)
|
|
274
|
+
} catch (error) {
|
|
275
|
+
await unlink(tmpPath).catch(() => {})
|
|
276
|
+
throw error
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function normalizeSecretsPayload(payload) {
|
|
281
|
+
const out = {}
|
|
282
|
+
if (!payload || typeof payload !== 'object') return out
|
|
283
|
+
const targets = payload.targets && typeof payload.targets === 'object' ? payload.targets : {}
|
|
284
|
+
for (const [targetId, fields] of Object.entries(targets)) {
|
|
285
|
+
if (!fields || typeof fields !== 'object') continue
|
|
286
|
+
const cleanFields = {}
|
|
287
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
288
|
+
if (typeof v === 'string' && v.length > 0) {
|
|
289
|
+
cleanFields[k] = v
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (Object.keys(cleanFields).length > 0) {
|
|
293
|
+
out[targetId] = cleanFields
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return out
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function buildProviderDefaultConfig(providerId) {
|
|
300
|
+
const def = PROVIDER_DEFINITIONS.find((item) => item.id === providerId)
|
|
301
|
+
const out = {}
|
|
302
|
+
if (!def) return out
|
|
303
|
+
for (const field of def.fields) {
|
|
304
|
+
if (field.kind !== 'secret' && field.defaultValue !== undefined) {
|
|
305
|
+
out[field.key] = field.defaultValue
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return out
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Create the config and secrets store.
|
|
313
|
+
*/
|
|
314
|
+
export function createConfigStore({ getDataDir, storageDomain, credentials, logger } = {}) {
|
|
315
|
+
let domain = null
|
|
316
|
+
let revision = 0
|
|
317
|
+
let config = buildDefaultConfig()
|
|
318
|
+
let secretsByTarget = {}
|
|
319
|
+
let writeTail = Promise.resolve()
|
|
320
|
+
let initialized = false
|
|
321
|
+
|
|
322
|
+
const configFallbackPath = () => path.join(getDataDir(), 'hooks', 'config.json')
|
|
323
|
+
const secretsFallbackPath = () => path.join(getDataDir(), 'hooks', 'secrets.json')
|
|
324
|
+
|
|
325
|
+
async function loadSecrets() {
|
|
326
|
+
if (credentials && typeof credentials.readRecord === 'function') {
|
|
327
|
+
try {
|
|
328
|
+
const record = await credentials.readRecord(SECRET_CREDENTIAL_KEY)
|
|
329
|
+
if (record?.kind === 'grant') {
|
|
330
|
+
return normalizeSecretsPayload(record.payload)
|
|
331
|
+
}
|
|
332
|
+
return {}
|
|
333
|
+
} catch (error) {
|
|
334
|
+
logger?.warn?.(`tavlo-hooks: credentials read failed: ${error?.message || error}`)
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
const raw = await readFile(secretsFallbackPath(), 'utf8')
|
|
339
|
+
return normalizeSecretsPayload(JSON.parse(raw))
|
|
340
|
+
} catch {
|
|
341
|
+
return {}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
async function persistSecrets(nextSecrets) {
|
|
346
|
+
const clean = normalizeSecretsPayload({ targets: nextSecrets })
|
|
347
|
+
if (credentials && typeof credentials.modifyRecord === 'function') {
|
|
348
|
+
if (Object.keys(clean).length === 0 && typeof credentials.deleteRecord === 'function') {
|
|
349
|
+
await credentials.deleteRecord(SECRET_CREDENTIAL_KEY)
|
|
350
|
+
} else {
|
|
351
|
+
await credentials.modifyRecord(SECRET_CREDENTIAL_KEY, async () => ({
|
|
352
|
+
kind: 'grant',
|
|
353
|
+
payload: { version: 1, targets: clean },
|
|
354
|
+
}))
|
|
355
|
+
}
|
|
356
|
+
return clean
|
|
357
|
+
}
|
|
358
|
+
await atomicWriteJson(secretsFallbackPath(), { version: 1, targets: clean }, 0o600)
|
|
359
|
+
return clean
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function persistDocument(nextRevision, nextConfig) {
|
|
363
|
+
const doc = {
|
|
364
|
+
version: 1,
|
|
365
|
+
revision: nextRevision,
|
|
366
|
+
config: nextConfig,
|
|
367
|
+
}
|
|
368
|
+
if (domain) {
|
|
369
|
+
await domain.global.set(doc)
|
|
370
|
+
return
|
|
371
|
+
}
|
|
372
|
+
await atomicWriteJson(configFallbackPath(), doc)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function init() {
|
|
376
|
+
if (initialized) return
|
|
377
|
+
const dataDir = getDataDir()
|
|
378
|
+
await ensureDefaultScripts(dataDir, { overwrite: false })
|
|
379
|
+
|
|
380
|
+
let loadedDoc = null
|
|
381
|
+
if (storageDomain && typeof storageDomain.open === 'function') {
|
|
382
|
+
domain = await storageDomain.open(hooksConfigDomain)
|
|
383
|
+
const globalDoc = domain.global.get()
|
|
384
|
+
if (globalDoc && globalDoc.revision > 0) {
|
|
385
|
+
loadedDoc = globalDoc
|
|
386
|
+
}
|
|
387
|
+
} else {
|
|
388
|
+
try {
|
|
389
|
+
const raw = await readFile(configFallbackPath(), 'utf8')
|
|
390
|
+
const parsed = storedConfigEnvelopeSchema.safeParse(JSON.parse(raw))
|
|
391
|
+
if (parsed.success) {
|
|
392
|
+
loadedDoc = parsed.data
|
|
393
|
+
}
|
|
394
|
+
} catch {
|
|
395
|
+
// First boot with no config.json
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (loadedDoc) {
|
|
400
|
+
revision = loadedDoc.revision
|
|
401
|
+
config = normalizeConfig(loadedDoc.config)
|
|
402
|
+
} else {
|
|
403
|
+
revision = 0
|
|
404
|
+
config = buildDefaultConfig()
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
secretsByTarget = await loadSecrets()
|
|
408
|
+
const soundInfo = await getCustomSoundInfo(dataDir)
|
|
409
|
+
config.systemNotifications.customSoundFilename = soundInfo?.filename ?? null
|
|
410
|
+
initialized = true
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async function close() {
|
|
414
|
+
await writeTail.catch(() => {})
|
|
415
|
+
if (domain) {
|
|
416
|
+
const target = domain
|
|
417
|
+
domain = null
|
|
418
|
+
await target.close()
|
|
419
|
+
}
|
|
420
|
+
initialized = false
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function buildTargetView(target) {
|
|
424
|
+
const secretKeys = getSecretFieldKeys(target.provider) ?? []
|
|
425
|
+
const storedSecrets = secretsByTarget[target.id] ?? {}
|
|
426
|
+
const secretState = {}
|
|
427
|
+
for (const key of secretKeys) {
|
|
428
|
+
const val = storedSecrets[key]
|
|
429
|
+
secretState[key] = {
|
|
430
|
+
configured: Boolean(typeof val === 'string' && val.length > 0),
|
|
431
|
+
...(typeof val === 'string' && val.length > 0 ? { preview: maskSecretPreview(val) } : {}),
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return {
|
|
435
|
+
...target,
|
|
436
|
+
config: { ...target.config },
|
|
437
|
+
events: { ...target.events },
|
|
438
|
+
secretState,
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function getPublicConfig() {
|
|
443
|
+
return {
|
|
444
|
+
inApp: { ...config.inApp },
|
|
445
|
+
systemNotifications: { ...config.systemNotifications },
|
|
446
|
+
thirdParty: {
|
|
447
|
+
enabled: config.thirdParty.enabled,
|
|
448
|
+
targets: config.thirdParty.targets.map(buildTargetView),
|
|
449
|
+
},
|
|
450
|
+
mountPoints: Object.fromEntries(
|
|
451
|
+
Object.entries(config.mountPoints).map(([id, mp]) => [
|
|
452
|
+
id,
|
|
453
|
+
{
|
|
454
|
+
enabled: mp.enabled,
|
|
455
|
+
bellEnabled: mp.bellEnabled,
|
|
456
|
+
scripts: mp.scripts.map((s) => ({ ...s })),
|
|
457
|
+
},
|
|
458
|
+
]),
|
|
459
|
+
),
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function getSnapshot() {
|
|
464
|
+
return {
|
|
465
|
+
revision,
|
|
466
|
+
config: getPublicConfig(),
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function getResolvedSecrets(targetId) {
|
|
471
|
+
if (typeof targetId === 'string') {
|
|
472
|
+
return { ...(secretsByTarget[targetId] ?? {}) }
|
|
473
|
+
}
|
|
474
|
+
const copy = {}
|
|
475
|
+
for (const [id, fields] of Object.entries(secretsByTarget)) {
|
|
476
|
+
copy[id] = { ...fields }
|
|
477
|
+
}
|
|
478
|
+
return copy
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function enqueueWrite(expectedRevision, mutator) {
|
|
482
|
+
const job = writeTail.then(async () => {
|
|
483
|
+
if (expectedRevision !== undefined && expectedRevision !== revision) {
|
|
484
|
+
throw new ConfigStoreError(
|
|
485
|
+
'revision-conflict',
|
|
486
|
+
'Revision conflict: settings changed. Reload the latest settings before saving.',
|
|
487
|
+
)
|
|
488
|
+
}
|
|
489
|
+
const next = await mutator(structuredClone(config), structuredClone(secretsByTarget))
|
|
490
|
+
const nextConfig = normalizeConfig(next.config)
|
|
491
|
+
let nextSecrets = secretsByTarget
|
|
492
|
+
if (next.secrets !== undefined) {
|
|
493
|
+
nextSecrets = await persistSecrets(next.secrets)
|
|
494
|
+
}
|
|
495
|
+
const nextRevision = revision + 1
|
|
496
|
+
await persistDocument(nextRevision, nextConfig)
|
|
497
|
+
config = nextConfig
|
|
498
|
+
secretsByTarget = nextSecrets
|
|
499
|
+
revision = nextRevision
|
|
500
|
+
return {
|
|
501
|
+
revision,
|
|
502
|
+
config: getPublicConfig(),
|
|
503
|
+
...(next.extra ?? {}),
|
|
504
|
+
}
|
|
505
|
+
})
|
|
506
|
+
writeTail = job.catch(() => {})
|
|
507
|
+
return job
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async function saveSettings(patch = {}) {
|
|
511
|
+
const expectedRevision = patch.expectedRevision
|
|
512
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
513
|
+
if (patch.inApp && typeof patch.inApp === 'object') {
|
|
514
|
+
if (typeof patch.inApp.enabled === 'boolean') draft.inApp.enabled = patch.inApp.enabled
|
|
515
|
+
if (typeof patch.inApp.autoCloseEnabled === 'boolean') {
|
|
516
|
+
draft.inApp.autoCloseEnabled = patch.inApp.autoCloseEnabled
|
|
517
|
+
}
|
|
518
|
+
if (patch.inApp.autoCloseSeconds !== undefined) {
|
|
519
|
+
draft.inApp.autoCloseSeconds = clampAutoCloseSeconds(patch.inApp.autoCloseSeconds)
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (patch.systemNotifications && typeof patch.systemNotifications === 'object') {
|
|
523
|
+
const s = patch.systemNotifications
|
|
524
|
+
if (typeof s.enabled === 'boolean') draft.systemNotifications.enabled = s.enabled
|
|
525
|
+
if (typeof s.suppressWhenFocused === 'boolean') {
|
|
526
|
+
draft.systemNotifications.suppressWhenFocused = s.suppressWhenFocused
|
|
527
|
+
}
|
|
528
|
+
if (typeof s.taskbarAttentionEnabled === 'boolean') {
|
|
529
|
+
draft.systemNotifications.taskbarAttentionEnabled = s.taskbarAttentionEnabled
|
|
530
|
+
}
|
|
531
|
+
if (s.taskbarAttentionMode === 'finite' || s.taskbarAttentionMode === 'untilFocused') {
|
|
532
|
+
draft.systemNotifications.taskbarAttentionMode = s.taskbarAttentionMode
|
|
533
|
+
}
|
|
534
|
+
if (s.taskbarAttentionFlashCount !== undefined) {
|
|
535
|
+
draft.systemNotifications.taskbarAttentionFlashCount = clampFlashCount(s.taskbarAttentionFlashCount)
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (patch.thirdParty && typeof patch.thirdParty === 'object') {
|
|
539
|
+
if (typeof patch.thirdParty.enabled === 'boolean') {
|
|
540
|
+
draft.thirdParty.enabled = patch.thirdParty.enabled
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return { config: draft }
|
|
544
|
+
})
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
async function toggleMountPoint({ mountPointId, enabled, expectedRevision }) {
|
|
548
|
+
if (!getMountPoint(mountPointId)) {
|
|
549
|
+
throw new ConfigStoreError('not-found', `Unknown mount point: ${mountPointId}`)
|
|
550
|
+
}
|
|
551
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
552
|
+
draft.mountPoints[mountPointId].enabled = Boolean(enabled)
|
|
553
|
+
return { config: draft }
|
|
554
|
+
})
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
async function toggleMountPointBell({ mountPointId, bellEnabled, expectedRevision }) {
|
|
558
|
+
if (!getMountPoint(mountPointId)) {
|
|
559
|
+
throw new ConfigStoreError('not-found', `Unknown mount point: ${mountPointId}`)
|
|
560
|
+
}
|
|
561
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
562
|
+
draft.mountPoints[mountPointId].bellEnabled = Boolean(bellEnabled)
|
|
563
|
+
return { config: draft }
|
|
564
|
+
})
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
async function toggleScript({ mountPointId, scriptId, enabled, expectedRevision }) {
|
|
568
|
+
if (!getMountPoint(mountPointId)) {
|
|
569
|
+
throw new ConfigStoreError('not-found', `Unknown mount point: ${mountPointId}`)
|
|
570
|
+
}
|
|
571
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
572
|
+
const target = draft.mountPoints[mountPointId].scripts.find((s) => s.id === scriptId)
|
|
573
|
+
if (!target) {
|
|
574
|
+
throw new ConfigStoreError('not-found', `Unknown script: ${scriptId}`)
|
|
575
|
+
}
|
|
576
|
+
target.enabled = Boolean(enabled)
|
|
577
|
+
return { config: draft }
|
|
578
|
+
})
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
async function updateScriptMeta({ mountPointId, scriptId, name, matcher, timeoutSeconds, enabled, expectedRevision }) {
|
|
582
|
+
const mpDef = getMountPoint(mountPointId)
|
|
583
|
+
if (!mpDef) {
|
|
584
|
+
throw new ConfigStoreError('not-found', `Unknown mount point: ${mountPointId}`)
|
|
585
|
+
}
|
|
586
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
587
|
+
const target = draft.mountPoints[mountPointId].scripts.find((s) => s.id === scriptId)
|
|
588
|
+
if (!target) {
|
|
589
|
+
throw new ConfigStoreError('not-found', `Unknown script: ${scriptId}`)
|
|
590
|
+
}
|
|
591
|
+
if (typeof name === 'string') {
|
|
592
|
+
const clean = name.replace(/[\x00-\x1f\x7f]/g, '').trim()
|
|
593
|
+
if (!clean) throw new ConfigStoreError('invalid-config', 'Script name cannot be empty')
|
|
594
|
+
target.name = clean.slice(0, 120)
|
|
595
|
+
}
|
|
596
|
+
if (matcher !== undefined) {
|
|
597
|
+
if (!mpDef.supportsMatcher && String(matcher).trim() !== '') {
|
|
598
|
+
throw new ConfigStoreError('invalid-config', `Mount point ${mountPointId} does not support matcher`)
|
|
599
|
+
}
|
|
600
|
+
target.matcher = String(matcher).trim().slice(0, 256)
|
|
601
|
+
}
|
|
602
|
+
if (timeoutSeconds !== undefined) {
|
|
603
|
+
target.timeoutSeconds = clampTimeoutSeconds(timeoutSeconds)
|
|
604
|
+
}
|
|
605
|
+
if (typeof enabled === 'boolean') {
|
|
606
|
+
target.enabled = enabled
|
|
607
|
+
}
|
|
608
|
+
return { config: draft, extra: { script: { ...target } } }
|
|
609
|
+
})
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async function addCustomScript({ mountPointId, scriptEntry, expectedRevision }) {
|
|
613
|
+
if (!getMountPoint(mountPointId)) {
|
|
614
|
+
throw new ConfigStoreError('not-found', `Unknown mount point: ${mountPointId}`)
|
|
615
|
+
}
|
|
616
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
617
|
+
draft.mountPoints[mountPointId].scripts.push(scriptEntry)
|
|
618
|
+
return { config: draft, extra: { script: { ...scriptEntry } } }
|
|
619
|
+
})
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
async function deleteScript({ mountPointId, scriptId, expectedRevision }) {
|
|
623
|
+
if (!getMountPoint(mountPointId)) {
|
|
624
|
+
throw new ConfigStoreError('not-found', `Unknown mount point: ${mountPointId}`)
|
|
625
|
+
}
|
|
626
|
+
let deletedFilename = null
|
|
627
|
+
const res = await enqueueWrite(expectedRevision, (draft) => {
|
|
628
|
+
const list = draft.mountPoints[mountPointId].scripts
|
|
629
|
+
const idx = list.findIndex((s) => s.id === scriptId)
|
|
630
|
+
if (idx === -1) {
|
|
631
|
+
throw new ConfigStoreError('not-found', `Unknown script: ${scriptId}`)
|
|
632
|
+
}
|
|
633
|
+
const entry = list[idx]
|
|
634
|
+
if (entry.kind !== 'custom') {
|
|
635
|
+
throw new ConfigStoreError('cannot-delete-default', 'Default scripts cannot be deleted; disable them instead.')
|
|
636
|
+
}
|
|
637
|
+
deletedFilename = entry.filename
|
|
638
|
+
list.splice(idx, 1)
|
|
639
|
+
return { config: draft }
|
|
640
|
+
})
|
|
641
|
+
if (deletedFilename) {
|
|
642
|
+
await deleteCustomScriptFile(getDataDir(), deletedFilename).catch(() => {})
|
|
643
|
+
}
|
|
644
|
+
return res
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
async function resetDefaultScripts({ expectedRevision } = {}) {
|
|
648
|
+
await ensureDefaultScripts(getDataDir(), { overwrite: true })
|
|
649
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
650
|
+
for (const mp of HOOK_MOUNT_POINTS) {
|
|
651
|
+
const existingCustom = (draft.mountPoints[mp.id]?.scripts ?? []).filter((s) => s.kind === 'custom')
|
|
652
|
+
draft.mountPoints[mp.id] = {
|
|
653
|
+
enabled: draft.mountPoints[mp.id]?.enabled ?? Boolean(mp.defaultEnabled),
|
|
654
|
+
bellEnabled: draft.mountPoints[mp.id]?.bellEnabled ?? Boolean(mp.defaultBell),
|
|
655
|
+
scripts: [...buildDefaultScriptsForMountPoint(mp), ...existingCustom],
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return { config: draft }
|
|
659
|
+
})
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async function saveThirdPartyTarget({ target: rawTarget, expectedRevision }) {
|
|
663
|
+
const inputTarget = rawTarget && typeof rawTarget === 'object' ? rawTarget : null
|
|
664
|
+
if (!inputTarget) {
|
|
665
|
+
throw new ConfigStoreError('bad-request', 'Missing target payload')
|
|
666
|
+
}
|
|
667
|
+
const provider = inputTarget.provider
|
|
668
|
+
if (!PROVIDER_IDS.includes(provider)) {
|
|
669
|
+
throw new ConfigStoreError('invalid-config', `Unsupported provider: ${provider}`)
|
|
670
|
+
}
|
|
671
|
+
const name = typeof inputTarget.name === 'string' ? inputTarget.name.trim().slice(0, 64) : ''
|
|
672
|
+
if (!name) {
|
|
673
|
+
throw new ConfigStoreError('invalid-config', 'Target name is required')
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const secretKeys = getSecretFieldKeys(provider) ?? []
|
|
677
|
+
const secretSet = new Set(secretKeys)
|
|
678
|
+
|
|
679
|
+
return enqueueWrite(expectedRevision, (draft, draftSecrets) => {
|
|
680
|
+
const targets = draft.thirdParty.targets
|
|
681
|
+
const existingIdx = inputTarget.id ? targets.findIndex((t) => t.id === inputTarget.id) : -1
|
|
682
|
+
const isNew = existingIdx === -1
|
|
683
|
+
if (isNew && targets.length >= MAX_THIRD_PARTY_TARGETS) {
|
|
684
|
+
throw new ConfigStoreError('target-limit', `Maximum ${MAX_THIRD_PARTY_TARGETS} third-party targets allowed`)
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
const targetId = isNew ? `tp_${randomUUID()}` : targets[existingIdx].id
|
|
688
|
+
const prevSecrets =
|
|
689
|
+
!isNew && targets[existingIdx].provider === provider ? (draftSecrets[targetId] ?? {}) : {}
|
|
690
|
+
|
|
691
|
+
const cleanNonSecretConfig = {
|
|
692
|
+
...buildProviderDefaultConfig(provider),
|
|
693
|
+
}
|
|
694
|
+
const rawCfg = inputTarget.config && typeof inputTarget.config === 'object' ? inputTarget.config : {}
|
|
695
|
+
for (const [k, v] of Object.entries(rawCfg)) {
|
|
696
|
+
if (!secretSet.has(k) && v !== undefined) {
|
|
697
|
+
cleanNonSecretConfig[k] = v
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
const rawSecretsInput = inputTarget.secrets && typeof inputTarget.secrets === 'object' ? inputTarget.secrets : {}
|
|
702
|
+
const nextTargetSecrets = {}
|
|
703
|
+
for (const key of secretKeys) {
|
|
704
|
+
const candidate = rawSecretsInput[key] !== undefined ? rawSecretsInput[key] : rawCfg[key]
|
|
705
|
+
if (typeof candidate === 'string' && candidate.trim() !== '') {
|
|
706
|
+
nextTargetSecrets[key] = candidate.trim()
|
|
707
|
+
} else if (typeof prevSecrets[key] === 'string' && prevSecrets[key].length > 0) {
|
|
708
|
+
nextTargetSecrets[key] = prevSecrets[key]
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
const mergedForValidation = {
|
|
713
|
+
...cleanNonSecretConfig,
|
|
714
|
+
...nextTargetSecrets,
|
|
715
|
+
}
|
|
716
|
+
try {
|
|
717
|
+
const check = validateProviderConfig(provider, mergedForValidation)
|
|
718
|
+
if (check && check.valid === false) {
|
|
719
|
+
throw new ConfigStoreError('invalid-config', check.message || check.error || 'Invalid provider configuration')
|
|
720
|
+
}
|
|
721
|
+
} catch (error) {
|
|
722
|
+
if (error instanceof ConfigStoreError) throw error
|
|
723
|
+
throw new ConfigStoreError('invalid-config', error?.message || 'Invalid provider configuration')
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const savedRecord = {
|
|
727
|
+
id: targetId,
|
|
728
|
+
name,
|
|
729
|
+
provider,
|
|
730
|
+
enabled: typeof inputTarget.enabled === 'boolean' ? inputTarget.enabled : true,
|
|
731
|
+
events: normalizeCategoryEvents(inputTarget.events),
|
|
732
|
+
config: cleanNonSecretConfig,
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
if (isNew) {
|
|
736
|
+
targets.push(savedRecord)
|
|
737
|
+
} else {
|
|
738
|
+
targets[existingIdx] = savedRecord
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
if (Object.keys(nextTargetSecrets).length > 0) {
|
|
742
|
+
draftSecrets[targetId] = nextTargetSecrets
|
|
743
|
+
} else {
|
|
744
|
+
delete draftSecrets[targetId]
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
return {
|
|
748
|
+
config: draft,
|
|
749
|
+
secrets: draftSecrets,
|
|
750
|
+
extra: { targetId },
|
|
751
|
+
}
|
|
752
|
+
})
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
async function toggleThirdPartyTarget({ targetId, enabled, expectedRevision }) {
|
|
756
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
757
|
+
const target = draft.thirdParty.targets.find((t) => t.id === targetId)
|
|
758
|
+
if (!target) {
|
|
759
|
+
throw new ConfigStoreError('not-found', `Unknown third-party target: ${targetId}`)
|
|
760
|
+
}
|
|
761
|
+
target.enabled = Boolean(enabled)
|
|
762
|
+
return { config: draft }
|
|
763
|
+
})
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
async function deleteThirdPartyTarget({ targetId, expectedRevision }) {
|
|
767
|
+
return enqueueWrite(expectedRevision, (draft, draftSecrets) => {
|
|
768
|
+
const idx = draft.thirdParty.targets.findIndex((t) => t.id === targetId)
|
|
769
|
+
if (idx === -1) {
|
|
770
|
+
throw new ConfigStoreError('not-found', `Unknown third-party target: ${targetId}`)
|
|
771
|
+
}
|
|
772
|
+
draft.thirdParty.targets.splice(idx, 1)
|
|
773
|
+
delete draftSecrets[targetId]
|
|
774
|
+
return { config: draft, secrets: draftSecrets }
|
|
775
|
+
})
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async function setCustomSoundFilename({ filename, expectedRevision }) {
|
|
779
|
+
return enqueueWrite(expectedRevision, (draft) => {
|
|
780
|
+
draft.systemNotifications.customSoundFilename = filename ?? null
|
|
781
|
+
return { config: draft }
|
|
782
|
+
})
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
return {
|
|
786
|
+
init,
|
|
787
|
+
close,
|
|
788
|
+
getSnapshot,
|
|
789
|
+
getPublicConfig,
|
|
790
|
+
getResolvedSecrets,
|
|
791
|
+
saveSettings,
|
|
792
|
+
toggleMountPoint,
|
|
793
|
+
toggleMountPointBell,
|
|
794
|
+
toggleScript,
|
|
795
|
+
updateScriptMeta,
|
|
796
|
+
addCustomScript,
|
|
797
|
+
deleteScript,
|
|
798
|
+
resetDefaultScripts,
|
|
799
|
+
saveThirdPartyTarget,
|
|
800
|
+
toggleThirdPartyTarget,
|
|
801
|
+
deleteThirdPartyTarget,
|
|
802
|
+
setCustomSoundFilename,
|
|
803
|
+
}
|
|
804
|
+
}
|