advisers 0.2.0-preview.71 → 0.2.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 +130 -201
- package/NOTICE +29 -4
- package/README-zh.md +35 -8
- package/README.md +37 -8
- package/THIRD-PARTY-NOTICES.md +277 -0
- package/bin/advisers.js +2264 -350
- package/index.js +1 -1
- package/lib/attachments.js +158 -29
- package/lib/capture.js +82 -2
- package/lib/evidence.js +1180 -26
- package/lib/ical.js +542 -0
- package/lib/imap.js +82 -24
- package/lib/mcp-server.js +869 -0
- package/lib/model.js +151 -2
- package/lib/notify.js +156 -4
- package/lib/ocr.js +26 -1
- package/lib/pdf.js +52 -6
- package/lib/pet-brief.js +78 -15
- package/lib/receipt-verify.js +644 -0
- package/lib/remind.js +261 -11
- package/lib/research.js +148 -18
- package/lib/safety/classifier.js +444 -0
- package/lib/safety/explain.js +157 -0
- package/lib/safety/index.js +333 -0
- package/lib/safety/redact.js +212 -0
- package/lib/safety/rules.js +824 -0
- package/lib/scheduler.js +399 -0
- package/lib/source.js +294 -0
- package/lib/sqlite.js +702 -42
- package/lib/sync.js +141 -20
- package/lib/timestamp.js +26 -1
- package/lib/tos/index.js +332 -0
- package/lib/tos/manifest.json +32 -0
- package/lib/tos/privacy.zh-CN.md +136 -0
- package/lib/tos/safety.zh-CN.md +101 -0
- package/lib/tos/summary.zh-CN.md +12 -0
- package/lib/tos/terms.zh-CN.md +439 -0
- package/package.json +10 -8
package/lib/sync.js
CHANGED
|
@@ -9,11 +9,74 @@
|
|
|
9
9
|
* Not provided: continuous merge, multi-writer conflict resolution, cloud accounts.
|
|
10
10
|
* Pull always backs up the local DB before replacing it.
|
|
11
11
|
*/
|
|
12
|
-
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { chmodSync, closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
13
13
|
import { createHash } from 'node:crypto'
|
|
14
|
-
import { basename, join } from 'node:path'
|
|
14
|
+
import { basename, dirname, join } from 'node:path'
|
|
15
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
15
16
|
import { decryptJson, encryptJson, isVaultEnvelope } from './vault.js'
|
|
16
17
|
|
|
18
|
+
/** fsync a directory entry so a rename survives a crash. */
|
|
19
|
+
function fsyncDir(dir) {
|
|
20
|
+
try {
|
|
21
|
+
const fd = openSync(dir, 'r')
|
|
22
|
+
try { fsyncSync(fd) } finally { closeSync(fd) }
|
|
23
|
+
} catch {}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Write a same-directory temp file, flush it, then rename it into place. */
|
|
27
|
+
function writeAtomic(file, data, { mode = 0o600 } = {}) {
|
|
28
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 })
|
|
29
|
+
const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
30
|
+
try {
|
|
31
|
+
writeFileSync(tmp, data, { mode, flush: true })
|
|
32
|
+
renameSync(tmp, file)
|
|
33
|
+
} catch (error) {
|
|
34
|
+
try { if (existsSync(tmp)) rmSync(tmp) } catch {}
|
|
35
|
+
throw error
|
|
36
|
+
}
|
|
37
|
+
try { chmodSync(file, mode) } catch {}
|
|
38
|
+
fsyncDir(join(file, '..'))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const PULL_TMP_PREFIX = '.advisers-pull-verify-'
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Verify that a database file is a structurally valid SQLite database before it
|
|
45
|
+
* is allowed to replace the main database (robustness audit P1-4, 2026-11-17).
|
|
46
|
+
*
|
|
47
|
+
* The snapshot SHA-256 only proves the envelope payload is self-consistent; a
|
|
48
|
+
* byte-corrupted payload is still "consistent" after re-encryption and used to
|
|
49
|
+
* be installed as the live library. PRAGMA quick_check is O(file) and catches
|
|
50
|
+
* corrupt b-trees/pages. The original file is only opened read-only.
|
|
51
|
+
*/
|
|
52
|
+
function assertDatabaseIntegrity(file) {
|
|
53
|
+
let db
|
|
54
|
+
try {
|
|
55
|
+
// A 0-byte file is a valid "empty database" to SQLite (quick_check says ok),
|
|
56
|
+
// so a truncated snapshot used to replace the live library silently. Treat it
|
|
57
|
+
// as corrupt (robustness audit P2-2 / P1-4) and keep the local database.
|
|
58
|
+
if (statSync(file).size === 0) throw new Error('E_DB_CORRUPT: the snapshot database is 0 bytes (truncated)')
|
|
59
|
+
db = new DatabaseSync(file, { readOnly: true })
|
|
60
|
+
const row = db.prepare('PRAGMA quick_check').get()
|
|
61
|
+
const verdict = String(row?.quick_check ?? 'unknown').slice(0, 120)
|
|
62
|
+
if (verdict !== 'ok') throw new Error(`quick_check reported ${verdict}`)
|
|
63
|
+
} catch (error) {
|
|
64
|
+
throw new Error(`snapshot database failed the integrity check: ${String(error?.message ?? error).slice(0, 200)}`)
|
|
65
|
+
} finally {
|
|
66
|
+
try { db?.close() } catch {}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Put the pre-pull database (and its WAL/SHM siblings) back after a failed replace. */
|
|
71
|
+
function restoreBackup(backup, dbPath) {
|
|
72
|
+
copyFileSync(backup, dbPath)
|
|
73
|
+
for (const suffix of ['-wal', '-shm']) {
|
|
74
|
+
if (existsSync(backup + suffix)) copyFileSync(backup + suffix, dbPath + suffix)
|
|
75
|
+
else { try { rmSync(dbPath + suffix) } catch {} }
|
|
76
|
+
}
|
|
77
|
+
try { chmodSync(dbPath, 0o600) } catch {}
|
|
78
|
+
}
|
|
79
|
+
|
|
17
80
|
export const SYNC_PREFIX = 'advisers-'
|
|
18
81
|
export const SYNC_SUFFIX = '.enc.json'
|
|
19
82
|
|
|
@@ -46,14 +109,29 @@ export function pushSnapshot({ dir, dbPath, passphrase, device = 'device', creat
|
|
|
46
109
|
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
47
110
|
const snap = createSnapshot({ dbPath, passphrase, device, createdAt })
|
|
48
111
|
const out = join(dir, snap.name)
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
try { chmodSync(out, 0o600) } catch {}
|
|
53
|
-
return { file: out, sha256: snap.payload.sha256, bytes: Buffer.byteLength(JSON.stringify(snap.envelope)) }
|
|
112
|
+
const body = JSON.stringify(snap.envelope) + '\n'
|
|
113
|
+
writeAtomic(out, body, { mode: 0o600 })
|
|
114
|
+
return { file: out, sha256: snap.payload.sha256, bytes: Buffer.byteLength(body) }
|
|
54
115
|
}
|
|
55
116
|
|
|
56
|
-
|
|
117
|
+
function latestDbMtime(dbPath) {
|
|
118
|
+
let latest = 0
|
|
119
|
+
for (const suffix of ['', '-wal']) {
|
|
120
|
+
try { latest = Math.max(latest, statSync(dbPath + suffix).mtimeMs) } catch {}
|
|
121
|
+
}
|
|
122
|
+
return latest
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Replace the local database with the chosen snapshot.
|
|
127
|
+
*
|
|
128
|
+
* Safety (robustness audit P1-4): when the local database was written after
|
|
129
|
+
* the snapshot was taken on *another* device, overwriting it would silently
|
|
130
|
+
* drop those writes. Refuse unless force:true. A snapshot pushed from this
|
|
131
|
+
* HOME (device marker matches payload.device) is treated as an intentional
|
|
132
|
+
* restore, and no local database at all is always allowed.
|
|
133
|
+
*/
|
|
134
|
+
export function pullSnapshot({ dir, dbPath, passphrase, file, force = false, localMtimeMs, localDevice }) {
|
|
57
135
|
const snapshots = listSnapshots(dir)
|
|
58
136
|
if (!snapshots.length) throw new Error(`no Advisers snapshots in ${dir}`)
|
|
59
137
|
const chosen = file ? snapshots.find((s) => s.name === basename(file)) : snapshots[0]
|
|
@@ -65,20 +143,63 @@ export function pullSnapshot({ dir, dbPath, passphrase, file, force = false }) {
|
|
|
65
143
|
const bytes = Buffer.from(payload.db, 'base64')
|
|
66
144
|
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
67
145
|
if (sha256 !== payload.sha256) throw new Error('snapshot checksum mismatch')
|
|
68
|
-
if (existsSync(dbPath) && !force
|
|
69
|
-
return { file: chosen.name, sha256, changed: false, backup: null }
|
|
146
|
+
if (existsSync(dbPath) && !force) {
|
|
147
|
+
if (readFileSync(dbPath).equals(bytes)) return { file: chosen.name, sha256, changed: false, backup: null }
|
|
148
|
+
const snapshotAt = Date.parse(payload.createdAt ?? '')
|
|
149
|
+
const localAt = Number.isFinite(localMtimeMs) && localMtimeMs > 0 ? localMtimeMs : latestDbMtime(dbPath)
|
|
150
|
+
const sameDevice = Boolean(localDevice) && Boolean(payload.device) && sanitizeDevice(payload.device) === sanitizeDevice(localDevice)
|
|
151
|
+
if (!sameDevice) {
|
|
152
|
+
if (!Number.isFinite(snapshotAt)) throw new Error(`cannot tell whether the local database is newer than ${chosen.name} (snapshot has no valid createdAt); re-run with --force to overwrite and keep a backup`)
|
|
153
|
+
if (localAt > snapshotAt) throw new Error(`local database was written after snapshot ${chosen.name} (local ${new Date(localAt).toISOString()} > snapshot ${new Date(snapshotAt).toISOString()}); refusing to overwrite. If those local writes matter, back them up/export them first; re-run with --force to overwrite anyway (a backup is kept).`)
|
|
154
|
+
}
|
|
70
155
|
}
|
|
156
|
+
const parent = dirname(dbPath)
|
|
157
|
+
mkdirSync(parent, { recursive: true, mode: 0o700 })
|
|
158
|
+
// Stage the snapshot bytes next to the live database and verify them BEFORE
|
|
159
|
+
// anything replaces the library (robustness audit P1-4). The backup copy is
|
|
160
|
+
// taken first and kept on every failure path; the live WAL/SHM are only
|
|
161
|
+
// removed once the staged database has passed the integrity check.
|
|
162
|
+
const tmp = join(parent, `${PULL_TMP_PREFIX}${process.pid}-${Math.random().toString(36).slice(2, 8)}`)
|
|
71
163
|
let backup = null
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
164
|
+
try {
|
|
165
|
+
writeFileSync(tmp, bytes, { mode: 0o600, flush: true })
|
|
166
|
+
const hadLocal = existsSync(dbPath)
|
|
167
|
+
if (hadLocal) {
|
|
168
|
+
backup = `${dbPath}.before-sync-${Date.now()}`
|
|
169
|
+
copyFileSync(dbPath, backup)
|
|
170
|
+
for (const suffix of ['-wal', '-shm']) {
|
|
171
|
+
try { if (existsSync(dbPath + suffix)) copyFileSync(dbPath + suffix, backup + suffix) } catch {}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
assertDatabaseIntegrity(tmp)
|
|
176
|
+
} catch (error) {
|
|
177
|
+
throw new Error(`refusing to replace the local database: ${error.message}`)
|
|
178
|
+
}
|
|
75
179
|
for (const suffix of ['-wal', '-shm']) { try { rmSync(dbPath + suffix) } catch {} }
|
|
76
|
-
|
|
77
|
-
|
|
180
|
+
try {
|
|
181
|
+
// Rename the verified bytes into place (same directory: atomic).
|
|
182
|
+
renameSync(tmp, dbPath)
|
|
183
|
+
try { chmodSync(dbPath, 0o600) } catch {}
|
|
184
|
+
fsyncDir(parent)
|
|
185
|
+
} catch (error) {
|
|
186
|
+
// A failure after the rename must never leave a half-installed library:
|
|
187
|
+
// restore the pre-pull database and keep the backup for inspection.
|
|
188
|
+
let restored = false
|
|
189
|
+
try {
|
|
190
|
+
if (hadLocal && backup) {
|
|
191
|
+
restoreBackup(backup, dbPath)
|
|
192
|
+
restored = true
|
|
193
|
+
} else {
|
|
194
|
+
rmSync(dbPath, { force: true })
|
|
195
|
+
restored = true
|
|
196
|
+
}
|
|
197
|
+
} catch {}
|
|
198
|
+
const hint = restored ? 'the previous local database was restored' : 'restore the backup manually from ' + String(backup)
|
|
199
|
+
throw new Error(`failed to install the verified snapshot; ${hint}: ${error.message}`)
|
|
200
|
+
}
|
|
201
|
+
return { file: chosen.name, sha256, changed: true, backup, device: payload.device, createdAt: payload.createdAt }
|
|
202
|
+
} finally {
|
|
203
|
+
try { if (existsSync(tmp)) rmSync(tmp) } catch {}
|
|
78
204
|
}
|
|
79
|
-
const tmp = `${dbPath}.sync-tmp-${process.pid}`
|
|
80
|
-
writeFileSync(tmp, bytes, { mode: 0o600 })
|
|
81
|
-
renameSync(tmp, dbPath)
|
|
82
|
-
try { chmodSync(dbPath, 0o600) } catch {}
|
|
83
|
-
return { file: chosen.name, sha256, changed: true, backup, device: payload.device, createdAt: payload.createdAt }
|
|
84
205
|
}
|
package/lib/timestamp.js
CHANGED
|
@@ -10,6 +10,31 @@ import { spawn } from 'node:child_process'
|
|
|
10
10
|
import { statSync } from 'node:fs'
|
|
11
11
|
import { isAbsolute, relative, resolve } from 'node:path'
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* Environment for the adapter subprocess: an explicit allowlist.
|
|
15
|
+
*
|
|
16
|
+
* The adapter is a local third-party program (RFC3161 client / signer).
|
|
17
|
+
* Inheriting process.env would hand it every Advisers secret — ADVISERS_API_KEY,
|
|
18
|
+
* ADVISERS_AUDIT_KEY (the audit HMAC key), vault/sync/export passphrases and
|
|
19
|
+
* provider URLs (security audit SEC2-03, 2026-11-17). Only OS/runtime basics
|
|
20
|
+
* needed to start a program are passed through; credentials never are.
|
|
21
|
+
*/
|
|
22
|
+
const ADAPTER_ENV_KEYS = Object.freeze([
|
|
23
|
+
'PATH', 'Path', 'PATHEXT', 'COMSPEC', 'SYSTEMROOT', 'SystemRoot', 'windir',
|
|
24
|
+
'HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'APPDATA', 'LOCALAPPDATA',
|
|
25
|
+
'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES', 'TZ',
|
|
26
|
+
'PSModulePath',
|
|
27
|
+
])
|
|
28
|
+
|
|
29
|
+
function adapterEnv(source = process.env) {
|
|
30
|
+
const env = {}
|
|
31
|
+
for (const key of ADAPTER_ENV_KEYS) {
|
|
32
|
+
const value = source?.[key]
|
|
33
|
+
if (typeof value === 'string' && value) env[key] = value
|
|
34
|
+
}
|
|
35
|
+
return env
|
|
36
|
+
}
|
|
37
|
+
|
|
13
38
|
export const MAX_PROOF_BYTES = 200_000
|
|
14
39
|
|
|
15
40
|
export function timestampConfigured() {
|
|
@@ -30,7 +55,7 @@ export async function runLocalTimestamp(file, { cmd = process.env.ADVISERS_TIMES
|
|
|
30
55
|
if (!cmd) throw new Error('timestamp is not configured; set ADVISERS_TIMESTAMP_CMD to a local timestamp/signing executable')
|
|
31
56
|
const abs = assertProofFile(file, cwd)
|
|
32
57
|
return await new Promise((resolvePromise, reject) => {
|
|
33
|
-
const child = spawn(cmd, [abs], { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs, windowsHide: true })
|
|
58
|
+
const child = spawn(cmd, [abs], { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs, windowsHide: true, env: adapterEnv() })
|
|
34
59
|
let out = '', err = ''
|
|
35
60
|
child.stdout.on('data', (b) => { out += b.toString('utf8'); if (out.length > MAX_PROOF_BYTES) { child.kill(); reject(new Error(`timestamp proof exceeds ${MAX_PROOF_BYTES} bytes`)) } })
|
|
36
61
|
child.stderr.on('data', (b) => { err += b.toString('utf8') })
|
package/lib/tos/index.js
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime TOS gate: packaged manifest, local acceptance record, and the pure
|
|
3
|
+
* decision helpers the CLI uses to implement docs/TOS.md §2.
|
|
4
|
+
*
|
|
5
|
+
* Contract implemented here:
|
|
6
|
+
* - The acceptance record lives in `$ADVISERS_HOME/tos.json` (mode 0600, written
|
|
7
|
+
* with a same-directory temp file + fsync + rename).
|
|
8
|
+
* - The record stores ONLY `version`, `sha256` (the manifest's hash of the TOS
|
|
9
|
+
* text), `acceptedAt`, `channel` (`interactive` | `flag` | `env`),
|
|
10
|
+
* `nonInteractive`, and `revokedAt` after a revoke. It NEVER stores the terms
|
|
11
|
+
* text (or any user content).
|
|
12
|
+
* - Interactive acceptance requires the user to type 同意; `y`/`yes` are
|
|
13
|
+
* accepted as shortcuts. Empty input, Enter, `n`, or anything else rejects.
|
|
14
|
+
* - Non-interactive acceptance requires `--accept-tos` or
|
|
15
|
+
* `ADVISERS_ACCEPT_TOS=1|true|yes|<version>`. Per TOS §2.5 the env var never
|
|
16
|
+
* takes effect when stdin is a TTY; the explicit `--accept-tos` flag does.
|
|
17
|
+
* - A changed TOS version or text hash invalidates the old record; revocation
|
|
18
|
+
* (`revokedAt`) also invalidates it. The audit-chain writes and process exit
|
|
19
|
+
* codes stay in bin/advisers.js so this module can be unit-tested without a PTY.
|
|
20
|
+
*/
|
|
21
|
+
import { execFileSync } from 'node:child_process'
|
|
22
|
+
import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from 'node:fs'
|
|
23
|
+
import { randomBytes } from 'node:crypto'
|
|
24
|
+
import { homedir } from 'node:os'
|
|
25
|
+
import { dirname, join } from 'node:path'
|
|
26
|
+
import { fileURLToPath } from 'node:url'
|
|
27
|
+
import { createInterface } from 'node:readline/promises'
|
|
28
|
+
|
|
29
|
+
/** File name of the local acceptance record inside ADVISERS_HOME. */
|
|
30
|
+
export const RECORD_FILE = 'tos.json'
|
|
31
|
+
/** File name of the source-checkout dev notice marker inside ADVISERS_HOME. */
|
|
32
|
+
export const SOURCE_REVIEW_FILE = 'source-reviewed.json'
|
|
33
|
+
/** Repo root when running from a git checkout (four levels above lib/tos/index.js). */
|
|
34
|
+
const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url))
|
|
35
|
+
/** Online canonical text (also printed by `advisers tos show`). */
|
|
36
|
+
export const ONLINE_TOS_URL = 'https://github.com/PerryLink/advisers/blob/main/docs/TOS.md'
|
|
37
|
+
/** Commands that stay usable without accepting the TOS (TOS §2.1 last sentence). */
|
|
38
|
+
export const EXEMPT_COMMANDS = new Set(['help', '--help', '-h', 'version', '--version', '-v', 'status', 'doctor', 'init', 'tos'])
|
|
39
|
+
/** Words/answers that count as explicit interactive acceptance. */
|
|
40
|
+
export const ACCEPT_WORDS = new Set(['同意'])
|
|
41
|
+
export const ACCEPT_SHORTCUTS = new Set(['y', 'yes'])
|
|
42
|
+
/** Values that mean "yes" for --accept-tos=<value>. */
|
|
43
|
+
const ACCEPT_VALUES = new Set(['1', 'true', 'yes'])
|
|
44
|
+
/** Values that mean "no" for ADVISERS_ACCEPT_TOS (treated as unset). */
|
|
45
|
+
const DECLINE_VALUES = new Set(['0', 'false', 'no'])
|
|
46
|
+
|
|
47
|
+
const MANIFEST_PATH = fileURLToPath(new URL('./manifest.json', import.meta.url))
|
|
48
|
+
let manifestCache
|
|
49
|
+
|
|
50
|
+
/** Read the packaged manifest (version + per-file SHA-256). */
|
|
51
|
+
export function readManifest() {
|
|
52
|
+
manifestCache ??= JSON.parse(readFileSync(MANIFEST_PATH, 'utf8'))
|
|
53
|
+
return manifestCache
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Resolve the current TOS facts (version/hash/paths) from the packaged manifest. */
|
|
57
|
+
export function currentTos({ version } = {}) {
|
|
58
|
+
const manifest = readManifest()
|
|
59
|
+
const files = Array.isArray(manifest.files) ? manifest.files : []
|
|
60
|
+
const entry = files.find((file) => file.source === manifest.canonical)
|
|
61
|
+
?? files.find((file) => file.path === 'terms.zh-CN.md')
|
|
62
|
+
?? files[0]
|
|
63
|
+
if (!entry?.sha256 || typeof entry.path !== 'string') throw new Error('packaged TOS manifest is missing the TOS text hash/path')
|
|
64
|
+
const envVersion = typeof process.env.ADVISERS_TOS_VERSION === 'string' ? process.env.ADVISERS_TOS_VERSION.trim() : ''
|
|
65
|
+
const resolvedVersion = version ?? (envVersion || manifest.version)
|
|
66
|
+
return {
|
|
67
|
+
version: resolvedVersion,
|
|
68
|
+
manifestVersion: manifest.version,
|
|
69
|
+
effectiveFrom: manifest.effectiveFrom,
|
|
70
|
+
language: manifest.language,
|
|
71
|
+
sha256: entry.sha256,
|
|
72
|
+
canonical: manifest.canonical,
|
|
73
|
+
termsPath: fileURLToPath(new URL(entry.path, import.meta.url)),
|
|
74
|
+
url: ONLINE_TOS_URL,
|
|
75
|
+
versionOverridden: Boolean(envVersion && envVersion !== manifest.version),
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Default Advisers home (same rule as the CLI). */
|
|
80
|
+
export function defaultHome() {
|
|
81
|
+
return process.env.ADVISERS_HOME || join(homedir(), '.advisers')
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Path of the acceptance record for a home directory. */
|
|
85
|
+
export function acceptancePath(home = defaultHome()) {
|
|
86
|
+
return join(home, RECORD_FILE)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Validate a parsed record; returns a clean record or null (fail closed). */
|
|
90
|
+
export function validateAcceptance(record) {
|
|
91
|
+
if (!record || typeof record !== 'object' || Array.isArray(record)) return null
|
|
92
|
+
const version = typeof record.version === 'string' ? record.version.trim() : ''
|
|
93
|
+
const sha256 = typeof record.sha256 === 'string' ? record.sha256.trim() : ''
|
|
94
|
+
const acceptedAt = typeof record.acceptedAt === 'string' ? record.acceptedAt.trim() : ''
|
|
95
|
+
const channel = ['interactive', 'flag', 'env'].includes(record.channel) ? record.channel : ''
|
|
96
|
+
if (!version || !/^[a-f0-9]{64}$/.test(sha256) || !acceptedAt || !channel) return null
|
|
97
|
+
if (Number.isNaN(Date.parse(acceptedAt))) return null
|
|
98
|
+
const clean = {
|
|
99
|
+
version,
|
|
100
|
+
sha256,
|
|
101
|
+
acceptedAt,
|
|
102
|
+
channel,
|
|
103
|
+
nonInteractive: record.nonInteractive === true || record.nonInteractive === 1,
|
|
104
|
+
}
|
|
105
|
+
if (typeof record.revokedAt === 'string' && !Number.isNaN(Date.parse(record.revokedAt))) clean.revokedAt = record.revokedAt
|
|
106
|
+
return clean
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Read the local acceptance record; missing/corrupt records fail closed (null). */
|
|
110
|
+
export function readAcceptance(home = defaultHome()) {
|
|
111
|
+
try {
|
|
112
|
+
const target = acceptancePath(home)
|
|
113
|
+
if (!existsSync(target)) return null
|
|
114
|
+
return validateAcceptance(JSON.parse(readFileSync(target, 'utf8')))
|
|
115
|
+
} catch {
|
|
116
|
+
return null
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Atomically write the acceptance record with mode 0600. */
|
|
121
|
+
export function writeAcceptance(home = defaultHome(), record) {
|
|
122
|
+
const clean = validateAcceptance(record)
|
|
123
|
+
if (!clean) throw new Error('refusing to write an invalid TOS acceptance record')
|
|
124
|
+
const target = acceptancePath(home)
|
|
125
|
+
const dir = dirname(target)
|
|
126
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
127
|
+
try { chmodSync(dir, 0o700) } catch {}
|
|
128
|
+
const temp = join(dir, `.${RECORD_FILE}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`)
|
|
129
|
+
const fd = openSync(temp, 'wx', 0o600)
|
|
130
|
+
try {
|
|
131
|
+
writeSync(fd, JSON.stringify(clean, null, 2) + '\n')
|
|
132
|
+
fsyncSync(fd)
|
|
133
|
+
} finally {
|
|
134
|
+
closeSync(fd)
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
renameSync(temp, target)
|
|
138
|
+
} catch (error) {
|
|
139
|
+
try { if (existsSync(temp)) rmSync(temp) } catch {}
|
|
140
|
+
throw error
|
|
141
|
+
}
|
|
142
|
+
try { chmodSync(target, 0o600) } catch {}
|
|
143
|
+
try {
|
|
144
|
+
const dirFd = openSync(dir, 'r')
|
|
145
|
+
try { fsyncSync(dirFd) } finally { closeSync(dirFd) }
|
|
146
|
+
} catch {}
|
|
147
|
+
return clean
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Mark the current acceptance as revoked (keeps version/hash/timestamp history). */
|
|
151
|
+
export function revokeAcceptance(home = defaultHome(), { revokedAt = new Date().toISOString() } = {}) {
|
|
152
|
+
const record = readAcceptance(home)
|
|
153
|
+
if (!record) return null
|
|
154
|
+
return writeAcceptance(home, { ...record, revokedAt })
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Decide whether the current TOS version/hash is accepted for a home.
|
|
159
|
+
* @returns {{accepted: boolean, reason: 'accepted'|'missing'|'invalid'|'revoked'|'version-changed'|'text-changed', record: object|null}}
|
|
160
|
+
*/
|
|
161
|
+
export function acceptanceStatus({ home = defaultHome(), version, sha256 } = {}) {
|
|
162
|
+
const info = version && sha256 ? { version, sha256 } : currentTos()
|
|
163
|
+
const record = readAcceptance(home)
|
|
164
|
+
if (!record) return { accepted: false, reason: 'missing', record: null }
|
|
165
|
+
if (record.revokedAt) return { accepted: false, reason: 'revoked', record }
|
|
166
|
+
if (record.version !== info.version) return { accepted: false, reason: 'version-changed', record }
|
|
167
|
+
if (record.sha256 !== info.sha256) return { accepted: false, reason: 'text-changed', record }
|
|
168
|
+
return { accepted: true, reason: 'accepted', record }
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Interpret an interactive answer. `同意` is required; y/yes are shortcuts.
|
|
173
|
+
* Empty input (Enter), n, or anything else rejects.
|
|
174
|
+
*/
|
|
175
|
+
export function decidePrompt(answer) {
|
|
176
|
+
const normalized = String(answer ?? '').trim().toLowerCase()
|
|
177
|
+
if (!normalized) return { accepted: false, reason: 'empty' }
|
|
178
|
+
if (ACCEPT_WORDS.has(normalized) || ACCEPT_SHORTCUTS.has(normalized)) return { accepted: true, reason: 'explicit' }
|
|
179
|
+
return { accepted: false, reason: 'rejected' }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Resolve explicit non-interactive consent.
|
|
184
|
+
* @returns {null | {ok: true, channel: 'flag'|'env', nonInteractive: true} | {ok: false, error: string}}
|
|
185
|
+
*/
|
|
186
|
+
export function resolveConsent({ flag, env, version, isTTY = false } = {}) {
|
|
187
|
+
if (flag !== undefined && flag !== null && flag !== false) {
|
|
188
|
+
const raw = flag === true ? '' : String(flag).trim()
|
|
189
|
+
if (!raw || ACCEPT_VALUES.has(raw.toLowerCase()) || raw === version) return { ok: true, channel: 'flag', nonInteractive: true }
|
|
190
|
+
return { ok: false, error: `--accept-tos version "${raw}" does not match the current TOS version ${version}` }
|
|
191
|
+
}
|
|
192
|
+
// TOS §2.5: ADVISERS_ACCEPT_TOS never takes effect in an interactive TTY.
|
|
193
|
+
if (isTTY) return null
|
|
194
|
+
const raw = env === undefined || env === null ? '' : String(env).trim()
|
|
195
|
+
if (!raw) return null
|
|
196
|
+
const lowered = raw.toLowerCase()
|
|
197
|
+
if (DECLINE_VALUES.has(lowered)) return null
|
|
198
|
+
if (ACCEPT_VALUES.has(lowered) || raw === version) return { ok: true, channel: 'env', nonInteractive: true }
|
|
199
|
+
return { ok: false, error: `ADVISERS_ACCEPT_TOS must be 1|true|yes or the current TOS version ${version} (got "${raw}")` }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Whether a command may run without accepting the TOS. */
|
|
203
|
+
export function isExemptCommand(command, { isTTY = false } = {}) {
|
|
204
|
+
if (!command) return !isTTY
|
|
205
|
+
return EXEMPT_COMMANDS.has(command)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** TTY summary printed before the first acceptance prompt (12 lines, plus prompt). */
|
|
209
|
+
export function summaryLines({ version = currentTos().version, url = ONLINE_TOS_URL } = {}) {
|
|
210
|
+
return [
|
|
211
|
+
`Advisers · 使用条款摘要(v${version})`,
|
|
212
|
+
'1. 许可:PolyForm Noncommercial 1.0.0,仅限个人非商业用途;商业使用需另行书面授权。文档/数据/设计按 CC BY-NC-SA 4.0。',
|
|
213
|
+
'2. 旧版本许可不变:0.2.0-preview.71 及更早版本按其发布时的许可证继续有效。',
|
|
214
|
+
'3. 本地优先助手,不提供法律/医疗/财务等专业意见;AI 输出可能出错,请自行核验并承担对外使用后果。',
|
|
215
|
+
'4. 禁止违法与有害用途:违法内容、诈骗、侵权、危害未成年人、深度伪造或逃避 AI 标识等(详见第 4 条)。',
|
|
216
|
+
'5. 你是内容安全审核与 AI 生成内容标识的第一责任人。',
|
|
217
|
+
'6. 数据默认留在本机;设置 ADVISERS_API_KEY 后,相关输入会发送给你配置的模型服务。',
|
|
218
|
+
'7. 免责与责任限制:按“现状”提供;免费版本累计赔偿责任上限为人民币壹佰元(¥100),法律不得排除的责任除外。',
|
|
219
|
+
'8. 管辖:适用中华人民共和国法律;争议由运营者住所地有管辖权的人民法院管辖(第 15.2 条)。',
|
|
220
|
+
'9. 修改人格/例行、数据替换等操作每次会再次确认;TTS/DLC 在 0.2.0 不提供,未来将另行取得明确同意。',
|
|
221
|
+
`10. 完整条款:运行 advisers tos show(随包于 packages/advisers/lib/tos/terms.zh-CN.md);在线:${url}`,
|
|
222
|
+
'11. 接受记录只含版本、文本 SHA-256、时间与渠道(写入本地审计链,不写条款正文);可用 advisers tos revoke 撤回。',
|
|
223
|
+
]
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Short re-confirmation notice shown for each modification surface (≤5 lines). */
|
|
227
|
+
export function modificationNotice({ scope = 'config', action = '' } = {}) {
|
|
228
|
+
if (scope === 'routine') {
|
|
229
|
+
return [
|
|
230
|
+
'修改确认 · 例行/自动化(routine)',
|
|
231
|
+
'例行会在后续会话中被复用;请勿写入违法、越权或对外自动发送的步骤。',
|
|
232
|
+
'仅个人非商业用途;本次确认会写入本地审计链(tos.reaccept,scope=routine)。',
|
|
233
|
+
]
|
|
234
|
+
}
|
|
235
|
+
if (scope === 'import') {
|
|
236
|
+
return [
|
|
237
|
+
'修改确认 · 数据替换(import --replace)',
|
|
238
|
+
'导入会覆盖既有账本(导入前会自动备份 state.db);请确认导入文件来源可信。',
|
|
239
|
+
'仅个人非商业用途;本次确认会写入本地审计链(tos.reaccept,scope=import)。',
|
|
240
|
+
]
|
|
241
|
+
}
|
|
242
|
+
return [
|
|
243
|
+
'修改确认 · 人格/设定(soul)',
|
|
244
|
+
'你即将替换 Advisers 的人格/行为设定。许可:PolyForm Noncommercial 1.0.0,仅个人非商业;对外分发或商用需另行授权。',
|
|
245
|
+
'设定导致的输出由你负责,不得写入违法或伤害性指令;本次确认会写入本地审计链(tos.reaccept,scope=config)。',
|
|
246
|
+
]
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* TOS §2.3 "源码修改版" row: when the CLI runs from a git checkout that has
|
|
251
|
+
* local modifications, show a non-blocking notice once per fingerprint change.
|
|
252
|
+
* Returns null when this is not a git checkout of the Advisers repo.
|
|
253
|
+
* @returns {string|null} fingerprint like `<sha7|nogit>+dirty` / `<sha7>`
|
|
254
|
+
*/
|
|
255
|
+
export function sourceCheckoutFingerprint() {
|
|
256
|
+
try {
|
|
257
|
+
// Only a real checkout of this repo: an npm install inside some *other* git
|
|
258
|
+
// project must not be mistaken for the Advisers source checkout.
|
|
259
|
+
if (!existsSync(join(REPO_ROOT, '.git'))) return null
|
|
260
|
+
if (!existsSync(join(REPO_ROOT, 'packages', 'advisers', 'bin', 'advisers.js'))) return null
|
|
261
|
+
} catch {
|
|
262
|
+
return null
|
|
263
|
+
}
|
|
264
|
+
const run = (args) => execFileSync('git', ['-C', REPO_ROOT, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 }).trim()
|
|
265
|
+
try {
|
|
266
|
+
const head = run(['rev-parse', '--short=7', 'HEAD'])
|
|
267
|
+
const dirty = run(['status', '--porcelain', '--untracked-files=no']).length > 0
|
|
268
|
+
return `${head || 'nogit'}${dirty ? '+dirty' : ''}`
|
|
269
|
+
} catch {
|
|
270
|
+
return 'nogit'
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Read the last fingerprint the dev-source notice was shown for (marker file). */
|
|
275
|
+
export function readSourceFingerprint(home = defaultHome()) {
|
|
276
|
+
try {
|
|
277
|
+
const parsed = JSON.parse(readFileSync(join(home, SOURCE_REVIEW_FILE), 'utf8'))
|
|
278
|
+
return typeof parsed?.fingerprint === 'string' ? parsed.fingerprint : null
|
|
279
|
+
} catch {
|
|
280
|
+
return null
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Atomically remember the fingerprint the notice was shown for (0600). */
|
|
285
|
+
export function writeSourceFingerprint(home = defaultHome(), fingerprint) {
|
|
286
|
+
if (typeof fingerprint !== 'string' || !fingerprint) throw new Error('refusing to write an empty source fingerprint')
|
|
287
|
+
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
288
|
+
const target = join(home, SOURCE_REVIEW_FILE)
|
|
289
|
+
const temp = join(home, `.${SOURCE_REVIEW_FILE}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`)
|
|
290
|
+
const fd = openSync(temp, 'wx', 0o600)
|
|
291
|
+
try {
|
|
292
|
+
writeSync(fd, JSON.stringify({ fingerprint, noticedAt: new Date().toISOString() }, null, 2) + '\n')
|
|
293
|
+
fsyncSync(fd)
|
|
294
|
+
} finally {
|
|
295
|
+
closeSync(fd)
|
|
296
|
+
}
|
|
297
|
+
try { renameSync(temp, target) } catch (error) { try { if (existsSync(temp)) rmSync(temp) } catch {} throw error }
|
|
298
|
+
try { chmodSync(target, 0o600) } catch {}
|
|
299
|
+
return fingerprint
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Whether the dev-source notice should be shown (dirty checkout, new fingerprint). */
|
|
303
|
+
export function shouldNoticeSourceModified({ home = defaultHome(), fingerprint } = {}) {
|
|
304
|
+
if (typeof fingerprint !== 'string' || !fingerprint.endsWith('+dirty')) return false
|
|
305
|
+
return readSourceFingerprint(home) !== fingerprint
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Non-blocking notice for a locally modified source checkout (TOS §2.3). */
|
|
309
|
+
export function sourceModifiedNotice({ fingerprint = 'nogit+dirty' } = {}) {
|
|
310
|
+
return [
|
|
311
|
+
`开发者模式 · 源码修改版(指纹 ${fingerprint})`,
|
|
312
|
+
'你在源码 checkout 中运行含本地改动的版本。PolyForm Noncommercial 1.0.0 允许个人非商业修改;对外提供服务或分发修改版需另行授权。',
|
|
313
|
+
'请勿移除 policy / 审计 / 内容安全钩子。本提示不阻塞运行,指纹变化后首次提示。',
|
|
314
|
+
]
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Print notice lines and read one interactive answer. TTY-only; callers check
|
|
319
|
+
* process.stdin.isTTY first (the pure `decidePrompt` is what the tests exercise).
|
|
320
|
+
* @returns {Promise<{accepted: boolean, reason: string, answer: string}>}
|
|
321
|
+
*/
|
|
322
|
+
export async function promptForConsent({ version, lines, question, stdin = process.stdin, stdout = process.stdout } = {}) {
|
|
323
|
+
const body = Array.isArray(lines) && lines.length ? lines : summaryLines({ version })
|
|
324
|
+
const terminal = createInterface({ input: stdin, output: stdout })
|
|
325
|
+
try {
|
|
326
|
+
for (const line of body) stdout.write(`${line}\n`)
|
|
327
|
+
const answer = await terminal.question(question ?? '输入“同意”后回车接受并继续(n 或直接 Enter 拒绝):')
|
|
328
|
+
return { ...decidePrompt(answer), answer: String(answer ?? '').trim() }
|
|
329
|
+
} finally {
|
|
330
|
+
try { terminal.close() } catch {}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": "advisers.tos/1",
|
|
3
|
+
"version": "2026.11.2",
|
|
4
|
+
"effectiveFrom": "2026-11-17",
|
|
5
|
+
"language": "zh-CN",
|
|
6
|
+
"canonical": "docs/TOS.md",
|
|
7
|
+
"shortNotice": "docs/DISCLAIMER.md",
|
|
8
|
+
"privacy": "docs/PRIVACY.md",
|
|
9
|
+
"safety": "docs/SAFETY.md",
|
|
10
|
+
"files": [
|
|
11
|
+
{
|
|
12
|
+
"path": "terms.zh-CN.md",
|
|
13
|
+
"source": "docs/TOS.md",
|
|
14
|
+
"sha256": "c40f869ad806e74a2e3870e7041d4d4602f6d1a4c2619b80b3e453333b9713dd"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"path": "summary.zh-CN.md",
|
|
18
|
+
"source": "docs/DISCLAIMER.md",
|
|
19
|
+
"sha256": "22f4c093a186d8f256744a345d7011e8bc05bcd076f67ded097bbe55dae0c1a8"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"path": "privacy.zh-CN.md",
|
|
23
|
+
"source": "docs/PRIVACY.md",
|
|
24
|
+
"sha256": "c20eb1525a5b8c232027bff6db88d57802696f1cf04cc06349e3440e2b90d0b9"
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"path": "safety.zh-CN.md",
|
|
28
|
+
"source": "docs/SAFETY.md",
|
|
29
|
+
"sha256": "2358b187f0f97af8dd8aeb30026654ea55804acc9dbeb7f87fd778fe0a29f044"
|
|
30
|
+
}
|
|
31
|
+
]
|
|
32
|
+
}
|