@njuptlzf/agent-chat-server 0.1.2 → 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.
Files changed (65) hide show
  1. package/dist/audit.d.ts +54 -0
  2. package/dist/audit.js +133 -0
  3. package/dist/authz.d.ts +134 -0
  4. package/dist/authz.js +238 -0
  5. package/dist/events.d.ts +33 -0
  6. package/dist/events.js +169 -0
  7. package/dist/index.d.ts +16 -0
  8. package/dist/index.js +4 -0
  9. package/dist/main.d.ts +1 -0
  10. package/dist/main.js +126 -0
  11. package/dist/manifest.d.ts +147 -0
  12. package/dist/manifest.js +491 -0
  13. package/dist/mcp-config.d.ts +87 -0
  14. package/dist/mcp-config.js +353 -0
  15. package/dist/model-config.d.ts +123 -0
  16. package/dist/model-config.js +371 -0
  17. package/dist/model-failover.d.ts +42 -0
  18. package/dist/model-failover.js +82 -0
  19. package/dist/models-api.d.ts +98 -0
  20. package/dist/models-api.js +326 -0
  21. package/dist/persona-config.d.ts +112 -0
  22. package/dist/persona-config.js +368 -0
  23. package/dist/persona-trial.d.ts +50 -0
  24. package/dist/persona-trial.js +77 -0
  25. package/dist/product-routes.d.ts +35 -0
  26. package/dist/product-routes.js +92 -0
  27. package/dist/server.d.ts +162 -0
  28. package/dist/server.js +2572 -0
  29. package/dist/session.d.ts +218 -0
  30. package/dist/session.js +545 -0
  31. package/dist/sqlite-stores.d.ts +173 -0
  32. package/dist/sqlite-stores.js +921 -0
  33. package/dist/stores.d.ts +506 -0
  34. package/dist/stores.js +614 -0
  35. package/dist/testing.d.ts +42 -0
  36. package/dist/testing.js +47 -0
  37. package/dist/trial-grant.d.ts +40 -0
  38. package/dist/trial-grant.js +24 -0
  39. package/dist/usage-report.d.ts +23 -0
  40. package/dist/usage-report.js +68 -0
  41. package/dist/util.d.ts +3 -0
  42. package/dist/util.js +5 -0
  43. package/package.json +15 -9
  44. package/scripts/agentchat-integrate.mjs +607 -607
  45. package/src/audit.ts +169 -169
  46. package/src/authz.ts +307 -307
  47. package/src/events.ts +206 -206
  48. package/src/index.ts +26 -26
  49. package/src/main.ts +142 -142
  50. package/src/manifest.ts +562 -562
  51. package/src/mcp-config.ts +385 -385
  52. package/src/model-config.ts +424 -424
  53. package/src/model-failover.ts +95 -95
  54. package/src/models-api.ts +360 -360
  55. package/src/persona-config.ts +436 -436
  56. package/src/persona-trial.ts +121 -121
  57. package/src/product-routes.ts +102 -102
  58. package/src/server.ts +2647 -2647
  59. package/src/session.ts +688 -688
  60. package/src/sqlite-stores.ts +1040 -1040
  61. package/src/stores.ts +899 -899
  62. package/src/testing.ts +80 -80
  63. package/src/trial-grant.ts +62 -62
  64. package/src/usage-report.ts +86 -86
  65. package/src/util.ts +6 -6
package/src/audit.ts CHANGED
@@ -1,169 +1,169 @@
1
- import { createHash } from "node:crypto";
2
-
3
- /**
4
- * 审计链纯函数层。
5
- * Memory 与 Sqlite 两实现共用:规范化 JSON、逐行摘要、链校验、敏感键守卫、
6
- * purge 段聚合。这里只有算法,没有 I/O——存储层负责把行喂进来。
7
- */
8
-
9
- /** 模型切换未落地,写点先引用这个常量留缝。 */
10
- export const MODEL_SWITCH = "model.switch";
11
-
12
- /** 创世行的 prev_hash(起点锚定后不要求链首=创世,首行 prev 存这个值是默认姿势,不参与校验)。 */
13
- export const GENESIS_HASH = "0".repeat(64);
14
-
15
- /** 参与摘要的字段域:id 不入摘要;at/actor/roles/action/target/result/reason/meta。 */
16
- export interface ChainRow {
17
- id: number;
18
- at: string;
19
- actor: string;
20
- roles: string[];
21
- action: string;
22
- target: string | null;
23
- result: string;
24
- reason: string | null;
25
- meta: Record<string, unknown>;
26
- prevHash: string;
27
- hash: string;
28
- }
29
-
30
- /** 递归按「键字典序 + 紧凑分隔符」规范化;数组保持序。同义不同形(键序/空白)→ 同串。 */
31
- export function canonicalize(value: unknown): string {
32
- return JSON.stringify(normalize(value));
33
- }
34
-
35
- function normalize(v: unknown): unknown {
36
- if (Array.isArray(v)) return v.map(normalize);
37
- if (v !== null && typeof v === "object") {
38
- return Object.fromEntries(
39
- Object.entries(v as Record<string, unknown>)
40
- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
41
- .map(([k, x]) => [k, normalize(x)]),
42
- );
43
- }
44
- return v;
45
- }
46
-
47
- /** hash = sha256_hex(prev_hash ‖ 规范化 payload)。payload 键序由 canonicalize 保证。 */
48
- export function rowHash(prevHash: string, row: Omit<ChainRow, "id" | "prevHash" | "hash">): string {
49
- const payload = canonicalize({
50
- at: row.at,
51
- actor: row.actor,
52
- roles: row.roles,
53
- action: row.action,
54
- target: row.target,
55
- result: row.result,
56
- reason: row.reason,
57
- meta: row.meta,
58
- });
59
- return createHash("sha256").update(prevHash + payload).digest("hex");
60
- }
61
-
62
- /**
63
- * 红线②守卫:meta 落库前递归查敏感键名。命中抛错 + stderr——
64
- * 写审计的代码有 bug 也不该把 key/token 带进表里。
65
- *
66
- * 语义=词集而非子串(实现时对方案字面正则 /key|token|…/i 的修正,review 时可推翻):
67
- * 子串会误杀 写点白名单里的 `tokens`(token 计数,非凭据),且 `cost_per_token`
68
- * 一类合法键也躲不过;词集按 camel/snake/kebab 拆词后整词匹配,
69
- * `api_key/refreshToken/COOKIE_ID` 照杀,`tokens/monkey` 放行。
70
- */
71
- const SENSITIVE_WORDS = /^(key|keys|token|secret|secrets|credential|credentials|authorization|cookie|cookies|apikey|accesskey|accesstoken|authtoken|refreshtoken|bearer)$/i;
72
-
73
- function sensitiveHit(key: string): boolean {
74
- return key
75
- .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
76
- .toLowerCase()
77
- .split(/[^a-z0-9]+/)
78
- .some((w) => SENSITIVE_WORDS.test(w));
79
- }
80
-
81
- export function assertNoSensitiveKeys(meta: Record<string, unknown>, path = "meta"): void {
82
- for (const [k, v] of Object.entries(meta)) {
83
- if (sensitiveHit(k)) {
84
- const where = `${path}.${k}`;
85
- console.error(`audit: rejected sensitive meta key ${where}`);
86
- throw new Error(`audit meta rejected: sensitive key ${where}`);
87
- }
88
- if (v !== null && typeof v === "object") {
89
- if (Array.isArray(v)) {
90
- v.forEach((x, i) => x !== null && typeof x === "object" && assertNoSensitiveKeys(x as Record<string, unknown>, `${path}.${k}[${i}]`));
91
- } else {
92
- assertNoSensitiveKeys(v as Record<string, unknown>, `${path}.${k}`);
93
- }
94
- }
95
- }
96
- }
97
-
98
- /** purge 段白名单(5B):一段连续被删 id + 段尾行存储 hash(删前读取)。 */
99
- export interface PurgeSegment {
100
- from_id: number;
101
- to_id: number;
102
- last_hash: string;
103
- }
104
-
105
- /** 把待删行(按 id 升序)聚成连续段。 */
106
- export function segmentsFrom(rows: Array<{ id: number; hash: string }>): PurgeSegment[] {
107
- const segs: PurgeSegment[] = [];
108
- for (const r of rows) {
109
- const last = segs[segs.length - 1];
110
- if (last && r.id === last.to_id + 1) last.to_id = r.id;
111
- else segs.push({ from_id: r.id, to_id: r.id, last_hash: r.hash });
112
- segs[segs.length - 1].last_hash = r.hash; // 段尾 hash 随延伸滚动
113
- }
114
- return segs;
115
- }
116
-
117
- export interface VerifyResult {
118
- ok: boolean;
119
- rows: number;
120
- /** 起点锚定:校验从当前最老行起。空表 null。 */
121
- checkedFromId: number | null;
122
- /** 摘要不符(内容被改)或白名单段衔接核对不符。 */
123
- brokenAtId: number | null;
124
- /** 未经 purge 记录的 id 空洞——首个缺失行的 id(疑似恶意删行,等同断链报告)。 */
125
- gapAtId: number | null;
126
- }
127
-
128
- /**
129
- * 按 id 升序扫全表重算链(三条口径)。`rows` 须已按 id 升序——
130
- * 存储层负责排序,这里不重排(verify 是全表扫,顺序错误是装配 bug,不该被静默吞掉)。
131
- */
132
- export function verifyChain(rows: ChainRow[]): VerifyResult {
133
- const base: VerifyResult = { ok: true, rows: rows.length, checkedFromId: rows[0]?.id ?? null, brokenAtId: null, gapAtId: null };
134
- if (!rows.length) return base;
135
-
136
- // 白名单:ops.audit.purge 行的 meta.segments。篡改它自身会被逐行重算抓到(它在链内, 自我闭环)。
137
- const segments: PurgeSegment[] = [];
138
- for (const r of rows) {
139
- if (r.action !== "ops.audit.purge") continue;
140
- const segs = r.meta["segments"];
141
- if (!Array.isArray(segs)) continue;
142
- for (const s of segs) {
143
- if (s && typeof s === "object") {
144
- const { from_id, to_id, last_hash } = s as Record<string, unknown>;
145
- if (typeof from_id === "number" && typeof to_id === "number" && typeof last_hash === "string") {
146
- segments.push({ from_id, to_id, last_hash });
147
- }
148
- }
149
- }
150
- }
151
-
152
- let brokenAtId: number | null = null;
153
- let gapAtId: number | null = null;
154
- for (let i = 0; i < rows.length; i++) {
155
- const r = rows[i];
156
- const prev = i > 0 ? rows[i - 1] : null;
157
- if (prev && r.id !== prev.id + 1) {
158
- // 空洞:须被某段白名单「恰等区间」背书,且空洞后首存活行 prev_hash == 段 last_hash。
159
- const seg = segments.find((s) => s.from_id === prev.id + 1 && s.to_id === r.id - 1);
160
- if (!seg) gapAtId ??= prev.id + 1;
161
- else if (seg.last_hash !== r.prevHash) brokenAtId ??= r.id;
162
- } else if (prev && r.prevHash !== prev.hash) {
163
- brokenAtId ??= r.id; // 无空洞却断衔接:腰删未重连/前缀被换
164
- }
165
- if (rowHash(r.prevHash, r) !== r.hash) brokenAtId ??= r.id; // 首行不做创世要求,但本行内容照验
166
- if (brokenAtId !== null && gapAtId !== null) break;
167
- }
168
- return { ...base, ok: brokenAtId === null && gapAtId === null, brokenAtId, gapAtId };
169
- }
1
+ import { createHash } from "node:crypto";
2
+
3
+ /**
4
+ * 审计链纯函数层。
5
+ * Memory 与 Sqlite 两实现共用:规范化 JSON、逐行摘要、链校验、敏感键守卫、
6
+ * purge 段聚合。这里只有算法,没有 I/O——存储层负责把行喂进来。
7
+ */
8
+
9
+ /** 模型切换未落地,写点先引用这个常量留缝。 */
10
+ export const MODEL_SWITCH = "model.switch";
11
+
12
+ /** 创世行的 prev_hash(起点锚定后不要求链首=创世,首行 prev 存这个值是默认姿势,不参与校验)。 */
13
+ export const GENESIS_HASH = "0".repeat(64);
14
+
15
+ /** 参与摘要的字段域:id 不入摘要;at/actor/roles/action/target/result/reason/meta。 */
16
+ export interface ChainRow {
17
+ id: number;
18
+ at: string;
19
+ actor: string;
20
+ roles: string[];
21
+ action: string;
22
+ target: string | null;
23
+ result: string;
24
+ reason: string | null;
25
+ meta: Record<string, unknown>;
26
+ prevHash: string;
27
+ hash: string;
28
+ }
29
+
30
+ /** 递归按「键字典序 + 紧凑分隔符」规范化;数组保持序。同义不同形(键序/空白)→ 同串。 */
31
+ export function canonicalize(value: unknown): string {
32
+ return JSON.stringify(normalize(value));
33
+ }
34
+
35
+ function normalize(v: unknown): unknown {
36
+ if (Array.isArray(v)) return v.map(normalize);
37
+ if (v !== null && typeof v === "object") {
38
+ return Object.fromEntries(
39
+ Object.entries(v as Record<string, unknown>)
40
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
41
+ .map(([k, x]) => [k, normalize(x)]),
42
+ );
43
+ }
44
+ return v;
45
+ }
46
+
47
+ /** hash = sha256_hex(prev_hash ‖ 规范化 payload)。payload 键序由 canonicalize 保证。 */
48
+ export function rowHash(prevHash: string, row: Omit<ChainRow, "id" | "prevHash" | "hash">): string {
49
+ const payload = canonicalize({
50
+ at: row.at,
51
+ actor: row.actor,
52
+ roles: row.roles,
53
+ action: row.action,
54
+ target: row.target,
55
+ result: row.result,
56
+ reason: row.reason,
57
+ meta: row.meta,
58
+ });
59
+ return createHash("sha256").update(prevHash + payload).digest("hex");
60
+ }
61
+
62
+ /**
63
+ * 红线②守卫:meta 落库前递归查敏感键名。命中抛错 + stderr——
64
+ * 写审计的代码有 bug 也不该把 key/token 带进表里。
65
+ *
66
+ * 语义=词集而非子串(实现时对方案字面正则 /key|token|…/i 的修正,review 时可推翻):
67
+ * 子串会误杀 写点白名单里的 `tokens`(token 计数,非凭据),且 `cost_per_token`
68
+ * 一类合法键也躲不过;词集按 camel/snake/kebab 拆词后整词匹配,
69
+ * `api_key/refreshToken/COOKIE_ID` 照杀,`tokens/monkey` 放行。
70
+ */
71
+ const SENSITIVE_WORDS = /^(key|keys|token|secret|secrets|credential|credentials|authorization|cookie|cookies|apikey|accesskey|accesstoken|authtoken|refreshtoken|bearer)$/i;
72
+
73
+ function sensitiveHit(key: string): boolean {
74
+ return key
75
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
76
+ .toLowerCase()
77
+ .split(/[^a-z0-9]+/)
78
+ .some((w) => SENSITIVE_WORDS.test(w));
79
+ }
80
+
81
+ export function assertNoSensitiveKeys(meta: Record<string, unknown>, path = "meta"): void {
82
+ for (const [k, v] of Object.entries(meta)) {
83
+ if (sensitiveHit(k)) {
84
+ const where = `${path}.${k}`;
85
+ console.error(`audit: rejected sensitive meta key ${where}`);
86
+ throw new Error(`audit meta rejected: sensitive key ${where}`);
87
+ }
88
+ if (v !== null && typeof v === "object") {
89
+ if (Array.isArray(v)) {
90
+ v.forEach((x, i) => x !== null && typeof x === "object" && assertNoSensitiveKeys(x as Record<string, unknown>, `${path}.${k}[${i}]`));
91
+ } else {
92
+ assertNoSensitiveKeys(v as Record<string, unknown>, `${path}.${k}`);
93
+ }
94
+ }
95
+ }
96
+ }
97
+
98
+ /** purge 段白名单(5B):一段连续被删 id + 段尾行存储 hash(删前读取)。 */
99
+ export interface PurgeSegment {
100
+ from_id: number;
101
+ to_id: number;
102
+ last_hash: string;
103
+ }
104
+
105
+ /** 把待删行(按 id 升序)聚成连续段。 */
106
+ export function segmentsFrom(rows: Array<{ id: number; hash: string }>): PurgeSegment[] {
107
+ const segs: PurgeSegment[] = [];
108
+ for (const r of rows) {
109
+ const last = segs[segs.length - 1];
110
+ if (last && r.id === last.to_id + 1) last.to_id = r.id;
111
+ else segs.push({ from_id: r.id, to_id: r.id, last_hash: r.hash });
112
+ segs[segs.length - 1].last_hash = r.hash; // 段尾 hash 随延伸滚动
113
+ }
114
+ return segs;
115
+ }
116
+
117
+ export interface VerifyResult {
118
+ ok: boolean;
119
+ rows: number;
120
+ /** 起点锚定:校验从当前最老行起。空表 null。 */
121
+ checkedFromId: number | null;
122
+ /** 摘要不符(内容被改)或白名单段衔接核对不符。 */
123
+ brokenAtId: number | null;
124
+ /** 未经 purge 记录的 id 空洞——首个缺失行的 id(疑似恶意删行,等同断链报告)。 */
125
+ gapAtId: number | null;
126
+ }
127
+
128
+ /**
129
+ * 按 id 升序扫全表重算链(三条口径)。`rows` 须已按 id 升序——
130
+ * 存储层负责排序,这里不重排(verify 是全表扫,顺序错误是装配 bug,不该被静默吞掉)。
131
+ */
132
+ export function verifyChain(rows: ChainRow[]): VerifyResult {
133
+ const base: VerifyResult = { ok: true, rows: rows.length, checkedFromId: rows[0]?.id ?? null, brokenAtId: null, gapAtId: null };
134
+ if (!rows.length) return base;
135
+
136
+ // 白名单:ops.audit.purge 行的 meta.segments。篡改它自身会被逐行重算抓到(它在链内, 自我闭环)。
137
+ const segments: PurgeSegment[] = [];
138
+ for (const r of rows) {
139
+ if (r.action !== "ops.audit.purge") continue;
140
+ const segs = r.meta["segments"];
141
+ if (!Array.isArray(segs)) continue;
142
+ for (const s of segs) {
143
+ if (s && typeof s === "object") {
144
+ const { from_id, to_id, last_hash } = s as Record<string, unknown>;
145
+ if (typeof from_id === "number" && typeof to_id === "number" && typeof last_hash === "string") {
146
+ segments.push({ from_id, to_id, last_hash });
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ let brokenAtId: number | null = null;
153
+ let gapAtId: number | null = null;
154
+ for (let i = 0; i < rows.length; i++) {
155
+ const r = rows[i];
156
+ const prev = i > 0 ? rows[i - 1] : null;
157
+ if (prev && r.id !== prev.id + 1) {
158
+ // 空洞:须被某段白名单「恰等区间」背书,且空洞后首存活行 prev_hash == 段 last_hash。
159
+ const seg = segments.find((s) => s.from_id === prev.id + 1 && s.to_id === r.id - 1);
160
+ if (!seg) gapAtId ??= prev.id + 1;
161
+ else if (seg.last_hash !== r.prevHash) brokenAtId ??= r.id;
162
+ } else if (prev && r.prevHash !== prev.hash) {
163
+ brokenAtId ??= r.id; // 无空洞却断衔接:腰删未重连/前缀被换
164
+ }
165
+ if (rowHash(r.prevHash, r) !== r.hash) brokenAtId ??= r.id; // 首行不做创世要求,但本行内容照验
166
+ if (brokenAtId !== null && gapAtId !== null) break;
167
+ }
168
+ return { ...base, ok: brokenAtId === null && gapAtId === null, brokenAtId, gapAtId };
169
+ }