@mebular/mcp 0.2.4 → 0.3.2

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.
@@ -0,0 +1,193 @@
1
+ // MCP Memory Capability token(0.3.0 contract v2 §2.1)
2
+ //
3
+ // 只服务于 MCP daemon 内部的 `/internal/memory/v1`:
4
+ // - 生成 ≥32 字节随机 base64url token;
5
+ // - 写入 `<home>/memory-runtime/capability-token`(目录 0700、文件 0600);
6
+ // - `MEBULAR_CAPABILITY_TOKEN` 可覆盖(测试/调试/由 MCP 注入 sidecar 子进程);
7
+ // - 进程内只保存 token 的 sha256(tokenHash)与过期时间;token 明文只在生成/读取时短暂存在。
8
+ //
9
+ // 本模块不在 import 时创建任何目录或文件;轻量模式(memoryRuntime.enabled=false)不会调用 ensure。
10
+
11
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
12
+ import { existsSync } from 'node:fs';
13
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
14
+ import { join } from 'node:path';
15
+
16
+ export const CAPABILITY_TOKEN_VERSION = 1;
17
+ export const CAPABILITY_TOKEN_DIR = 'memory-runtime';
18
+ export const CAPABILITY_TOKEN_FILE = 'capability-token';
19
+ export const DEFAULT_CAPABILITY_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
20
+
21
+ /** `<home>/memory-runtime`。 */
22
+ export function capabilityTokenDir(home) {
23
+ return join(home, CAPABILITY_TOKEN_DIR);
24
+ }
25
+
26
+ /** `<home>/memory-runtime/capability-token`。 */
27
+ export function capabilityTokenPath(home) {
28
+ return join(capabilityTokenDir(home), CAPABILITY_TOKEN_FILE);
29
+ }
30
+
31
+ /** 至少 32 字节随机 → base64url(约 43 字符)。 */
32
+ export function generateCapabilityToken({ bytes = 32 } = {}) {
33
+ const size = Number.isInteger(bytes) && bytes >= 32 ? bytes : 32;
34
+ return randomBytes(size).toString('base64url');
35
+ }
36
+
37
+ /** token 的 sha256 十六进制摘要(进程内只保存它)。 */
38
+ export function hashCapabilityToken(token) {
39
+ return createHash('sha256').update(String(token)).digest('hex');
40
+ }
41
+
42
+ /** 稳定 tokenId(可安全放进日志/状态;不含 token 明文)。 */
43
+ export function tokenIdForToken(token) {
44
+ return `tok_${hashCapabilityToken(token).slice(0, 16)}`;
45
+ }
46
+
47
+ /** 常量时间比较两个 token 字符串(内部按 sha256 比较,避免长度泄漏)。 */
48
+ export function safeTokenEqual(a, b) {
49
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
50
+ const ah = Buffer.from(hashCapabilityToken(a), 'hex');
51
+ const bh = Buffer.from(hashCapabilityToken(b), 'hex');
52
+ return ah.length === bh.length && timingSafeEqual(ah, bh);
53
+ }
54
+
55
+ /**
56
+ * 校验调用方 token 是否匹配进程内记录。
57
+ * @param {unknown} token
58
+ * @param {{tokenHash?: string, expiresAt?: number|null}|null|undefined} record
59
+ * @param {{now?: number}} [options]
60
+ */
61
+ export function verifyCapabilityToken(token, record, { now = Date.now() } = {}) {
62
+ if (!record || typeof record.tokenHash !== 'string' || typeof token !== 'string' || token.length === 0) {
63
+ return false;
64
+ }
65
+ const expiresAt = typeof record.expiresAt === 'number' ? record.expiresAt : 0;
66
+ if (expiresAt > 0 && now >= expiresAt) return false;
67
+ let expected;
68
+ try {
69
+ expected = Buffer.from(record.tokenHash, 'hex');
70
+ } catch {
71
+ return false;
72
+ }
73
+ if (expected.length !== 32) return false;
74
+ const actual = Buffer.from(hashCapabilityToken(token), 'hex');
75
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
76
+ }
77
+
78
+ /**
79
+ * 读取 sidecar 可用的 token 记录。
80
+ *
81
+ * 顺序:`MEBULAR_CAPABILITY_TOKEN` → `<home>/memory-runtime/capability-token`。
82
+ * 文件损坏/过期仍返回记录(带 `expired`),由调用方决定是否拒绝;不存在返回 null。
83
+ * 返回对象包含 token 明文——只允许交给本机 sidecar / 测试,不得写入日志或 status。
84
+ */
85
+ export async function readCapabilityToken({ home, env = process.env, now = Date.now() } = {}) {
86
+ const override = env?.MEBULAR_CAPABILITY_TOKEN;
87
+ if (typeof override === 'string' && override.length > 0) {
88
+ return {
89
+ version: CAPABILITY_TOKEN_VERSION,
90
+ token: override,
91
+ tokenId: tokenIdForToken(override),
92
+ tokenHash: hashCapabilityToken(override),
93
+ issuedAt: 0,
94
+ expiresAt: 0,
95
+ mcpPid: null,
96
+ source: 'env',
97
+ expired: false,
98
+ };
99
+ }
100
+ if (typeof home !== 'string' || home.length === 0) return null;
101
+ const file = capabilityTokenPath(home);
102
+ if (!existsSync(file)) return null;
103
+ let data;
104
+ try {
105
+ data = JSON.parse(await readFile(file, 'utf-8'));
106
+ } catch {
107
+ return null;
108
+ }
109
+ if (!data || data.version !== CAPABILITY_TOKEN_VERSION || typeof data.token !== 'string' || data.token.length === 0) {
110
+ return null;
111
+ }
112
+ const expiresAt = typeof data.expiresAt === 'number' ? data.expiresAt : 0;
113
+ return {
114
+ ...data,
115
+ tokenId: tokenIdForToken(data.token),
116
+ tokenHash: hashCapabilityToken(data.token),
117
+ source: 'file',
118
+ expired: expiresAt > 0 && now >= expiresAt,
119
+ };
120
+ }
121
+
122
+ /**
123
+ * 生成并持久化 token;已存在也**重新生成**(MCP 每次启动轮换,旧 token 立即失效)。
124
+ * 设置 `MEBULAR_CAPABILITY_TOKEN` 时不创建目录/文件,直接返回覆盖值。
125
+ *
126
+ * @returns {Promise<{version:number, token:string, tokenId:string, tokenHash:string,
127
+ * issuedAt:number, expiresAt:number, mcpPid:number|null, source:'env'|'file', file:string|null}>}
128
+ */
129
+ export async function ensureCapabilityToken({
130
+ home,
131
+ env = process.env,
132
+ now = Date.now(),
133
+ ttlMs = DEFAULT_CAPABILITY_TOKEN_TTL_MS,
134
+ mcpPid = process.pid,
135
+ dirMode = 0o700,
136
+ fileMode = 0o600,
137
+ } = {}) {
138
+ const override = env?.MEBULAR_CAPABILITY_TOKEN;
139
+ if (typeof override === 'string' && override.length > 0) {
140
+ return {
141
+ version: CAPABILITY_TOKEN_VERSION,
142
+ token: override,
143
+ tokenId: tokenIdForToken(override),
144
+ tokenHash: hashCapabilityToken(override),
145
+ issuedAt: now,
146
+ expiresAt: 0,
147
+ mcpPid,
148
+ source: 'env',
149
+ file: null,
150
+ };
151
+ }
152
+ if (typeof home !== 'string' || home.length === 0) {
153
+ throw new Error('capability token 需要 home 目录');
154
+ }
155
+
156
+ const dir = capabilityTokenDir(home);
157
+ const file = capabilityTokenPath(home);
158
+ const token = generateCapabilityToken();
159
+ const record = {
160
+ version: CAPABILITY_TOKEN_VERSION,
161
+ token,
162
+ issuedAt: now,
163
+ expiresAt: now + (Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : DEFAULT_CAPABILITY_TOKEN_TTL_MS),
164
+ mcpPid,
165
+ };
166
+
167
+ await mkdir(dir, { recursive: true, mode: dirMode });
168
+ await chmod(dir, dirMode);
169
+ const tmp = join(dir, `.${CAPABILITY_TOKEN_FILE}.tmp-${process.pid}-${randomUUID()}`);
170
+ try {
171
+ await writeFile(tmp, JSON.stringify(record), { encoding: 'utf-8', mode: fileMode });
172
+ await chmod(tmp, fileMode);
173
+ await rename(tmp, file);
174
+ await chmod(file, fileMode);
175
+ } catch (error) {
176
+ await rm(tmp, { force: true }).catch(() => undefined);
177
+ throw error;
178
+ }
179
+
180
+ return {
181
+ ...record,
182
+ tokenId: tokenIdForToken(token),
183
+ tokenHash: hashCapabilityToken(token),
184
+ source: 'file',
185
+ file,
186
+ };
187
+ }
188
+
189
+ /** 删除 token 文件(撤销/停用);目录保留。 */
190
+ export async function removeCapabilityToken({ home } = {}) {
191
+ if (typeof home !== 'string' || home.length === 0) return;
192
+ await rm(capabilityTokenPath(home), { force: true }).catch(() => undefined);
193
+ }