advisers 0.1.0-preview.4 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +131 -21
- package/NOTICE +34 -0
- package/README-zh.md +40 -9
- package/README.md +53 -10
- package/THIRD-PARTY-NOTICES.md +277 -0
- package/bin/advisers.js +4230 -122
- package/index.js +1 -1
- package/lib/agent.js +414 -0
- package/lib/attachments.js +283 -0
- package/lib/capture.js +168 -0
- package/lib/context-window.js +123 -0
- package/lib/digest.js +27 -0
- package/lib/doc-review.js +30 -0
- package/lib/egress.js +27 -0
- package/lib/evidence.js +1995 -0
- package/lib/ical.js +542 -0
- package/lib/imap.js +181 -0
- package/lib/importers.js +1001 -0
- package/lib/learning.js +46 -0
- package/lib/mcp-server.js +869 -0
- package/lib/model.js +307 -0
- package/lib/notify.js +189 -0
- package/lib/nudge.js +10 -0
- package/lib/ocr.js +47 -0
- package/lib/pdf.js +105 -0
- package/lib/pet-brief-store.js +51 -0
- package/lib/pet-brief.js +644 -0
- package/lib/receipt-verify.js +624 -0
- package/lib/relative-date.js +393 -0
- package/lib/remind.js +690 -0
- package/lib/research.js +193 -0
- package/lib/review.js +88 -0
- package/lib/routine.js +22 -0
- package/lib/safety/classifier.js +392 -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 +1022 -0
- package/lib/sync.js +129 -0
- package/lib/timestamp.js +45 -0
- 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/lib/ui.js +49 -0
- package/lib/undo.js +83 -0
- package/lib/vault.js +51 -0
- package/package.json +26 -4
package/lib/sync.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* P2: file-based end-to-end encrypted snapshot sync.
|
|
3
|
+
*
|
|
4
|
+
* The user chooses a directory that their existing sync tool (OneDrive, Dropbox,
|
|
5
|
+
* Syncthing, rsync, a NAS) already replicates. Advisers only writes encrypted
|
|
6
|
+
* snapshots there and never talks to a sync server itself.
|
|
7
|
+
*
|
|
8
|
+
* Scope: whole-database snapshots, manual push/pull, last-snapshot-wins.
|
|
9
|
+
* Not provided: continuous merge, multi-writer conflict resolution, cloud accounts.
|
|
10
|
+
* Pull always backs up the local DB before replacing it.
|
|
11
|
+
*/
|
|
12
|
+
import { chmodSync, closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { createHash } from 'node:crypto'
|
|
14
|
+
import { basename, join } from 'node:path'
|
|
15
|
+
import { decryptJson, encryptJson, isVaultEnvelope } from './vault.js'
|
|
16
|
+
|
|
17
|
+
/** fsync a directory entry so a rename survives a crash. */
|
|
18
|
+
function fsyncDir(dir) {
|
|
19
|
+
try {
|
|
20
|
+
const fd = openSync(dir, 'r')
|
|
21
|
+
try { fsyncSync(fd) } finally { closeSync(fd) }
|
|
22
|
+
} catch {}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Write a same-directory temp file, flush it, then rename it into place. */
|
|
26
|
+
function writeAtomic(file, data, { mode = 0o600 } = {}) {
|
|
27
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 })
|
|
28
|
+
const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
29
|
+
try {
|
|
30
|
+
writeFileSync(tmp, data, { mode, flush: true })
|
|
31
|
+
renameSync(tmp, file)
|
|
32
|
+
} catch (error) {
|
|
33
|
+
try { if (existsSync(tmp)) rmSync(tmp) } catch {}
|
|
34
|
+
throw error
|
|
35
|
+
}
|
|
36
|
+
try { chmodSync(file, mode) } catch {}
|
|
37
|
+
fsyncDir(join(file, '..'))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const SYNC_PREFIX = 'advisers-'
|
|
41
|
+
export const SYNC_SUFFIX = '.enc.json'
|
|
42
|
+
|
|
43
|
+
export function sanitizeDevice(value) {
|
|
44
|
+
return String(value || 'device').toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'device'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function snapshotName(device, date = new Date()) {
|
|
48
|
+
const stamp = date.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z')
|
|
49
|
+
return `${SYNC_PREFIX}${sanitizeDevice(device)}-${stamp}${SYNC_SUFFIX}`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function createSnapshot({ dbPath, passphrase, device = 'device', createdAt = new Date() }) {
|
|
53
|
+
if (!existsSync(dbPath)) throw new Error(`no database at ${dbPath}`)
|
|
54
|
+
const bytes = readFileSync(dbPath)
|
|
55
|
+
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
56
|
+
const payload = { kind: 'advisers-sync-db', version: 1, device: sanitizeDevice(device), createdAt: createdAt.toISOString(), sha256, db: bytes.toString('base64') }
|
|
57
|
+
return { name: snapshotName(device, createdAt), payload, envelope: encryptJson(payload, passphrase) }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function listSnapshots(dir) {
|
|
61
|
+
if (!existsSync(dir)) return []
|
|
62
|
+
return readdirSync(dir)
|
|
63
|
+
.filter((n) => n.startsWith(SYNC_PREFIX) && n.endsWith(SYNC_SUFFIX))
|
|
64
|
+
.map((name) => { const st = statSync(join(dir, name)); return { name, mtimeMs: st.mtimeMs, bytes: st.size } })
|
|
65
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function pushSnapshot({ dir, dbPath, passphrase, device = 'device', createdAt = new Date() }) {
|
|
69
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
70
|
+
const snap = createSnapshot({ dbPath, passphrase, device, createdAt })
|
|
71
|
+
const out = join(dir, snap.name)
|
|
72
|
+
const body = JSON.stringify(snap.envelope) + '\n'
|
|
73
|
+
writeAtomic(out, body, { mode: 0o600 })
|
|
74
|
+
return { file: out, sha256: snap.payload.sha256, bytes: Buffer.byteLength(body) }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function latestDbMtime(dbPath) {
|
|
78
|
+
let latest = 0
|
|
79
|
+
for (const suffix of ['', '-wal']) {
|
|
80
|
+
try { latest = Math.max(latest, statSync(dbPath + suffix).mtimeMs) } catch {}
|
|
81
|
+
}
|
|
82
|
+
return latest
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Replace the local database with the chosen snapshot.
|
|
87
|
+
*
|
|
88
|
+
* Safety (robustness audit P1-4): when the local database was written after
|
|
89
|
+
* the snapshot was taken on *another* device, overwriting it would silently
|
|
90
|
+
* drop those writes. Refuse unless force:true. A snapshot pushed from this
|
|
91
|
+
* HOME (device marker matches payload.device) is treated as an intentional
|
|
92
|
+
* restore, and no local database at all is always allowed.
|
|
93
|
+
*/
|
|
94
|
+
export function pullSnapshot({ dir, dbPath, passphrase, file, force = false, localMtimeMs, localDevice }) {
|
|
95
|
+
const snapshots = listSnapshots(dir)
|
|
96
|
+
if (!snapshots.length) throw new Error(`no Advisers snapshots in ${dir}`)
|
|
97
|
+
const chosen = file ? snapshots.find((s) => s.name === basename(file)) : snapshots[0]
|
|
98
|
+
if (!chosen) throw new Error(`snapshot not found: ${file}`)
|
|
99
|
+
const envelope = JSON.parse(readFileSync(join(dir, chosen.name), 'utf8'))
|
|
100
|
+
if (!isVaultEnvelope(envelope)) throw new Error('snapshot is not an Advisers encrypted envelope')
|
|
101
|
+
const payload = decryptJson(envelope, passphrase)
|
|
102
|
+
if (payload.kind !== 'advisers-sync-db' || typeof payload.db !== 'string') throw new Error('snapshot is not an Advisers database snapshot')
|
|
103
|
+
const bytes = Buffer.from(payload.db, 'base64')
|
|
104
|
+
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
105
|
+
if (sha256 !== payload.sha256) throw new Error('snapshot checksum mismatch')
|
|
106
|
+
if (existsSync(dbPath) && !force) {
|
|
107
|
+
if (readFileSync(dbPath).equals(bytes)) return { file: chosen.name, sha256, changed: false, backup: null }
|
|
108
|
+
const snapshotAt = Date.parse(payload.createdAt ?? '')
|
|
109
|
+
const localAt = Number.isFinite(localMtimeMs) && localMtimeMs > 0 ? localMtimeMs : latestDbMtime(dbPath)
|
|
110
|
+
const sameDevice = Boolean(localDevice) && Boolean(payload.device) && sanitizeDevice(payload.device) === sanitizeDevice(localDevice)
|
|
111
|
+
if (!sameDevice) {
|
|
112
|
+
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`)
|
|
113
|
+
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).`)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
let backup = null
|
|
117
|
+
if (existsSync(dbPath)) {
|
|
118
|
+
backup = `${dbPath}.before-sync-${Date.now()}`
|
|
119
|
+
copyFileSync(dbPath, backup)
|
|
120
|
+
for (const suffix of ['-wal', '-shm']) {
|
|
121
|
+
try { if (existsSync(dbPath + suffix)) copyFileSync(dbPath + suffix, backup + suffix) } catch {}
|
|
122
|
+
}
|
|
123
|
+
for (const suffix of ['-wal', '-shm']) { try { rmSync(dbPath + suffix) } catch {} }
|
|
124
|
+
} else {
|
|
125
|
+
mkdirSync(join(dbPath, '..'), { recursive: true, mode: 0o700 })
|
|
126
|
+
}
|
|
127
|
+
writeAtomic(dbPath, bytes, { mode: 0o600 })
|
|
128
|
+
return { file: chosen.name, sha256, changed: true, backup, device: payload.device, createdAt: payload.createdAt }
|
|
129
|
+
}
|
package/lib/timestamp.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* P2: third-party timestamp adapter (local executable).
|
|
3
|
+
*
|
|
4
|
+
* Advisers never calls a timestamp authority itself. The user may point
|
|
5
|
+
* `ADVISERS_TIMESTAMP_CMD` at a local tool (e.g. an RFC3161 client or an
|
|
6
|
+
* internal signer) that receives the file path and writes a proof to stdout.
|
|
7
|
+
* Without it the feature fails closed; no network is used by Advisers.
|
|
8
|
+
*/
|
|
9
|
+
import { spawn } from 'node:child_process'
|
|
10
|
+
import { statSync } from 'node:fs'
|
|
11
|
+
import { isAbsolute, relative, resolve } from 'node:path'
|
|
12
|
+
|
|
13
|
+
export const MAX_PROOF_BYTES = 200_000
|
|
14
|
+
|
|
15
|
+
export function timestampConfigured() {
|
|
16
|
+
return Boolean(process.env.ADVISERS_TIMESTAMP_CMD)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function assertProofFile(file, cwd = process.cwd()) {
|
|
20
|
+
const abs = resolve(cwd, file)
|
|
21
|
+
const rel = relative(resolve(cwd), abs)
|
|
22
|
+
if (rel.startsWith('..') || isAbsolute(rel)) throw new Error(`timestamp file escapes workspace: ${file}`)
|
|
23
|
+
const info = statSync(abs)
|
|
24
|
+
if (!info.isFile()) throw new Error(`not a file: ${file}`)
|
|
25
|
+
if (info.size > 10 * 1024 * 1024) throw new Error('timestamp file is larger than 10 MB')
|
|
26
|
+
return abs
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function runLocalTimestamp(file, { cmd = process.env.ADVISERS_TIMESTAMP_CMD, timeoutMs = 30_000, cwd = process.cwd() } = {}) {
|
|
30
|
+
if (!cmd) throw new Error('timestamp is not configured; set ADVISERS_TIMESTAMP_CMD to a local timestamp/signing executable')
|
|
31
|
+
const abs = assertProofFile(file, cwd)
|
|
32
|
+
return await new Promise((resolvePromise, reject) => {
|
|
33
|
+
const child = spawn(cmd, [abs], { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs, windowsHide: true })
|
|
34
|
+
let out = '', err = ''
|
|
35
|
+
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
|
+
child.stderr.on('data', (b) => { err += b.toString('utf8') })
|
|
37
|
+
child.on('error', (e) => reject(new Error(`timestamp command failed to start: ${e.message}`)))
|
|
38
|
+
child.on('close', (code, signal) => {
|
|
39
|
+
if (code !== 0) return reject(new Error(`timestamp command exited ${code ?? signal}: ${err.trim().slice(0, 300)}`))
|
|
40
|
+
const proof = out.trim()
|
|
41
|
+
if (!proof) return reject(new Error('timestamp command returned an empty proof'))
|
|
42
|
+
resolvePromise(proof)
|
|
43
|
+
})
|
|
44
|
+
})
|
|
45
|
+
}
|
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
|
+
}
|