advisers 0.3.1 → 0.4.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.
Files changed (48) hide show
  1. package/README-zh.md +13 -15
  2. package/README.md +32 -22
  3. package/THIRD-PARTY-NOTICES.md +1 -1
  4. package/bin/advisers.js +2769 -183
  5. package/index.js +1 -1
  6. package/lib/brief-archive.js +267 -0
  7. package/lib/client-pack.js +1016 -0
  8. package/lib/consent.js +390 -0
  9. package/lib/credentials.js +195 -0
  10. package/lib/customer-read.js +524 -0
  11. package/lib/error-codes.js +516 -7
  12. package/lib/evidence.js +928 -120
  13. package/lib/kb-extract.js +626 -0
  14. package/lib/kb-facts.js +429 -0
  15. package/lib/kb-pages.js +1084 -0
  16. package/lib/kb.js +1036 -0
  17. package/lib/ledger-read.js +109 -1
  18. package/lib/mail-errors.js +46 -0
  19. package/lib/mail-extract.js +351 -0
  20. package/lib/mail-imap.js +446 -0
  21. package/lib/mail-import.js +176 -0
  22. package/lib/mail-parse.js +223 -0
  23. package/lib/mail-store.js +731 -0
  24. package/lib/mail.js +506 -0
  25. package/lib/mcp-server.js +397 -11
  26. package/lib/notify.js +265 -7
  27. package/lib/policy/decision.js +315 -0
  28. package/lib/policy/egress.js +268 -0
  29. package/lib/policy/errors.js +71 -0
  30. package/lib/policy/index.js +99 -0
  31. package/lib/policy/rules.js +468 -0
  32. package/lib/policy/surfaces.js +141 -0
  33. package/lib/receipt-verify.js +283 -26
  34. package/lib/receivables.js +1653 -0
  35. package/lib/scheduler.js +453 -9
  36. package/lib/shell.js +1406 -0
  37. package/lib/source.js +98 -3
  38. package/lib/sqlite.js +501 -49
  39. package/lib/tos/index.js +2 -2
  40. package/lib/tos/manifest.json +6 -6
  41. package/lib/tos/privacy.zh-CN.md +33 -20
  42. package/lib/tos/safety.zh-CN.md +7 -6
  43. package/lib/tos/summary.zh-CN.md +3 -2
  44. package/lib/tos/terms.zh-CN.md +31 -16
  45. package/lib/tui/labels.js +1 -1
  46. package/lib/tui/render.js +1 -1
  47. package/lib/urgency.js +467 -0
  48. package/package.json +4 -4
package/lib/consent.js ADDED
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Local consent records for data-egress surfaces (0.4 Policy subset).
3
+ *
4
+ * File: $ADVISERS_HOME/consent.json (0600, atomic same-directory temp + fsync +
5
+ * rename, directory 0700). Shape:
6
+ *
7
+ * { version: 1, entries: [ {
8
+ * surface, dataClass, provider, baseUrl, grantedAt, channel,
9
+ * revokedAt? } ] }
10
+ *
11
+ * Granularity: one entry per surface + dataClass + provider (+ baseUrl). A
12
+ * changed provider/baseUrl invalidates the old entry (consentStatus reports
13
+ * provider-changed / base-url-changed and granted:false). Revocation keeps the
14
+ * row with revokedAt (the local audit trail), it never re-grants implicitly.
15
+ *
16
+ * This module stores the PRODUCT consent record. It is not a legal agreement,
17
+ * not proof the user understood the consequences, and not tamper-proof: the
18
+ * same user can edit the file. docs/TOS.md §9.3 / docs/PRIVACY.md §4 must list
19
+ * the surfaces before they ship (lead/legal gate).
20
+ *
21
+ * IO contract: reads/writes only the given home (tests use a temp
22
+ * ADVISERS_HOME); no network; no tokens or message bodies are ever written.
23
+ */
24
+ import { chmodSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
25
+ import { homedir } from 'node:os'
26
+ import { dirname, join } from 'node:path'
27
+
28
+ import { atomicWriteFileSync } from './fs-safe.js'
29
+ import { policyError } from './policy/errors.js'
30
+ import { DATA_CLASSES } from './policy/surfaces.js'
31
+
32
+ /** Format version of consent.json. */
33
+ export const CONSENT_VERSION = 1
34
+ export const CONSENT_FILE = 'consent.json'
35
+ export const CONSENT_FILE_MODE = 0o600
36
+ export const CONSENT_DIR_MODE = 0o700
37
+ /** How the consent was recorded; never inferred. */
38
+ export const CONSENT_CHANNELS = Object.freeze(['tty', 'flag', 'env'])
39
+ const MAX_ENTRIES = 500
40
+ const MAX_TEXT = 200
41
+
42
+ function isPlainObject(value) {
43
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
44
+ }
45
+
46
+ function trimmed(value) {
47
+ return typeof value === 'string' ? value.trim() : ''
48
+ }
49
+
50
+ function isIsoDate(value) {
51
+ if (typeof value !== 'string' || !value) return false
52
+ return !Number.isNaN(Date.parse(value))
53
+ }
54
+
55
+ function textField(value, field, { max = MAX_TEXT } = {}) {
56
+ const text = trimmed(value)
57
+ if (!text) throw policyError('POLICY_INVALID_FACTS', 'consent ' + field + ' is required')
58
+ if (text.length > max) throw policyError('POLICY_INVALID_FACTS', 'consent ' + field + ' is longer than ' + max + ' characters')
59
+ return text
60
+ }
61
+
62
+ function normalizeBaseUrl(value) {
63
+ if (value === undefined || value === null || value === '') return null
64
+ const text = trimmed(value)
65
+ if (!text) return null
66
+ if (text.length > 300) throw policyError('POLICY_INVALID_FACTS', 'consent baseUrl is longer than 300 characters')
67
+ return text
68
+ }
69
+
70
+ /** Default Advisers home (same rule as lib/tos: ADVISERS_HOME or ~/.advisers). */
71
+ export function defaultHome() {
72
+ return process.env.ADVISERS_HOME || join(homedir(), '.advisers')
73
+ }
74
+
75
+ /** Path of consent.json for a home directory. */
76
+ export function consentPath(home = defaultHome()) {
77
+ return join(home, CONSENT_FILE)
78
+ }
79
+
80
+ function normalizeEntry(raw) {
81
+ if (!isPlainObject(raw)) return null
82
+ const surface = trimmed(raw.surface)
83
+ const dataClass = trimmed(raw.dataClass)
84
+ const provider = trimmed(raw.provider)
85
+ if (!surface || surface.length > MAX_TEXT) return null
86
+ if (!DATA_CLASSES.includes(dataClass)) return null
87
+ if (!provider || provider.length > MAX_TEXT) return null
88
+ const baseUrl = raw.baseUrl === undefined || raw.baseUrl === null || raw.baseUrl === '' ? null : trimmed(raw.baseUrl)
89
+ if (baseUrl !== null && (!baseUrl || baseUrl.length > 300)) return null
90
+ const grantedAt = trimmed(raw.grantedAt)
91
+ if (!isIsoDate(grantedAt)) return null
92
+ const channel = trimmed(raw.channel)
93
+ if (!CONSENT_CHANNELS.includes(channel)) return null
94
+ const entry = { surface, dataClass, provider, grantedAt, channel }
95
+ if (baseUrl !== null) entry.baseUrl = baseUrl
96
+ if (raw.revokedAt !== undefined && raw.revokedAt !== null && raw.revokedAt !== '') {
97
+ const revokedAt = trimmed(raw.revokedAt)
98
+ if (!isIsoDate(revokedAt)) return null
99
+ entry.revokedAt = revokedAt
100
+ }
101
+ return entry
102
+ }
103
+
104
+ function compareEntries(left, right) {
105
+ const a = [left.surface, left.dataClass, left.provider, left.baseUrl ?? '', left.grantedAt].join('\u0000')
106
+ const b = [right.surface, right.dataClass, right.provider, right.baseUrl ?? '', right.grantedAt].join('\u0000')
107
+ return a < b ? -1 : a > b ? 1 : 0
108
+ }
109
+
110
+ /**
111
+ * Validate and canonicalise a parsed consent record.
112
+ * A single malformed entry invalidates the WHOLE file (fail closed): a
113
+ * partially trusted consent file is how a forged entry would slip through.
114
+ *
115
+ * @returns {{version: 1, entries: object[]}|null}
116
+ */
117
+ export function validateConsentRecord(record) {
118
+ if (!isPlainObject(record)) return null
119
+ if (record.version !== CONSENT_VERSION) return null
120
+ if (!Array.isArray(record.entries) || record.entries.length > MAX_ENTRIES) return null
121
+ const entries = []
122
+ const seen = new Set()
123
+ for (const raw of record.entries) {
124
+ const entry = normalizeEntry(raw)
125
+ if (!entry) return null
126
+ const key = [entry.surface, entry.dataClass, entry.provider, entry.baseUrl ?? '', entry.grantedAt, entry.revokedAt ?? ''].join('\u0000')
127
+ if (seen.has(key)) continue
128
+ seen.add(key)
129
+ entries.push(entry)
130
+ }
131
+ entries.sort(compareEntries)
132
+ return { version: CONSENT_VERSION, entries }
133
+ }
134
+
135
+ /** Read + validate consent.json; missing/corrupt/unreadable files fail closed (null). */
136
+ export function readConsent(home = defaultHome()) {
137
+ let raw
138
+ try {
139
+ const target = consentPath(home)
140
+ if (!existsSync(target)) return null
141
+ raw = readFileSync(target, 'utf8')
142
+ } catch {
143
+ return null
144
+ }
145
+ try {
146
+ return validateConsentRecord(JSON.parse(raw))
147
+ } catch {
148
+ return null
149
+ }
150
+ }
151
+
152
+ /** Alias used by lib/policy/index.js (loadConsent/saveConsent naming). */
153
+ export const loadConsent = readConsent
154
+
155
+ /**
156
+ * Atomically write consent.json (0600, directory 0700). Invalid records are
157
+ * rejected before anything touches the filesystem.
158
+ */
159
+ export function writeConsent(home = defaultHome(), record) {
160
+ const clean = validateConsentRecord(record)
161
+ if (!clean) throw policyError('POLICY_INVALID_FACTS', 'refusing to write an invalid consent record')
162
+ const target = consentPath(home)
163
+ const dir = dirname(target)
164
+ mkdirSync(dir, { recursive: true, mode: CONSENT_DIR_MODE })
165
+ try { chmodSync(dir, CONSENT_DIR_MODE) } catch {}
166
+ const text = JSON.stringify(clean, null, 2) + '\n'
167
+ atomicWriteFileSync(target, text, { mode: CONSENT_FILE_MODE })
168
+ try { chmodSync(target, CONSENT_FILE_MODE) } catch {}
169
+ return clean
170
+ }
171
+
172
+ /** Alias used by lib/policy/index.js. */
173
+ export const saveConsent = writeConsent
174
+
175
+ function auditOrRefuse(audit, event) {
176
+ if (typeof audit !== 'function') return false
177
+ let result
178
+ try {
179
+ result = audit(event)
180
+ } catch {
181
+ throw policyError('POLICY_AUDIT_UNAVAILABLE', 'the consent audit could not be written; the consent change was refused')
182
+ }
183
+ if (result && typeof result.then === 'function') {
184
+ throw policyError('POLICY_AUDIT_UNAVAILABLE', 'the consent audit callback must be synchronous; the consent change was refused')
185
+ }
186
+ if (isPlainObject(result) && result.ok === false) {
187
+ throw policyError('POLICY_AUDIT_UNAVAILABLE', 'the consent audit reported failure; the consent change was refused')
188
+ }
189
+ return true
190
+ }
191
+
192
+ function entryKey(entry) {
193
+ return [entry.surface, entry.dataClass, entry.provider, entry.baseUrl ?? ''].join('\u0000')
194
+ }
195
+
196
+ function activeEntries(record, { surface, dataClass } = {}) {
197
+ if (!record) return []
198
+ return record.entries.filter((entry) => {
199
+ if (entry.revokedAt) return false
200
+ if (surface && entry.surface !== surface) return false
201
+ if (dataClass && entry.dataClass !== dataClass) return false
202
+ return true
203
+ })
204
+ }
205
+
206
+ /**
207
+ * Record an explicit consent grant (surface + dataClass + provider + baseUrl).
208
+ *
209
+ * The audit callback runs BEFORE the file write: if it throws or reports
210
+ * {ok:false}, the call fails closed and consent.json is left untouched.
211
+ *
212
+ * @param {string} [home]
213
+ * @param {{surface: string, dataClass: string, provider: string, baseUrl?: string,
214
+ * channel?: 'tty'|'flag'|'env', now?: Date|string, audit?: Function}} input
215
+ * @returns {{version: number, entry: object, record: object, auditWritten: boolean}}
216
+ */
217
+ export function grantConsent(home, input = {}) {
218
+ if (isPlainObject(home) && input && Object.keys(input).length === 0) {
219
+ input = home
220
+ home = defaultHome()
221
+ }
222
+ if (!isPlainObject(input)) throw new TypeError('grantConsent requires an input object')
223
+ const surface = textField(input.surface, 'surface')
224
+ const dataClass = trimmed(input.dataClass)
225
+ if (!DATA_CLASSES.includes(dataClass)) throw policyError('POLICY_INVALID_FACTS', 'consent dataClass must be one of ' + DATA_CLASSES.join(', '))
226
+ const provider = textField(input.provider, 'provider')
227
+ const baseUrl = normalizeBaseUrl(input.baseUrl)
228
+ const channel = trimmed(input.channel) || 'flag'
229
+ if (!CONSENT_CHANNELS.includes(channel)) throw policyError('POLICY_INVALID_FACTS', 'consent channel must be one of ' + CONSENT_CHANNELS.join(', '))
230
+ const grantedAt = (() => {
231
+ if (input.now === undefined || input.now === null) return new Date().toISOString()
232
+ if (input.now instanceof Date) return input.now.toISOString()
233
+ const text = String(input.now)
234
+ if (Number.isNaN(Date.parse(text))) throw policyError('POLICY_INVALID_FACTS', 'consent now must be an ISO timestamp or Date')
235
+ return new Date(text).toISOString()
236
+ })()
237
+ const entry = { surface, dataClass, provider, grantedAt, channel }
238
+ if (baseUrl !== null) entry.baseUrl = baseUrl
239
+ const event = { action: 'consent.grant', surface, dataClass, provider, baseUrl, channel, at: grantedAt, ok: true }
240
+ const auditWritten = auditOrRefuse(input.audit, event)
241
+ const current = readConsent(home) ?? { version: CONSENT_VERSION, entries: [] }
242
+ const key = entryKey(entry)
243
+ const entries = current.entries.filter((item) => entryKey(item) !== key)
244
+ entries.push(entry)
245
+ const record = writeConsent(home, { version: CONSENT_VERSION, entries })
246
+ return { version: record.version, entry, record, auditWritten }
247
+ }
248
+
249
+ /**
250
+ * Revoke consent. Matching is surface + optional dataClass/provider/baseUrl.
251
+ * Revocation keeps rows (revokedAt) as the local audit trail.
252
+ *
253
+ * @returns {{revoked: number, entries: object[], record: object|null, auditWritten: boolean}}
254
+ */
255
+ export function revokeConsent(home, input = {}) {
256
+ if (isPlainObject(home) && input && Object.keys(input).length === 0) {
257
+ input = home
258
+ home = defaultHome()
259
+ }
260
+ if (!isPlainObject(input)) throw new TypeError('revokeConsent requires an input object')
261
+ const surface = textField(input.surface, 'surface')
262
+ const dataClass = trimmed(input.dataClass)
263
+ if (dataClass && !DATA_CLASSES.includes(dataClass)) throw policyError('POLICY_INVALID_FACTS', 'consent dataClass must be one of ' + DATA_CLASSES.join(', '))
264
+ const provider = trimmed(input.provider)
265
+ const baseUrl = normalizeBaseUrl(input.baseUrl)
266
+ const revokedAt = (() => {
267
+ if (input.now === undefined || input.now === null) return new Date().toISOString()
268
+ if (input.now instanceof Date) return input.now.toISOString()
269
+ const text = String(input.now)
270
+ if (Number.isNaN(Date.parse(text))) throw policyError('POLICY_INVALID_FACTS', 'consent now must be an ISO timestamp or Date')
271
+ return new Date(text).toISOString()
272
+ })()
273
+ const current = readConsent(home)
274
+ if (!current) return { revoked: 0, entries: [], record: null, auditWritten: false }
275
+ const matches = current.entries.filter((entry) => {
276
+ if (entry.revokedAt) return false
277
+ if (entry.surface !== surface) return false
278
+ if (dataClass && entry.dataClass !== dataClass) return false
279
+ if (provider && entry.provider !== provider) return false
280
+ if (baseUrl !== null && (entry.baseUrl ?? null) !== baseUrl) return false
281
+ return true
282
+ })
283
+ if (!matches.length) return { revoked: 0, entries: [], record: current, auditWritten: false }
284
+ const event = { action: 'consent.revoke', surface, dataClass: dataClass || null, provider: provider || null, baseUrl, at: revokedAt, ok: true, revoked: matches.length }
285
+ const auditWritten = auditOrRefuse(input.audit, event)
286
+ const revokedKeys = new Set(matches.map((entry) => entry.grantedAt + '\u0000' + entryKey(entry)))
287
+ const entries = current.entries.map((entry) => {
288
+ const key = entry.grantedAt + '\u0000' + entryKey(entry)
289
+ return revokedKeys.has(key) ? { ...entry, revokedAt } : entry
290
+ })
291
+ const record = writeConsent(home, { version: CONSENT_VERSION, entries })
292
+ const revoked = record.entries.filter((entry) => entry.revokedAt === revokedAt && matches.some((item) => item.surface === entry.surface && item.dataClass === entry.dataClass && item.provider === entry.provider && (item.baseUrl ?? null) === (entry.baseUrl ?? null)))
293
+ return { revoked: revoked.length, entries: revoked, record, auditWritten }
294
+ }
295
+
296
+ /**
297
+ * Consent status for one query. Fail closed: a missing/corrupt file is
298
+ * 'missing'; a mismatch names the changed dimension so the caller can ask for
299
+ * a fresh grant instead of silently reusing consent for a different provider.
300
+ *
301
+ * @param {string} [home]
302
+ * @param {{surface: string, dataClass: string, provider?: string, baseUrl?: string}} query
303
+ * @returns {{granted: boolean, reason: string, entry: object|null, configured: boolean}}
304
+ */
305
+ export function consentStatus(home, query = {}) {
306
+ if (isPlainObject(home) && query && Object.keys(query).length === 0) {
307
+ query = home
308
+ home = defaultHome()
309
+ }
310
+ if (!isPlainObject(query)) throw new TypeError('consentStatus requires a query object')
311
+ const surface = trimmed(query.surface)
312
+ const dataClass = trimmed(query.dataClass)
313
+ const provider = trimmed(query.provider)
314
+ const baseUrl = normalizeBaseUrl(query.baseUrl)
315
+ if (!surface || !dataClass) return { granted: false, reason: 'invalid-query', entry: null, configured: false }
316
+ const record = readConsent(home)
317
+ if (!record) return { granted: false, reason: 'missing', entry: null, configured: false }
318
+ const sameClass = record.entries.filter((entry) => entry.surface === surface && entry.dataClass === dataClass)
319
+ const active = sameClass.filter((entry) => !entry.revokedAt)
320
+ if (!sameClass.length) return { granted: false, reason: 'missing', entry: null, configured: true }
321
+ if (!active.length) return { granted: false, reason: 'revoked', entry: sameClass[sameClass.length - 1], configured: true }
322
+ if (provider) {
323
+ const matchingProvider = sameClass.filter((entry) => entry.provider === provider)
324
+ if (!matchingProvider.length) {
325
+ return { granted: false, reason: 'provider-changed', entry: sameClass[sameClass.length - 1], configured: true }
326
+ }
327
+ const activeProvider = matchingProvider.filter((entry) => !entry.revokedAt)
328
+ if (!activeProvider.length) {
329
+ return { granted: false, reason: 'revoked', entry: matchingProvider[matchingProvider.length - 1], configured: true }
330
+ }
331
+ if (baseUrl !== null) {
332
+ const sameBase = activeProvider.filter((entry) => (entry.baseUrl ?? null) === baseUrl)
333
+ if (!sameBase.length) {
334
+ const revokedBase = matchingProvider.some((entry) => entry.revokedAt && (entry.baseUrl ?? null) === baseUrl)
335
+ return {
336
+ granted: false,
337
+ reason: revokedBase ? 'revoked' : 'base-url-changed',
338
+ entry: activeProvider[activeProvider.length - 1],
339
+ configured: true,
340
+ }
341
+ }
342
+ return { granted: true, reason: 'granted', entry: sameBase[sameBase.length - 1], configured: true }
343
+ }
344
+ return { granted: true, reason: 'granted', entry: activeProvider[activeProvider.length - 1], configured: true }
345
+ }
346
+ return { granted: true, reason: 'granted', entry: active[active.length - 1], configured: true }
347
+ }
348
+
349
+ /**
350
+ * Consent fact for evaluate(facts): granted is only true when the stored entry
351
+ * matches the surface + dataClass (+ provider/baseUrl when the caller knows
352
+ * them). The provider recorded in the entry is always carried, because a
353
+ * consent without a named provider cannot satisfy R-P04-05.
354
+ *
355
+ * @returns {{surface: string, dataClass: string, provider: string, baseUrl: string|null,
356
+ * granted: boolean, reason: string}}
357
+ */
358
+ export function consentFacts(home, query = {}) {
359
+ if (isPlainObject(home) && query && Object.keys(query).length === 0) {
360
+ query = home
361
+ home = defaultHome()
362
+ }
363
+ if (!isPlainObject(query)) throw new TypeError('consentFacts requires a query object')
364
+ const status = consentStatus(home, query)
365
+ const entry = status.entry ?? null
366
+ return {
367
+ surface: trimmed(query.surface) || (entry ? entry.surface : ''),
368
+ dataClass: trimmed(query.dataClass) || (entry ? entry.dataClass : ''),
369
+ provider: trimmed(query.provider) || (entry ? entry.provider : ''),
370
+ baseUrl: normalizeBaseUrl(query.baseUrl) ?? (entry ? entry.baseUrl ?? null : null),
371
+ granted: status.granted === true,
372
+ reason: status.reason,
373
+ }
374
+ }
375
+
376
+ /** JSON-ready list of every stored entry with its active/revoked state. */
377
+ export function listConsents(home = defaultHome()) {
378
+ const record = readConsent(home)
379
+ if (!record) return []
380
+ return record.entries.map((entry) => ({
381
+ surface: entry.surface,
382
+ dataClass: entry.dataClass,
383
+ provider: entry.provider,
384
+ baseUrl: entry.baseUrl ?? null,
385
+ grantedAt: entry.grantedAt,
386
+ channel: entry.channel,
387
+ revokedAt: entry.revokedAt ?? null,
388
+ active: !entry.revokedAt,
389
+ }))
390
+ }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * IMAP credential storage for the 0.4.0 mail entry (lib/mail.js).
3
+ *
4
+ * Design (41-mail-entry.md §3.2, 总纲 §3):
5
+ * - The password never enters SQLite, export/backup payloads, JSON output,
6
+ * argv, or logs. It lives in one JSON file per account:
7
+ * <ADVISERS_HOME>/credentials/imap/<account-id>.json
8
+ * - Directory is created 0700, the file is written 0600 through the durable
9
+ * atomic writer (same-directory temp + fsync + rename), so a crash cannot
10
+ * leave a truncated credential file.
11
+ * - A file whose POSIX mode grants group/other access is REFUSED on read
12
+ * (E_CREDENTIALS_INSECURE) instead of being silently trusted. Windows has no
13
+ * meaningful POSIX mode; there the user-profile ACL is the boundary and the
14
+ * check is skipped (documented in PRIVACY; this module never claims 0600
15
+ * protects the file on Windows).
16
+ * - Reading a credential returns the secret; callers must only hand it to the
17
+ * IMAP login. No function in this module logs or stringifies the secret.
18
+ *
19
+ * The account id is restricted to a safe file-name alphabet so a crafted id
20
+ * (e.g. '../x') can never escape the credentials directory.
21
+ */
22
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'
23
+ import { homedir } from 'node:os'
24
+ import { join } from 'node:path'
25
+ import { atomicWriteFileSync, rmWithRetrySync } from './fs-safe.js'
26
+ import { mailError, MAIL_ERROR_CODES } from './mail-errors.js'
27
+
28
+ export const IMAP_CREDENTIAL_FORMAT = 1
29
+ export const CREDENTIALS_DIR_NAME = 'credentials'
30
+ export const IMAP_DIR_NAME = 'imap'
31
+ export const MAX_ACCOUNT_ID_CHARS = 64
32
+ export const MAX_USER_CHARS = 320
33
+ export const MAX_PASS_CHARS = 4096
34
+
35
+ const ACCOUNT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
36
+ const WINDOWS = process.platform === 'win32'
37
+ const INSECURE_HINT = 'fix the permissions (chmod 700 <home>/credentials/imap and chmod 600 the .json file) and retry; advisers refuses to read a credential other local users can read'
38
+
39
+ /**
40
+ * Resolve the Advisers home: explicit argument, ADVISERS_HOME, then ~/.advisers.
41
+ * A provided-but-invalid home (number, empty string) is a hard error: silently
42
+ * falling back to the real profile would write credentials to the wrong place.
43
+ */
44
+ export function advisersHome(home) {
45
+ if (home !== undefined && home !== null) {
46
+ if (typeof home !== 'string' || !home.trim()) {
47
+ throw mailError(MAIL_ERROR_CODES.CONFIG, 'ADVISERS_HOME must be a non-empty path string', 'pass the explicit home directory or set ADVISERS_HOME')
48
+ }
49
+ return home.trim()
50
+ }
51
+ const fromEnv = typeof process.env.ADVISERS_HOME === 'string' ? process.env.ADVISERS_HOME.trim() : ''
52
+ if (fromEnv) return fromEnv
53
+ return join(homedir(), '.advisers')
54
+ }
55
+
56
+ /** Reject ids that could escape the credentials directory or shadow a path. */
57
+ export function assertCredentialAccountId(accountId) {
58
+ if (typeof accountId !== 'string' || !ACCOUNT_ID_RE.test(accountId) || accountId.includes('..')) {
59
+ throw mailError(MAIL_ERROR_CODES.CONFIG, 'invalid mail account id for credential storage', 'account ids must match ' + ACCOUNT_ID_RE.source)
60
+ }
61
+ return accountId
62
+ }
63
+
64
+ /** <home>/credentials/imap (identity of the directory, not a promise it exists). */
65
+ export function imapCredentialsDir(home) {
66
+ return join(advisersHome(home), CREDENTIALS_DIR_NAME, IMAP_DIR_NAME)
67
+ }
68
+
69
+ /** <home>/credentials/imap/<account-id>.json */
70
+ export function imapCredentialPath(accountId, { home } = {}) {
71
+ const id = assertCredentialAccountId(accountId)
72
+ return join(imapCredentialsDir(home), id + '.json')
73
+ }
74
+
75
+ function ensureCredentialsDir(home) {
76
+ const dir = imapCredentialsDir(home)
77
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
78
+ if (!WINDOWS) {
79
+ try { chmodSync(dir, 0o700) } catch {}
80
+ }
81
+ return dir
82
+ }
83
+
84
+ function normalizeSecret(value, field, max) {
85
+ if (typeof value !== 'string') throw mailError(MAIL_ERROR_CODES.CONFIG, 'IMAP ' + field + ' must be a string')
86
+ const text = value.replace(/[\u0000\r\n]/g, '')
87
+ if (!text.trim()) throw mailError(MAIL_ERROR_CODES.CONFIG, 'IMAP ' + field + ' is required')
88
+ if (text.length > max) throw mailError(MAIL_ERROR_CODES.CONFIG, 'IMAP ' + field + ' is longer than ' + max + ' characters')
89
+ return text
90
+ }
91
+
92
+ function assertFileMode(file) {
93
+ if (WINDOWS) return
94
+ const stat = statSync(file)
95
+ if ((stat.mode & 0o077) !== 0) {
96
+ throw mailError(MAIL_ERROR_CODES.CREDENTIALS_INSECURE, 'the IMAP credential file grants access to group/other users', INSECURE_HINT)
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Save (or replace) one IMAP credential atomically.
102
+ *
103
+ * @param {string} accountId stable mail account id (see lib/mail-store.js)
104
+ * @param {{ user: string, pass: string }} credential
105
+ * @param {{ home?: string, now?: Date }} [options]
106
+ * @returns {{ accountId: string, path: string, user: string, updatedAt: string }}
107
+ * metadata only — never the password.
108
+ */
109
+ export function saveImapCredential(accountId, credential = {}, { home, now } = {}) {
110
+ const id = assertCredentialAccountId(accountId)
111
+ const user = normalizeSecret(credential.user, 'user', MAX_USER_CHARS)
112
+ const pass = normalizeSecret(credential.pass, 'password', MAX_PASS_CHARS)
113
+ if (/[\u0000-\u001f\u007f]/.test(user)) throw mailError(MAIL_ERROR_CODES.CONFIG, 'IMAP user contains control characters')
114
+ const at = (now instanceof Date ? now : new Date(now ?? Date.now())).toISOString()
115
+ const file = imapCredentialPath(id, { home })
116
+ ensureCredentialsDir(home)
117
+ const previous = readRawCredentialFile(file)
118
+ const record = {
119
+ format: IMAP_CREDENTIAL_FORMAT,
120
+ accountId: id,
121
+ user,
122
+ pass,
123
+ createdAt: previous?.createdAt ?? at,
124
+ updatedAt: at,
125
+ }
126
+ atomicWriteFileSync(file, JSON.stringify(record) + '\n', { mode: 0o600 })
127
+ if (!WINDOWS) {
128
+ try { chmodSync(file, 0o600) } catch {}
129
+ assertFileMode(file)
130
+ }
131
+ return { accountId: id, path: file, user, updatedAt: at }
132
+ }
133
+
134
+ function readRawCredentialFile(file) {
135
+ let stat
136
+ try { stat = lstatSync(file) } catch { return undefined }
137
+ if (stat.isSymbolicLink()) {
138
+ throw mailError(MAIL_ERROR_CODES.CREDENTIALS_INSECURE, 'the IMAP credential file is a symbolic link; refusing to follow it', 'replace it with a regular 0600 file')
139
+ }
140
+ assertFileMode(file)
141
+ let record
142
+ try { record = JSON.parse(readFileSync(file, 'utf8')) } catch {
143
+ throw mailError(MAIL_ERROR_CODES.CREDENTIALS_INSECURE, 'the IMAP credential file is not valid JSON', 'delete it and run `advisers mail account add` again')
144
+ }
145
+ return record && typeof record === 'object' ? record : undefined
146
+ }
147
+
148
+ /**
149
+ * Read one IMAP credential. Returns undefined when no file exists (callers map
150
+ * that to E_MAIL_CREDENTIALS_MISSING with an actionable hint). Throws
151
+ * E_CREDENTIALS_INSECURE for a symlink, loose permissions or corrupt JSON.
152
+ *
153
+ * @returns {{ accountId: string, user: string, pass: string, updatedAt?: string } | undefined}
154
+ */
155
+ export function readImapCredential(accountId, { home } = {}) {
156
+ const id = assertCredentialAccountId(accountId)
157
+ const file = imapCredentialPath(id, { home })
158
+ if (!existsSync(file)) return undefined
159
+ const record = readRawCredentialFile(file)
160
+ if (!record || record.format !== IMAP_CREDENTIAL_FORMAT || record.accountId !== id) {
161
+ throw mailError(MAIL_ERROR_CODES.CREDENTIALS_INSECURE, 'the IMAP credential file has an unsupported format', 'delete it and run `advisers mail account add` again')
162
+ }
163
+ if (typeof record.user !== 'string' || !record.user || typeof record.pass !== 'string' || !record.pass) {
164
+ throw mailError(MAIL_ERROR_CODES.CREDENTIALS_INSECURE, 'the IMAP credential file is incomplete', 'delete it and run `advisers mail account add` again')
165
+ }
166
+ return { accountId: id, user: record.user, pass: record.pass, updatedAt: record.updatedAt }
167
+ }
168
+
169
+ /** True when a credential file exists (no secret is read). */
170
+ export function hasImapCredential(accountId, { home } = {}) {
171
+ try { return existsSync(imapCredentialPath(accountId, { home })) } catch { return false }
172
+ }
173
+
174
+ /** Remove one credential file. Returns true when a file was removed. */
175
+ export function removeImapCredential(accountId, { home } = {}) {
176
+ const file = imapCredentialPath(accountId, { home })
177
+ if (!existsSync(file)) return false
178
+ rmWithRetrySync(file, { force: true })
179
+ return true
180
+ }
181
+
182
+ /** Account ids that currently have a stored credential (sorted). */
183
+ export function listImapCredentialAccountIds({ home } = {}) {
184
+ const dir = imapCredentialsDir(home)
185
+ let entries
186
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return [] }
187
+ const ids = []
188
+ for (const entry of entries) {
189
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue
190
+ const id = entry.name.slice(0, -'.json'.length)
191
+ if (!ACCOUNT_ID_RE.test(id) || id.includes('..')) continue
192
+ ids.push(id)
193
+ }
194
+ return ids.sort()
195
+ }