advisers 0.3.2 → 0.4.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.
Files changed (44) hide show
  1. package/README-zh.md +13 -14
  2. package/README.md +37 -23
  3. package/THIRD-PARTY-NOTICES.md +1 -1
  4. package/bin/advisers.js +2302 -95
  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/error-codes.js +516 -7
  11. package/lib/evidence.js +697 -113
  12. package/lib/kb-extract.js +626 -0
  13. package/lib/kb-facts.js +429 -0
  14. package/lib/kb-pages.js +1084 -0
  15. package/lib/kb.js +1036 -0
  16. package/lib/mail-errors.js +46 -0
  17. package/lib/mail-extract.js +351 -0
  18. package/lib/mail-imap.js +446 -0
  19. package/lib/mail-import.js +176 -0
  20. package/lib/mail-parse.js +223 -0
  21. package/lib/mail-store.js +731 -0
  22. package/lib/mail.js +506 -0
  23. package/lib/mcp-server.js +196 -10
  24. package/lib/notify.js +265 -7
  25. package/lib/policy/decision.js +315 -0
  26. package/lib/policy/egress.js +268 -0
  27. package/lib/policy/errors.js +71 -0
  28. package/lib/policy/index.js +99 -0
  29. package/lib/policy/rules.js +468 -0
  30. package/lib/policy/surfaces.js +141 -0
  31. package/lib/receipt-verify.js +199 -19
  32. package/lib/receivables.js +1653 -0
  33. package/lib/scheduler.js +453 -9
  34. package/lib/shell.js +1406 -0
  35. package/lib/source.js +98 -3
  36. package/lib/sqlite.js +366 -49
  37. package/lib/tos/index.js +2 -2
  38. package/lib/tos/manifest.json +6 -6
  39. package/lib/tos/privacy.zh-CN.md +33 -20
  40. package/lib/tos/safety.zh-CN.md +7 -6
  41. package/lib/tos/summary.zh-CN.md +3 -2
  42. package/lib/tos/terms.zh-CN.md +31 -16
  43. package/lib/urgency.js +467 -0
  44. package/package.json +4 -4
package/lib/mcp-server.js CHANGED
@@ -1,10 +1,22 @@
1
1
  /**
2
- * Advisers MCP server (JSON-RPC 2.0 over stdio, protocol '2024-11-05').
2
+ * Advisers MCP server (JSON-RPC 2.0 over stdio; legacy '2024-11-05' handshake
3
+ * plus the stateless modern '2026-07-28' revision — dual-era since 0.4.0).
3
4
  *
4
5
  * This module is the testable library extracted from the MCP section of
5
6
  * 'bin/advisers.js'. The binary owns process wiring (home, audit key, sqlite);
6
7
  * this module owns the protocol surface and never touches the network.
7
8
  *
9
+ * Era rules (0.4.0):
10
+ * - A request is served by the modern path only when it carries the per-request
11
+ * metadata in 'params._meta' (io.modelcontextprotocol/protocolVersion or
12
+ * .../clientCapabilities) and is not 'initialize'. The modern path is a strict
13
+ * allowlist (server/discover, tools/list, tools/call, resources/list,
14
+ * resources/read) that returns the SAME read-model payload wrapped in the
15
+ * modern result envelope (resultType + optional ttlMs/cacheScope + _meta).
16
+ * - Every other request keeps the legacy dispatcher byte-for-byte, so 0.3.x
17
+ * clients observe exactly the old responses. ADVISERS_MCP_MODERN=off disables
18
+ * the era layer entirely.
19
+ *
8
20
  * Surface (0.2.0):
9
21
  * - 5 read-only tools: today / commit_ls / who / evidence / remind
10
22
  * - 2 whitelisted writes:
@@ -49,13 +61,65 @@ export const PROTOCOL_VERSION = '2024-11-05'
49
61
  *
50
62
  * The 2025-06-18 / 2025-11-25 revisions keep the same initialize/tools/
51
63
  * resources lifecycle this server implements, so echoing the client's
52
- * supported version is safe; anything else (including the stateless
53
- * 2026-07-28 modern revision, which needs server/discover) falls back to
54
- * PROTOCOL_VERSION. The modern revisions are NOT implemented here: this
55
- * server deliberately does not advertise server/discover, so a modern client
56
- * probes once, gets an unknown-method error, and falls back to initialize.
64
+ * supported version is safe; anything else (including a stray 2026-07-28
65
+ * value, which is modern-era and never negotiated through initialize) falls
66
+ * back to PROTOCOL_VERSION. The modern revision is served statelessly through
67
+ * the per-request `_meta` path below; dual-era clients pick it with
68
+ * `server/discover` and legacy clients keep the handshake.
57
69
  */
58
70
  export const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze(['2024-11-05', '2025-06-18', '2025-11-25'])
71
+ /**
72
+ * Modern (stateless) MCP revision served by the era layer (0.4.0).
73
+ *
74
+ * Spec: <https://modelcontextprotocol.io/specification/2026-07-28/>. There is
75
+ * no initialize handshake: every request declares its protocol version and
76
+ * client capabilities in `params._meta` and the server answers it statelessly.
77
+ */
78
+ export const MODERN_PROTOCOL_VERSION = '2026-07-28'
79
+ export const SUPPORTED_MODERN_PROTOCOL_VERSIONS = Object.freeze([MODERN_PROTOCOL_VERSION])
80
+ /** Reserved modern `_meta` keys (spec: basic/index#_meta). */
81
+ export const META_PROTOCOL_VERSION = 'io.modelcontextprotocol/protocolVersion'
82
+ export const META_CLIENT_CAPABILITIES = 'io.modelcontextprotocol/clientCapabilities'
83
+ export const META_SERVER_INFO = 'io.modelcontextprotocol/serverInfo'
84
+ /**
85
+ * Explicit modern method allowlist. The modern era removed initialize/ping/
86
+ * logging/roots and keeps resources/subscribe out; anything not listed here is
87
+ * answered with -32601 instead of falling through to the legacy dispatcher.
88
+ */
89
+ export const MODERN_METHODS = Object.freeze(['server/discover', 'tools/list', 'tools/call', 'resources/list', 'resources/read'])
90
+ /**
91
+ * Cache hints for cacheable modern results (spec: server/utilities/caching).
92
+ * The tool/resource catalogue is static for the process lifetime, so it is safe
93
+ * to cache publicly; ledger reads are private and stale immediately.
94
+ */
95
+ export const MODERN_CACHE_HINTS = Object.freeze({
96
+ discover: Object.freeze({ ttlMs: 300000, cacheScope: 'public' }),
97
+ toolsList: Object.freeze({ ttlMs: 300000, cacheScope: 'public' }),
98
+ resourcesList: Object.freeze({ ttlMs: 300000, cacheScope: 'public' }),
99
+ resourcesRead: Object.freeze({ ttlMs: 0, cacheScope: 'private' }),
100
+ })
101
+ /** ADVISERS_MCP_MODERN values that disable the modern era (default: enabled). */
102
+ const MODERN_OFF_VALUES = Object.freeze(['off', '0', 'false', 'no', 'disabled'])
103
+ /** True unless ADVISERS_MCP_MODERN explicitly disables the modern era. */
104
+ export function resolveModernEnabled(env = process.env) {
105
+ const raw = env?.ADVISERS_MCP_MODERN
106
+ if (raw === undefined || raw === null) return true
107
+ return !MODERN_OFF_VALUES.includes(String(raw).trim().toLowerCase())
108
+ }
109
+ /**
110
+ * Modern per-request metadata, or null for a legacy request. `initialize` is
111
+ * never modern (the handshake IS the legacy-era discriminator), and a request
112
+ * with no modern `_meta` key stays on the legacy path even when `_meta` exists
113
+ * for another reason (e.g. `progressToken`) — era is never guessed.
114
+ */
115
+ function modernRequestMeta(params) {
116
+ if (!params || typeof params !== 'object' || Array.isArray(params)) return null
117
+ const meta = params._meta
118
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta)) return null
119
+ if (!Object.prototype.hasOwnProperty.call(meta, META_PROTOCOL_VERSION)
120
+ && !Object.prototype.hasOwnProperty.call(meta, META_CLIENT_CAPABILITIES)) return null
121
+ return meta
122
+ }
59
123
  export const SERVER_NAME = 'advisers'
60
124
  /** Hard cap for one stdio JSON-RPC line (bytes). */
61
125
  export const MAX_LINE_BYTES = 1024 * 1024
@@ -481,10 +545,19 @@ export function readReceiptDirectory(dir) {
481
545
  * `advisers_who` (whose payload is full Commitment rows): `(ids: string[])
482
546
  * => Map<string, object> | object[]`. Only the capped <= 20 rows per
483
547
  * bucket are hydrated; omitted => the narrow who path is not used.
548
+ * @param {boolean} [options.modern] Dual-era (0.4.0): serve the stateless
549
+ * 2026-07-28 revision for requests that carry modern per-request
550
+ * `params._meta`. Defaults to `ADVISERS_MCP_MODERN` (enabled unless the
551
+ * env value is off/0/false/no/disabled); explicit `false` forces
552
+ * legacy-only, `true` forces dual-era even when the env disables it.
484
553
  * @returns {{protocolVersion: string, handle: Function, handleLine: Function, serve: Function, tools: Function, resources: Function}}
485
554
  */
486
- export function createMcpServer({ store, ledger, loadLedger, loadStore, loadCommitmentView, loadCommitmentRecords, version = '0.0.0', audit, readPack, now = () => new Date(), clearance = 0 } = {}) {
555
+ export function createMcpServer({ store, ledger, loadLedger, loadStore, loadCommitmentView, loadCommitmentRecords, version = '0.0.0', audit, readPack, now = () => new Date(), clearance = 0, modern } = {}) {
487
556
  const serverVersion = String(version ?? '0.0.0')
557
+ // 0.4.0 MCP modern: dual-era switch. The env var is read per factory call, so
558
+ // `ADVISERS_MCP_MODERN=off advisers mcp --stdio` is a one-restart rollback to
559
+ // the exact 0.3.2 surface without touching the CLI wiring.
560
+ const modernEnabled = modern === undefined ? resolveModernEnabled() : modern === true
488
561
  // Protocol version agreed by the last legacy `initialize` (advisory only:
489
562
  // the legacy method surface is identical for every supported revision).
490
563
  let negotiatedProtocolVersion = PROTOCOL_VERSION
@@ -1084,6 +1157,108 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, loadComm
1084
1157
  }
1085
1158
  }
1086
1159
 
1160
+ /* -------------------------- modern (2026-07-28) -------------------------- */
1161
+
1162
+ /** Modern result envelope: resultType is mandatory; the payload is untouched. */
1163
+ function modernResult(result, cache) {
1164
+ const envelope = {
1165
+ resultType: 'complete',
1166
+ ...result,
1167
+ _meta: { [META_SERVER_INFO]: { name: SERVER_NAME, version: serverVersion } },
1168
+ }
1169
+ if (cache) {
1170
+ envelope.ttlMs = cache.ttlMs
1171
+ envelope.cacheScope = cache.cacheScope
1172
+ }
1173
+ return envelope
1174
+ }
1175
+
1176
+ /** Modern JSON-RPC error response (errors never carry resultType). */
1177
+ function modernError(id, error) {
1178
+ const payload = { code: error.code, message: error.message }
1179
+ if (error.data !== undefined) payload.data = error.data
1180
+ return { jsonrpc: '2.0', id, error: payload }
1181
+ }
1182
+
1183
+ /**
1184
+ * Wrap a legacy result response in the modern envelope. The payload object
1185
+ * itself is spread unchanged, so tools/call content[0].text and resources/read
1186
+ * contents[0].text stay byte-identical to the legacy response.
1187
+ */
1188
+ function modernWrappedResult(legacyResponse, cache) {
1189
+ const result = legacyResponse?.result
1190
+ if (!result || typeof result !== 'object' || Array.isArray(result)) return legacyResponse
1191
+ return { jsonrpc: '2.0', id: legacyResponse.id, result: modernResult(result, cache) }
1192
+ }
1193
+
1194
+ /**
1195
+ * Validate the required per-request modern `_meta` fields. Missing or
1196
+ * ill-typed metadata is a malformed request (-32602); a well-formed but
1197
+ * unsupported version is -32022 with the supported list (client retries).
1198
+ */
1199
+ function modernMetaError(meta) {
1200
+ const requested = meta[META_PROTOCOL_VERSION]
1201
+ if (typeof requested !== 'string' || !requested.trim()) {
1202
+ return { code: -32602, message: 'invalid params: _meta field ' + META_PROTOCOL_VERSION + ' must be a string' }
1203
+ }
1204
+ const version = requested.trim()
1205
+ if (!SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(version)) {
1206
+ return { code: -32022, message: 'Unsupported protocol version', data: { supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], requested: version } }
1207
+ }
1208
+ const capabilities = meta[META_CLIENT_CAPABILITIES]
1209
+ if (capabilities === undefined || capabilities === null || typeof capabilities !== 'object' || Array.isArray(capabilities)) {
1210
+ return { code: -32602, message: 'invalid params: _meta field ' + META_CLIENT_CAPABILITIES + ' must be an object' }
1211
+ }
1212
+ return null
1213
+ }
1214
+
1215
+ /** This server returns a single static page; any client cursor is invalid. */
1216
+ function assertNoModernCursor(params) {
1217
+ if (Object.prototype.hasOwnProperty.call(params, 'cursor')) throw invalidParams('invalid cursor')
1218
+ }
1219
+
1220
+ /**
1221
+ * Stateless modern dispatcher (strict allowlist). Methods that only exist in
1222
+ * the legacy lifecycle (initialize/ping/...) answer -32601 here instead of
1223
+ * leaking into the legacy dispatcher; notifications are never answered.
1224
+ */
1225
+ async function handleModernRequest(hasId, id, method, params, meta) {
1226
+ if (!hasId) return null
1227
+ const metaError = modernMetaError(meta)
1228
+ if (metaError) return modernError(id, metaError)
1229
+ if (method.startsWith('notifications/')) return null
1230
+ if (!MODERN_METHODS.includes(method)) return rpcError(id, -32601, 'unknown method')
1231
+ try {
1232
+ if (method === 'server/discover') {
1233
+ return reply(id, modernResult({
1234
+ supportedVersions: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS],
1235
+ capabilities: { tools: { listChanged: false }, resources: { listChanged: false } },
1236
+ }, MODERN_CACHE_HINTS.discover))
1237
+ }
1238
+ if (method === 'tools/list') {
1239
+ assertNoModernCursor(params)
1240
+ return reply(id, modernResult({ tools: toolsList() }, MODERN_CACHE_HINTS.toolsList))
1241
+ }
1242
+ if (method === 'resources/list') {
1243
+ assertNoModernCursor(params)
1244
+ return reply(id, modernResult({ resources: RESOURCE_DEFINITIONS.map((entry) => ({ ...entry })) }, MODERN_CACHE_HINTS.resourcesList))
1245
+ }
1246
+ if (method === 'tools/call') {
1247
+ return modernWrappedResult(await handleToolsCall(id, params))
1248
+ }
1249
+ // resources/read: modern uses -32602 for an unknown resource (legacy keeps
1250
+ // -32002 for pre-0.4 clients); ledger reads are private and immediately stale.
1251
+ const legacyResponse = await handleResourcesRead(id, params)
1252
+ if (legacyResponse?.error) {
1253
+ return legacyResponse.error.code === -32002 ? rpcError(id, -32602, 'resource not found') : legacyResponse
1254
+ }
1255
+ return modernWrappedResult(legacyResponse, MODERN_CACHE_HINTS.resourcesRead)
1256
+ } catch (error) {
1257
+ if (error instanceof RpcError) return rpcError(id, error.code, error.message)
1258
+ return rpcError(id, -32603, 'internal error')
1259
+ }
1260
+ }
1261
+
1087
1262
  /* ------------------------------ dispatcher ------------------------------ */
1088
1263
 
1089
1264
  function reply(id, result) {
@@ -1106,9 +1281,10 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, loadComm
1106
1281
  * Legacy `initialize` result. 0.3.0 P0-T3: echo the client's version when
1107
1282
  * this server implements that legacy revision (2024-11-05 / 2025-06-18 /
1108
1283
  * 2025-11-25); a missing or unknown version keeps the 2024-11-05 default so
1109
- * pre-0.3 clients observe exactly the old behaviour. 2026-07-28 modern is
1110
- * not advertised on purpose (it needs server/discover and stateless
1111
- * per-request `_meta`; see docs/MCP.md).
1284
+ * pre-0.3 clients observe exactly the old behaviour. 2026-07-28 is never
1285
+ * negotiated here: the modern revision is stateless and advertises itself
1286
+ * through `server/discover`, so a modern client probes that method instead of
1287
+ * calling initialize (dual-era; see docs/MCP.md).
1112
1288
  */
1113
1289
  function initializeResult(requestedVersion) {
1114
1290
  const requested = typeof requestedVersion === 'string' ? requestedVersion.trim() : ''
@@ -1216,6 +1392,16 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, loadComm
1216
1392
  }
1217
1393
  const method = message.method
1218
1394
 
1395
+ // 0.4.0 dual-era: a request carrying the modern per-request `_meta` is
1396
+ // served by the stateless modern path. `initialize` is never modern (the
1397
+ // handshake is the legacy discriminator), and when ADVISERS_MCP_MODERN=off
1398
+ // no request takes this branch, so the legacy dispatcher below is byte-for-
1399
+ // byte the pre-0.4 surface.
1400
+ if (modernEnabled && method !== 'initialize') {
1401
+ const modernMeta = modernRequestMeta(message.params)
1402
+ if (modernMeta) return handleModernRequest(hasId, id, method, message.params, modernMeta)
1403
+ }
1404
+
1219
1405
  try {
1220
1406
  if (method === 'initialize') {
1221
1407
  const params = paramsObject(message.params)
package/lib/notify.js CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import { existsSync } from 'node:fs'
11
11
  import { spawn } from 'node:child_process'
12
+ import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto'
12
13
  import { localDay } from './remind.js'
13
14
  // 0.3.0 Wave 3 (docs/TUI.md §4): webhook/notifier failure detail is remote text
14
15
  // and reaches stderr through bin's `webhook 未发送:` line. Sanitise at the library
@@ -78,6 +79,217 @@ export function isWebhookConfigured(env = process.env) {
78
79
  return String(env?.[WEBHOOK_ENV] ?? '').trim() !== ''
79
80
  }
80
81
 
82
+ /** Env var holding the Standard Webhooks signing secret (`whsec_<base64>`). */
83
+ export const WEBHOOK_SECRET_ENV = 'ADVISERS_NOTIFY_WEBHOOK_SECRET'
84
+ /** Standard Webhooks signature version this adapter emits. */
85
+ export const WEBHOOK_SIGNATURE_VERSION = 'v1'
86
+ /** Replay window: |now - webhook-timestamp| must be <= this many seconds. */
87
+ export const WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = 300
88
+ export const WEBHOOK_ID_HEADER = 'webhook-id'
89
+ export const WEBHOOK_TIMESTAMP_HEADER = 'webhook-timestamp'
90
+ export const WEBHOOK_SIGNATURE_HEADER = 'webhook-signature'
91
+
92
+ function toWebhookBody(body) {
93
+ if (typeof body === 'string') return Buffer.from(body, 'utf8')
94
+ if (Buffer.isBuffer(body)) return body
95
+ if (body instanceof Uint8Array) return Buffer.from(body.buffer, body.byteOffset, body.byteLength)
96
+ throw new TypeError('webhook body must be a string or Buffer')
97
+ }
98
+
99
+ function normalizeWebhookId(id) {
100
+ const text = typeof id === 'string' ? id.trim() : String(id ?? '').trim()
101
+ if (!text) throw new TypeError('webhook id must not be empty')
102
+ if (/[\r\n\0]/.test(text)) throw new TypeError('webhook id must be single-line')
103
+ return text
104
+ }
105
+
106
+ function normalizeWebhookTimestamp(timestamp) {
107
+ const value = typeof timestamp === 'string' ? Number(timestamp.trim()) : timestamp
108
+ if (!Number.isSafeInteger(value) || value < 0) throw new TypeError('webhook timestamp must be integer unix seconds')
109
+ return value
110
+ }
111
+
112
+ function resolveNowMs(now) {
113
+ if (now === undefined || now === null) return Date.now()
114
+ const date = now instanceof Date ? now : new Date(now)
115
+ const ms = date.getTime()
116
+ if (!Number.isFinite(ms)) throw new RangeError('invalid webhook now: ' + String(now))
117
+ return ms
118
+ }
119
+
120
+ function headerValue(headers, name) {
121
+ if (!headers || typeof headers !== 'object') return undefined
122
+ if (typeof headers.get === 'function') {
123
+ const value = headers.get(name)
124
+ return value === undefined || value === null ? undefined : String(value)
125
+ }
126
+ if (headers instanceof Map) {
127
+ for (const [key, value] of headers) if (String(key).toLowerCase() === name) return value === undefined || value === null ? undefined : String(value)
128
+ return undefined
129
+ }
130
+ for (const key of Object.keys(headers)) {
131
+ if (key.toLowerCase() !== name) continue
132
+ const value = headers[key]
133
+ if (Array.isArray(value)) return value.length ? String(value[0]) : undefined
134
+ return value === undefined || value === null ? undefined : String(value)
135
+ }
136
+ return undefined
137
+ }
138
+
139
+ /**
140
+ * Decode a Standard Webhooks secret. `whsec_<base64>` yields the decoded key
141
+ * bytes; any other non-empty string is used as UTF-8 key material (convenience
142
+ * for self-hosted receivers). Returns null for empty/invalid input — never
143
+ * throws and never logs the value.
144
+ *
145
+ * @param {string|null|undefined} secret
146
+ * @returns {Buffer|null}
147
+ */
148
+ export function parseWebhookSecret(secret) {
149
+ if (typeof secret !== 'string') return null
150
+ const text = secret.trim()
151
+ if (!text) return null
152
+ if (!text.startsWith('whsec_')) return Buffer.from(text, 'utf8')
153
+ const encoded = text.slice('whsec_'.length).trim()
154
+ if (!encoded) return null
155
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return null
156
+ const decoded = Buffer.from(encoded, 'base64')
157
+ if (!decoded.length) return null
158
+ if (decoded.toString('base64').replace(/=+$/, '') !== encoded.replace(/=+$/, '')) return null
159
+ return decoded
160
+ }
161
+
162
+ /** True when the configured webhook would be signed (a valid secret exists). */
163
+ export function isWebhookSigningConfigured(env = process.env) {
164
+ return parseWebhookSecret(env?.[WEBHOOK_SECRET_ENV]) !== null
165
+ }
166
+
167
+ function signWithKey(key, { id, timestamp, body }) {
168
+ const messageId = normalizeWebhookId(id)
169
+ const seconds = normalizeWebhookTimestamp(timestamp)
170
+ const payload = toWebhookBody(body)
171
+ const signedContent = Buffer.concat([Buffer.from(messageId + '.' + seconds + '.', 'utf8'), payload])
172
+ const digest = createHmac('sha256', key).update(signedContent).digest('base64')
173
+ return WEBHOOK_SIGNATURE_VERSION + ',' + digest
174
+ }
175
+
176
+ /**
177
+ * `webhook-signature` header value: `v1,base64(HMAC-SHA256(secret, id.timestamp.body))`.
178
+ * Pure and deterministic; throws TypeError on an invalid secret/id/timestamp.
179
+ *
180
+ * @param {string} secret
181
+ * @param {{id: string, timestamp: number|string, body: string|Buffer}} options
182
+ * @returns {string}
183
+ */
184
+ export function signWebhook(secret, options = {}) {
185
+ const key = parseWebhookSecret(secret)
186
+ if (!key) throw new TypeError('invalid webhook secret')
187
+ return signWithKey(key, options ?? {})
188
+ }
189
+
190
+ /**
191
+ * The three Standard Webhooks request headers. `timestamp` defaults to the
192
+ * injected `now` (or the clock); `id` defaults to a random UUID.
193
+ *
194
+ * @param {{secret: string, id?: string, timestamp?: number|string,
195
+ * body: string|Buffer, now?: Date|string|number}} options
196
+ * @returns {Record<string, string>}
197
+ */
198
+ export function buildWebhookHeaders({ secret, id, timestamp, body, now } = {}) {
199
+ const key = parseWebhookSecret(secret)
200
+ if (!key) throw new TypeError('invalid webhook secret')
201
+ const messageId = id === undefined ? randomUUID() : normalizeWebhookId(id)
202
+ const seconds = timestamp === undefined ? Math.floor(resolveNowMs(now) / 1000) : normalizeWebhookTimestamp(timestamp)
203
+ return {
204
+ [WEBHOOK_ID_HEADER]: messageId,
205
+ [WEBHOOK_TIMESTAMP_HEADER]: String(seconds),
206
+ [WEBHOOK_SIGNATURE_HEADER]: signWithKey(key, { id: messageId, timestamp: seconds, body }),
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Stateless receiver-side verifier for Standard Webhooks deliveries.
212
+ *
213
+ * Checks header presence, the +/- `toleranceSeconds` timestamp window and the
214
+ * HMAC in constant time. Returns structured results (never throws for a bad
215
+ * delivery):
216
+ *
217
+ * { valid: true, id, timestamp, version }
218
+ * { valid: false, reason: 'missing-header'|'invalid-id'|'invalid-timestamp'|
219
+ * 'timestamp-out-of-window'|'invalid-signature'|'invalid-secret', ... }
220
+ *
221
+ * `webhook-id` is the idempotency key: pair this with
222
+ * {@link createWebhookReplayGuard} to reject replays inside the window.
223
+ */
224
+ export function verifyWebhookSignature({ secret, headers, body, now, toleranceSeconds = WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS } = {}) {
225
+ const key = parseWebhookSecret(secret)
226
+ if (!key) return { valid: false, reason: 'invalid-secret' }
227
+ const id = headerValue(headers, WEBHOOK_ID_HEADER)
228
+ const timestampHeader = headerValue(headers, WEBHOOK_TIMESTAMP_HEADER)
229
+ const signatureHeader = headerValue(headers, WEBHOOK_SIGNATURE_HEADER)
230
+ const missing = []
231
+ if (!id) missing.push(WEBHOOK_ID_HEADER)
232
+ if (!timestampHeader) missing.push(WEBHOOK_TIMESTAMP_HEADER)
233
+ if (!signatureHeader) missing.push(WEBHOOK_SIGNATURE_HEADER)
234
+ if (missing.length) return { valid: false, reason: 'missing-header', missing }
235
+ if (/[\r\n\0]/.test(id)) return { valid: false, reason: 'invalid-id' }
236
+ if (!/^\d+$/.test(timestampHeader.trim())) return { valid: false, reason: 'invalid-timestamp' }
237
+ const seconds = Number(timestampHeader.trim())
238
+ if (!Number.isSafeInteger(seconds)) return { valid: false, reason: 'invalid-timestamp' }
239
+ if (!Number.isInteger(toleranceSeconds) || toleranceSeconds < 0) throw new RangeError('toleranceSeconds must be a non-negative integer')
240
+ const nowSeconds = Math.floor(resolveNowMs(now) / 1000)
241
+ if (Math.abs(nowSeconds - seconds) > toleranceSeconds) return { valid: false, reason: 'timestamp-out-of-window', timestamp: seconds }
242
+ const payload = toWebhookBody(body)
243
+ const signedContent = Buffer.concat([Buffer.from(id + '.' + seconds + '.', 'utf8'), payload])
244
+ const expected = createHmac('sha256', key).update(signedContent).digest()
245
+ for (const candidate of signatureHeader.split(/\s+/).filter(Boolean)) {
246
+ const separator = candidate.indexOf(',')
247
+ if (separator <= 0) continue
248
+ if (candidate.slice(0, separator) !== WEBHOOK_SIGNATURE_VERSION) continue
249
+ const provided = Buffer.from(candidate.slice(separator + 1), 'base64')
250
+ if (provided.length !== expected.length) continue
251
+ if (timingSafeEqual(provided, expected)) return { valid: true, id, timestamp: seconds, version: WEBHOOK_SIGNATURE_VERSION }
252
+ }
253
+ return { valid: false, reason: 'invalid-signature' }
254
+ }
255
+
256
+ /**
257
+ * In-memory idempotency cache for receivers: rejects a `webhook-id` seen before
258
+ * (replay), a timestamp outside the +/- tolerance window, and stale entries are
259
+ * evicted automatically. `verify()` composes the signature check with the replay
260
+ * check; `check()` only inspects id/timestamp.
261
+ *
262
+ * The cache is deliberately process-local and bounded: it is a convenience for
263
+ * the documented verifier snippet, not a durable outbox.
264
+ */
265
+ export function createWebhookReplayGuard({ toleranceSeconds = WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS, maxEntries = 1000 } = {}) {
266
+ if (!Number.isInteger(toleranceSeconds) || toleranceSeconds < 0) throw new RangeError('toleranceSeconds must be a non-negative integer')
267
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) throw new RangeError('maxEntries must be a positive integer')
268
+ const seen = new Map()
269
+ function prune(nowSeconds) {
270
+ for (const [id, timestamp] of seen) if (nowSeconds - timestamp > toleranceSeconds) seen.delete(id)
271
+ while (seen.size > maxEntries) { const oldest = seen.keys().next().value; seen.delete(oldest) }
272
+ }
273
+ function check({ id, timestamp, now } = {}) {
274
+ const messageId = normalizeWebhookId(id)
275
+ const seconds = normalizeWebhookTimestamp(timestamp)
276
+ const nowSeconds = Math.floor(resolveNowMs(now) / 1000)
277
+ if (Math.abs(nowSeconds - seconds) > toleranceSeconds) return { accepted: false, reason: 'timestamp-out-of-window' }
278
+ prune(nowSeconds)
279
+ if (seen.has(messageId)) return { accepted: false, reason: 'replay' }
280
+ seen.set(messageId, seconds)
281
+ return { accepted: true }
282
+ }
283
+ function verify({ secret, headers, body, now } = {}) {
284
+ const result = verifyWebhookSignature({ secret, headers, body, now, toleranceSeconds })
285
+ if (!result.valid) return result
286
+ const replay = check({ id: result.id, timestamp: result.timestamp, now })
287
+ if (!replay.accepted) return { valid: false, reason: replay.reason }
288
+ return result
289
+ }
290
+ return { check, verify, size: () => seen.size }
291
+ }
292
+
81
293
  /**
82
294
  * Reduce due reminders to the only data allowed to leave the machine: a count,
83
295
  * per-level counts and the affected local dates. Titles, creditors, actions,
@@ -131,9 +343,20 @@ function truncateDetail(value, limit = 200) {
131
343
  * function never throws for network/config failures; it returns a structured
132
344
  * result so the caller can fall back to the local log:
133
345
  *
134
- * { sent: true, channel: 'webhook', configured: true, status, payload }
346
+ * { sent: true, channel: 'webhook', configured: true, status, payload,
347
+ * signing: 'standard-webhooks'|'none', warning?: 'missing-secret',
348
+ * webhookId?, webhookTimestamp? }
135
349
  * { sent: false, channel: 'webhook', configured: false, reason: 'not-configured' }
136
- * { sent: false, channel: 'webhook', configured: true, error: 'network'|'timeout'|'http'|'invalid-url'|'unsupported-protocol', status?, detail? }
350
+ * { sent: false, channel: 'webhook', configured: true, error: 'network'|'timeout'|'http'|
351
+ * 'invalid-url'|'unsupported-protocol'|'invalid-secret'|'invalid-options'|'fetch-unavailable',
352
+ * status?, detail?, signing? }
353
+ *
354
+ * Proactive 0.4 adds Standard Webhooks headers (`webhook-id`/`webhook-timestamp`/
355
+ * `webhook-signature`) when `ADVISERS_NOTIFY_WEBHOOK_SECRET` (or `options.secret`)
356
+ * is present; the JSON payload itself is byte-identical to 0.3.2. A configured
357
+ * webhook without a secret still delivers unsigned (`signing:'none'`,
358
+ * `warning:'missing-secret'`) for backward compatibility; an invalid secret is a
359
+ * structured `invalid-secret` failure and nothing is sent.
137
360
  */
138
361
  export async function sendWebhookNotification(reminders, options = {}) {
139
362
  const opts = options ?? {}
@@ -151,15 +374,48 @@ export async function sendWebhookNotification(reminders, options = {}) {
151
374
  }
152
375
  const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_WEBHOOK_TIMEOUT_MS
153
376
  const signal = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(timeoutMs) : undefined
377
+ // The payload bytes are unchanged from 0.3.2: the signature covers exactly the
378
+ // body that goes over the wire, and only request headers are added.
379
+ const body = JSON.stringify(summary)
380
+ const configuredSecret = opts.secret === undefined ? process.env?.[WEBHOOK_SECRET_ENV] : opts.secret
381
+ let signing = 'none'
382
+ let warning
383
+ let webhookId
384
+ let webhookTimestamp
385
+ let requestHeaders = { 'content-type': 'application/json', 'user-agent': 'advisers-webhook/1' }
386
+ if (configuredSecret !== undefined && configuredSecret !== null && String(configuredSecret).trim() !== '') {
387
+ const key = parseWebhookSecret(configuredSecret)
388
+ if (!key) return { sent: false, channel: 'webhook', configured: true, error: 'invalid-secret' }
389
+ try {
390
+ const id = opts.id === undefined ? randomUUID() : normalizeWebhookId(opts.id)
391
+ const seconds = opts.timestamp === undefined ? Math.floor(resolveNowMs(opts.now) / 1000) : normalizeWebhookTimestamp(opts.timestamp)
392
+ requestHeaders = {
393
+ ...requestHeaders,
394
+ [WEBHOOK_ID_HEADER]: id,
395
+ [WEBHOOK_TIMESTAMP_HEADER]: String(seconds),
396
+ [WEBHOOK_SIGNATURE_HEADER]: signWithKey(key, { id, timestamp: seconds, body }),
397
+ }
398
+ webhookId = id
399
+ webhookTimestamp = seconds
400
+ signing = 'standard-webhooks'
401
+ } catch (error) {
402
+ return { sent: false, channel: 'webhook', configured: true, error: 'invalid-options', detail: truncateDetail(error?.message ?? error) }
403
+ }
404
+ } else {
405
+ // Backward compatible: a configured webhook still delivers unsigned, but the
406
+ // result says so; the CLI prints one warning and status records signing=none.
407
+ warning = 'missing-secret'
408
+ }
409
+ const signingMeta = { signing, ...(warning ? { warning } : {}), ...(webhookId ? { webhookId, webhookTimestamp } : {}) }
154
410
  try {
155
411
  const response = await fetchImpl(target.url.href, {
156
412
  method: 'POST',
157
- headers: { 'content-type': 'application/json', 'user-agent': 'advisers-webhook/1' },
158
- body: JSON.stringify(summary),
413
+ headers: requestHeaders,
414
+ body,
159
415
  signal,
160
416
  })
161
417
  if (!response || typeof response !== 'object') {
162
- return { sent: false, channel: 'webhook', configured: true, error: 'network', detail: 'empty response' }
418
+ return { sent: false, channel: 'webhook', configured: true, error: 'network', detail: 'empty response', ...signingMeta }
163
419
  }
164
420
  if (!response.ok) {
165
421
  let detail
@@ -175,13 +431,14 @@ export async function sendWebhookNotification(reminders, options = {}) {
175
431
  error: 'http',
176
432
  status: response.status,
177
433
  ...(detail ? { detail } : {}),
434
+ ...signingMeta,
178
435
  }
179
436
  }
180
- return { sent: true, channel: 'webhook', configured: true, status: response.status, payload: summary }
437
+ return { sent: true, channel: 'webhook', configured: true, status: response.status, payload: summary, ...signingMeta }
181
438
  } catch (error) {
182
439
  const name = String(error?.name ?? '')
183
440
  if (name === 'TimeoutError' || name === 'AbortError') {
184
- return { sent: false, channel: 'webhook', configured: true, error: 'timeout', detail: `no response within ${timeoutMs}ms` }
441
+ return { sent: false, channel: 'webhook', configured: true, error: 'timeout', detail: `no response within ${timeoutMs}ms`, ...signingMeta }
185
442
  }
186
443
  return {
187
444
  sent: false,
@@ -189,6 +446,7 @@ export async function sendWebhookNotification(reminders, options = {}) {
189
446
  configured: true,
190
447
  error: 'network',
191
448
  detail: truncateDetail(error?.message ?? error),
449
+ ...signingMeta,
192
450
  }
193
451
  }
194
452
  }