advisers 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README-zh.md +13 -15
  2. package/README.md +32 -22
  3. package/THIRD-PARTY-NOTICES.md +1 -1
  4. package/bin/advisers.js +2769 -183
  5. package/index.js +1 -1
  6. package/lib/brief-archive.js +267 -0
  7. package/lib/client-pack.js +1016 -0
  8. package/lib/consent.js +390 -0
  9. package/lib/credentials.js +195 -0
  10. package/lib/customer-read.js +524 -0
  11. package/lib/error-codes.js +516 -7
  12. package/lib/evidence.js +928 -120
  13. package/lib/kb-extract.js +626 -0
  14. package/lib/kb-facts.js +429 -0
  15. package/lib/kb-pages.js +1084 -0
  16. package/lib/kb.js +1036 -0
  17. package/lib/ledger-read.js +109 -1
  18. package/lib/mail-errors.js +46 -0
  19. package/lib/mail-extract.js +351 -0
  20. package/lib/mail-imap.js +446 -0
  21. package/lib/mail-import.js +176 -0
  22. package/lib/mail-parse.js +223 -0
  23. package/lib/mail-store.js +731 -0
  24. package/lib/mail.js +506 -0
  25. package/lib/mcp-server.js +397 -11
  26. package/lib/notify.js +265 -7
  27. package/lib/policy/decision.js +315 -0
  28. package/lib/policy/egress.js +268 -0
  29. package/lib/policy/errors.js +71 -0
  30. package/lib/policy/index.js +99 -0
  31. package/lib/policy/rules.js +468 -0
  32. package/lib/policy/surfaces.js +141 -0
  33. package/lib/receipt-verify.js +283 -26
  34. package/lib/receivables.js +1653 -0
  35. package/lib/scheduler.js +453 -9
  36. package/lib/shell.js +1406 -0
  37. package/lib/source.js +98 -3
  38. package/lib/sqlite.js +501 -49
  39. package/lib/tos/index.js +2 -2
  40. package/lib/tos/manifest.json +6 -6
  41. package/lib/tos/privacy.zh-CN.md +33 -20
  42. package/lib/tos/safety.zh-CN.md +7 -6
  43. package/lib/tos/summary.zh-CN.md +3 -2
  44. package/lib/tos/terms.zh-CN.md +31 -16
  45. package/lib/tui/labels.js +1 -1
  46. package/lib/tui/render.js +1 -1
  47. package/lib/urgency.js +467 -0
  48. package/package.json +4 -4
package/lib/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
  }
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Decision tokens (0.4 grant-lite) + intent/result audit orchestration.
3
+ *
4
+ * authorize(action, facts) runs evaluate(); on allow it issues a one-shot token
5
+ * bound to an effectDigest (surface/action/path/recipient/subject/provider/
6
+ * dataClass/record kind+secrecy), writes an audit intent row, and returns the
7
+ * token. runWithDecision(token, effect, fn) consumes the token (allow + digest
8
+ * match + unused + unexpired), executes fn and writes the audit result row.
9
+ *
10
+ * Threat model: this catches "a code path forgot to call the gate" and "a
11
+ * decision for A is reused to execute B". It does NOT defend against a
12
+ * same-user process that can rewrite the source or read process memory;
13
+ * docs/SECURITY.md #8 stays the honest statement. The token is in-process only
14
+ * (a Map); 0.5 may add HMAC/TTL persistence. Decision tokens are not secrets.
15
+ */
16
+ import { randomUUID } from 'node:crypto'
17
+
18
+ import { POLICY_CODES, PolicyError, policyError } from './errors.js'
19
+ import { EFFECT_DIGEST_FIELDS, canonicalJson, effectDigestOf, evaluate } from './rules.js'
20
+
21
+ /** Default token lifetime (milliseconds). */
22
+ export const DECISION_TOKEN_TTL_MS = 60_000
23
+
24
+ const tokens = new Map()
25
+
26
+ function isPlainObject(value) {
27
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
28
+ }
29
+
30
+ function nowMs(now) {
31
+ if (now === undefined || now === null) return Date.now()
32
+ if (now instanceof Date) return now.getTime()
33
+ const value = typeof now === 'number' ? now : Date.parse(String(now))
34
+ if (!Number.isFinite(value)) throw new TypeError('authorize/consumeDecision now must be a Date, epoch ms or ISO string')
35
+ return value
36
+ }
37
+
38
+ function isoAt(ms) {
39
+ return new Date(ms).toISOString()
40
+ }
41
+
42
+ /** JSON-ready decision metadata without the token (safe to print/audit). */
43
+ export function decisionView(decision) {
44
+ if (!isPlainObject(decision)) return null
45
+ return {
46
+ surface: decision.surface,
47
+ action: decision.action,
48
+ dataClass: decision.dataClass,
49
+ decision: decision.decision,
50
+ code: decision.code ?? null,
51
+ policyCode: decision.policyCode ?? null,
52
+ ruleIds: Array.isArray(decision.ruleIds) ? [...decision.ruleIds] : [],
53
+ obligations: Array.isArray(decision.obligations) ? [...decision.obligations] : [],
54
+ reason: decision.reason,
55
+ effectDigest: decision.effectDigest,
56
+ }
57
+ }
58
+
59
+ function auditEvent(input) {
60
+ const event = {
61
+ at: input.at,
62
+ actor: input.actor || 'local',
63
+ surface: input.surface,
64
+ action: input.action,
65
+ policyAction: input.policyAction,
66
+ phase: input.phase,
67
+ decision: input.decision,
68
+ allowed: input.decision === 'allow',
69
+ }
70
+ for (const key of ['code', 'policyCode', 'reason', 'decisionId', 'effectDigest']) {
71
+ if (input[key] !== undefined && input[key] !== null && input[key] !== '') event[key] = input[key]
72
+ }
73
+ if (Array.isArray(input.ruleIds) && input.ruleIds.length) event.ruleIds = [...input.ruleIds]
74
+ if (input.ok !== undefined) event.ok = input.ok === true
75
+ return event
76
+ }
77
+
78
+ /**
79
+ * Write one audit row through a caller-supplied synchronous callback.
80
+ * Returns true on success; a throw or an explicit {ok:false} is a failure
81
+ * (fail closed). The callback never receives content: no quotes, paths,
82
+ * recipients or titles, only the metadata above.
83
+ */
84
+ function writeAudit(audit, event) {
85
+ if (typeof audit !== 'function') return false
86
+ let result
87
+ try {
88
+ result = audit(event)
89
+ } catch {
90
+ return false
91
+ }
92
+ if (result && typeof result.then === 'function') return false
93
+ if (isPlainObject(result) && result.ok === false) return false
94
+ return true
95
+ }
96
+
97
+ function tokenRecordOf(token) {
98
+ if (!isPlainObject(token)) return null
99
+ const decisionId = typeof token.decisionId === 'string' ? token.decisionId : ''
100
+ const effectDigest = typeof token.effectDigest === 'string' ? token.effectDigest : ''
101
+ if (!decisionId || !effectDigest) return null
102
+ return {
103
+ decisionId,
104
+ effectDigest,
105
+ surface: typeof token.surface === 'string' ? token.surface : '',
106
+ action: typeof token.action === 'string' ? token.action : '',
107
+ expiresAt: typeof token.expiresAt === 'string' ? token.expiresAt : '',
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Authorize one action for one set of facts.
113
+ *
114
+ * - deny/confirm: returns the evaluate() result plus {authorized:false,
115
+ * decisionId:null, token:null}; a deny/confirm audit row is attempted when a
116
+ * callback is supplied but its failure cannot change the refusal;
117
+ * - allow: writes the intent audit row before returning. If the action has the
118
+ * audit.intent obligation and the callback is missing/throws, the call is
119
+ * refused with E_POLICY_AUDIT_UNAVAILABLE and no token is issued.
120
+ *
121
+ * @param {string} action canonical policy action
122
+ * @param {object} facts see lib/policy/rules.js evaluate()
123
+ * @param {{now?: Date|number|string, ttlMs?: number, audit?: Function}} [options]
124
+ * @returns {object} decision + {authorized, decisionId, token, expiresAt, auditWritten}
125
+ */
126
+ export function authorize(action, facts, options = {}) {
127
+ if (typeof action !== 'string' || !action.trim()) throw new TypeError('authorize(action, facts) requires a non-empty action')
128
+ if (!isPlainObject(facts)) throw new TypeError('authorize(action, facts) requires a facts object')
129
+ if (!isPlainObject(options)) throw new TypeError('authorize options must be an object')
130
+ const at = nowMs(options.now)
131
+ const ttl = options.ttlMs === undefined || options.ttlMs === null ? DECISION_TOKEN_TTL_MS : Number(options.ttlMs)
132
+ if (!Number.isFinite(ttl) || ttl <= 0) throw new TypeError('authorize ttlMs must be a positive number of milliseconds')
133
+ const audit = options.audit
134
+ const decision = evaluate({ ...facts, action })
135
+ const base = { ...decision, authorized: false, decisionId: null, token: null, expiresAt: null, auditWritten: false }
136
+
137
+ if (decision.decision !== 'allow') {
138
+ const wrote = writeAudit(
139
+ audit,
140
+ auditEvent({
141
+ at: isoAt(at),
142
+ actor: facts.actor,
143
+ surface: decision.surface,
144
+ action: decision.action,
145
+ policyAction: action,
146
+ phase: 'decision',
147
+ decision: decision.decision,
148
+ code: decision.code,
149
+ policyCode: decision.policyCode,
150
+ reason: decision.reason,
151
+ ruleIds: decision.ruleIds,
152
+ }),
153
+ )
154
+ return { ...base, auditWritten: wrote }
155
+ }
156
+
157
+ const decisionId = 'dec_' + randomUUID()
158
+ const expiresAt = isoAt(at + ttl)
159
+ const token = { decisionId, effectDigest: decision.effectDigest, surface: decision.surface, action: decision.action, expiresAt }
160
+ const requiresIntent = Array.isArray(decision.obligations) && decision.obligations.includes('audit.intent')
161
+ if (requiresIntent) {
162
+ const wrote = writeAudit(
163
+ audit,
164
+ auditEvent({
165
+ at: isoAt(at),
166
+ actor: facts.actor,
167
+ surface: decision.surface,
168
+ action: decision.action,
169
+ policyAction: action,
170
+ phase: 'intent',
171
+ decision: 'allow',
172
+ decisionId,
173
+ effectDigest: decision.effectDigest,
174
+ ruleIds: decision.ruleIds,
175
+ }),
176
+ )
177
+ if (!wrote) {
178
+ return {
179
+ ...base,
180
+ decision: 'deny',
181
+ code: POLICY_CODES.POLICY_AUDIT_UNAVAILABLE.code,
182
+ policyCode: 'POLICY_AUDIT_UNAVAILABLE',
183
+ ruleIds: [...decision.ruleIds, 'R-P04-07'],
184
+ obligations: [],
185
+ reason: 'the intent audit could not be written; refusing the side effect',
186
+ }
187
+ }
188
+ }
189
+ tokens.set(decisionId, {
190
+ decisionId,
191
+ effectDigest: decision.effectDigest,
192
+ surface: decision.surface,
193
+ action: decision.action,
194
+ expiresAt: at + ttl,
195
+ used: false,
196
+ requiresAudit: requiresIntent,
197
+ createdAt: at,
198
+ })
199
+ return { ...base, authorized: true, decisionId, token, expiresAt, auditWritten: requiresIntent }
200
+ }
201
+
202
+ function assertToken(token) {
203
+ const record = tokenRecordOf(token)
204
+ if (!record) throw policyError('POLICY_TOKEN_INVALID', 'the decision token is malformed')
205
+ const stored = tokens.get(record.decisionId)
206
+ if (!stored) throw policyError('POLICY_TOKEN_UNKNOWN', 'the decision token was not issued by this process')
207
+ if (stored.used) throw policyError('POLICY_TOKEN_REPLAY', 'the decision token was already consumed')
208
+ if (record.effectDigest !== stored.effectDigest || record.surface !== stored.surface || record.action !== stored.action) {
209
+ throw policyError('POLICY_TOKEN_INVALID', 'the decision token fields were modified after issue')
210
+ }
211
+ return stored
212
+ }
213
+
214
+ /**
215
+ * Consume a one-shot decision token for the effect that is about to run.
216
+ * Throws PolicyError (E_POLICY_TOKEN_*) when the token is invalid, expired,
217
+ * already used, tampered with, or when the effect does not match the digest.
218
+ *
219
+ * @param {object} token token returned by authorize()
220
+ * @param {object} effect same effect metadata that was authorized
221
+ * @param {{now?: Date|number|string}} [options]
222
+ * @returns {{decisionId: string, effectDigest: string, surface: string, action: string}}
223
+ */
224
+ export function consumeDecision(token, effect, options = {}) {
225
+ const at = nowMs(options.now)
226
+ const stored = assertToken(token)
227
+ if (at > stored.expiresAt) throw policyError('POLICY_TOKEN_EXPIRED', 'the decision token expired before the effect was executed')
228
+ const digest = effectDigestOf(effect)
229
+ if (digest !== stored.effectDigest) {
230
+ throw policyError('POLICY_TOKEN_EFFECT_MISMATCH', 'the effect does not match the effect digest the decision was issued for')
231
+ }
232
+ stored.used = true
233
+ return {
234
+ decisionId: stored.decisionId,
235
+ effectDigest: stored.effectDigest,
236
+ surface: stored.surface,
237
+ action: stored.action,
238
+ auditRequired: stored.requiresAudit === true,
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Consume the token, execute fn, and write the result audit row.
244
+ *
245
+ * The intent row was written by authorize(); this writes exactly one result
246
+ * row with ok=<boolean> (and the error code when fn throws) and rethrows the
247
+ * original error. A result-audit failure after the effect throws
248
+ * E_POLICY_AUDIT_UNAVAILABLE with effectCompleted:true: callers must surface
249
+ * that loudly (the effect already happened and is not audited).
250
+ *
251
+ * @param {object} token from authorize()
252
+ * @param {object} effect effect metadata
253
+ * @param {Function} fn synchronous effect executor
254
+ * @param {{now?: Date|number|string, audit?: Function, actor?: string}} [options]
255
+ */
256
+ export function runWithDecision(token, effect, fn, options = {}) {
257
+ if (typeof fn !== 'function') throw new TypeError('runWithDecision(token, effect, fn) requires a function')
258
+ if (!isPlainObject(options)) throw new TypeError('runWithDecision options must be an object')
259
+ const at = nowMs(options.now)
260
+ const consumed = consumeDecision(token, effect, { now: at })
261
+ const audit = options.audit
262
+ let result
263
+ try {
264
+ result = fn()
265
+ } catch (error) {
266
+ writeAudit(
267
+ audit,
268
+ auditEvent({
269
+ at: isoAt(at),
270
+ actor: options.actor,
271
+ surface: consumed.surface,
272
+ action: consumed.action,
273
+ policyAction: consumed.action,
274
+ phase: 'result',
275
+ decision: 'allow',
276
+ decisionId: consumed.decisionId,
277
+ effectDigest: consumed.effectDigest,
278
+ ok: false,
279
+ code: typeof error?.code === 'string' ? error.code : 'E_POLICY_EFFECT_FAILED',
280
+ }),
281
+ )
282
+ throw error
283
+ }
284
+ const wrote = writeAudit(
285
+ audit,
286
+ auditEvent({
287
+ at: isoAt(at),
288
+ actor: options.actor,
289
+ surface: consumed.surface,
290
+ action: consumed.action,
291
+ policyAction: consumed.action,
292
+ phase: 'result',
293
+ decision: 'allow',
294
+ decisionId: consumed.decisionId,
295
+ effectDigest: consumed.effectDigest,
296
+ ok: true,
297
+ }),
298
+ )
299
+ if (consumed.auditRequired && !wrote) {
300
+ throw policyError('POLICY_AUDIT_UNAVAILABLE', 'the effect completed but its result audit could not be written', { effectCompleted: true, decisionId: consumed.decisionId })
301
+ }
302
+ return result
303
+ }
304
+
305
+ /** Drop every issued token (tests, long-lived processes after a failure). */
306
+ export function clearDecisionTokens() {
307
+ tokens.clear()
308
+ }
309
+
310
+ /** Number of unexpired/unused tokens currently tracked (diagnostics). */
311
+ export function decisionTokenCount() {
312
+ return tokens.size
313
+ }
314
+
315
+ export { PolicyError, effectDigestOf, canonicalJson, EFFECT_DIGEST_FIELDS }