@lark-codem/codem-cli 0.1.274-test.202611170849.0.gc5a50ef → 0.1.274

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.
@@ -1,37 +1,37 @@
1
- export function credentialStorageRecovery(errorCode) {
2
- const code = String(errorCode).replace(/^credential_storage_/, "");
3
- if (code === "backend_load_failed") return {
4
- message: "本机凭据模块无法加载",
5
- hint: "请重新安装与当前操作系统和架构匹配的完整 CodeM 包;保留现有凭据文件,不要删除或重新生成主密钥。"
6
- };
7
- if (code !== "corrupt" && code !== "key_missing") return null;
8
- return {
9
- message: code === "corrupt" ? "本机加密凭据损坏" : "本机凭据主密钥缺失",
10
- hint: "请运行 codem report --dry-run --no-session 生成本地诊断包;如有备份,请恢复配套的凭据和主密钥。不要单独删除或重新生成主密钥。"
11
- };
12
- }
13
-
14
- // An interrupted rotation can recover through refresh/replay. Re-login remains
15
- // an explicit escape hatch, not the verdict for a temporary transport failure.
16
- export const OAUTH_REAUTHORIZATION_HINT =
17
- "上次 OAuth 刷新尚未确认,将在下次连接时重试恢复;也可运行 codem login 重新登录(设备身份会保留)";
18
-
19
- export class CredentialStorageError extends Error {
20
- constructor(code, kind = null) {
21
- const recovery = credentialStorageRecovery(code);
22
- const rotation = kind === "oauth" && (code === "rotation_pending" || code === "rotation_unknown");
23
- const suffix = recovery ? `。${recovery.message}。${recovery.hint}` : rotation ? `。${OAUTH_REAUTHORIZATION_HINT}。` : "";
24
- super(`Credential storage ${code}${kind ? ` (${kind})` : ""}${suffix}`);
25
- this.name = "CredentialStorageError";
26
- this.code = `credential_storage_${code}`;
27
- this.kind = kind;
28
- }
29
- }
30
-
31
- export function isRecoverableCredentialState(error) {
32
- return error?.code === "credential_storage_rotation_pending"
33
- || error?.code === "credential_storage_rotation_unknown"
34
- // A missing OAuth record permits reauthorization with the existing device,
35
- // never use of its stale plaintext mirror or another credential kind.
36
- || (error?.code === "credential_storage_missing" && error.kind === "oauth");
37
- }
1
+ export function credentialStorageRecovery(errorCode) {
2
+ const code = String(errorCode).replace(/^credential_storage_/, "");
3
+ if (code === "backend_load_failed") return {
4
+ message: "本机凭据模块无法加载",
5
+ hint: "请重新安装与当前操作系统和架构匹配的完整 CodeM 包;保留现有凭据文件,不要删除或重新生成主密钥。"
6
+ };
7
+ if (code !== "corrupt" && code !== "key_missing") return null;
8
+ return {
9
+ message: code === "corrupt" ? "本机加密凭据损坏" : "本机凭据主密钥缺失",
10
+ hint: "请运行 codem report --dry-run --no-session 生成本地诊断包;如有备份,请恢复配套的凭据和主密钥。不要单独删除或重新生成主密钥。"
11
+ };
12
+ }
13
+
14
+ // An interrupted rotation can recover through refresh/replay. Re-login remains
15
+ // an explicit escape hatch, not the verdict for a temporary transport failure.
16
+ export const OAUTH_REAUTHORIZATION_HINT =
17
+ "上次 OAuth 刷新尚未确认,将在下次连接时重试恢复;也可运行 codem login 重新登录(设备身份会保留)";
18
+
19
+ export class CredentialStorageError extends Error {
20
+ constructor(code, kind = null) {
21
+ const recovery = credentialStorageRecovery(code);
22
+ const rotation = kind === "oauth" && (code === "rotation_pending" || code === "rotation_unknown");
23
+ const suffix = recovery ? `。${recovery.message}。${recovery.hint}` : rotation ? `。${OAUTH_REAUTHORIZATION_HINT}。` : "";
24
+ super(`Credential storage ${code}${kind ? ` (${kind})` : ""}${suffix}`);
25
+ this.name = "CredentialStorageError";
26
+ this.code = `credential_storage_${code}`;
27
+ this.kind = kind;
28
+ }
29
+ }
30
+
31
+ export function isRecoverableCredentialState(error) {
32
+ return error?.code === "credential_storage_rotation_pending"
33
+ || error?.code === "credential_storage_rotation_unknown"
34
+ // A missing OAuth record permits reauthorization with the existing device,
35
+ // never use of its stale plaintext mirror or another credential kind.
36
+ || (error?.code === "credential_storage_missing" && error.kind === "oauth");
37
+ }
@@ -1,29 +1,29 @@
1
- import fs from "node:fs/promises";
2
- import { CredentialStorageError } from "./credential-errors.js";
3
-
4
- export const CREDENTIAL_SCHEMA = 1;
5
- const KINDS = new Set(["oauth", "router-ak"]);
6
- const STATES = new Set(["legacy", "preparing", "secure"]);
7
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
8
- function fail(code, kind) { throw new CredentialStorageError(code, kind); }
9
-
10
- export async function readCredentialMetadata(metadataPath, marker = null, expectedKind = null) {
11
- if (expectedKind && marker && marker.kind !== expectedKind) fail("scope_mismatch", expectedKind);
12
- let metadata;
13
- try {
14
- metadata = JSON.parse(await fs.readFile(metadataPath, "utf8"));
15
- } catch (error) {
16
- if (error.code === "ENOENT" && !marker) return null;
17
- fail(error.code === "ENOENT" ? "metadata_missing" : "metadata_unreadable");
18
- }
19
- if (metadata?.schemaVersion !== CREDENTIAL_SCHEMA) fail("incompatible");
20
- if (!UUID.test(metadata.scopeId) || !UUID.test(metadata.loginEpoch)
21
- || typeof metadata.loggedOut !== "boolean" || !metadata.slots || typeof metadata.slots !== "object") fail("corrupt");
22
- for (const [kind, slot] of Object.entries(metadata.slots)) {
23
- if (!KINDS.has(kind) || !STATES.has(slot?.state)) fail("corrupt", kind);
24
- if (slot.state !== "legacy" && typeof slot.backend !== "string") fail("corrupt", kind);
25
- if (slot.rotation && !UUID.test(slot.rotation.operationId)) fail("corrupt", kind);
26
- }
27
- if (marker && (marker.schemaVersion !== CREDENTIAL_SCHEMA || marker.scopeId !== metadata.scopeId)) fail("scope_mismatch");
28
- return metadata;
29
- }
1
+ import fs from "node:fs/promises";
2
+ import { CredentialStorageError } from "./credential-errors.js";
3
+
4
+ export const CREDENTIAL_SCHEMA = 1;
5
+ const KINDS = new Set(["oauth", "router-ak"]);
6
+ const STATES = new Set(["legacy", "preparing", "secure"]);
7
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
8
+ function fail(code, kind) { throw new CredentialStorageError(code, kind); }
9
+
10
+ export async function readCredentialMetadata(metadataPath, marker = null, expectedKind = null) {
11
+ if (expectedKind && marker && marker.kind !== expectedKind) fail("scope_mismatch", expectedKind);
12
+ let metadata;
13
+ try {
14
+ metadata = JSON.parse(await fs.readFile(metadataPath, "utf8"));
15
+ } catch (error) {
16
+ if (error.code === "ENOENT" && !marker) return null;
17
+ fail(error.code === "ENOENT" ? "metadata_missing" : "metadata_unreadable");
18
+ }
19
+ if (metadata?.schemaVersion !== CREDENTIAL_SCHEMA) fail("incompatible");
20
+ if (!UUID.test(metadata.scopeId) || !UUID.test(metadata.loginEpoch)
21
+ || typeof metadata.loggedOut !== "boolean" || !metadata.slots || typeof metadata.slots !== "object") fail("corrupt");
22
+ for (const [kind, slot] of Object.entries(metadata.slots)) {
23
+ if (!KINDS.has(kind) || !STATES.has(slot?.state)) fail("corrupt", kind);
24
+ if (slot.state !== "legacy" && typeof slot.backend !== "string") fail("corrupt", kind);
25
+ if (slot.rotation && !UUID.test(slot.rotation.operationId)) fail("corrupt", kind);
26
+ }
27
+ if (marker && (marker.schemaVersion !== CREDENTIAL_SCHEMA || marker.scopeId !== metadata.scopeId)) fail("scope_mismatch");
28
+ return metadata;
29
+ }
package/profile/debug.js CHANGED
@@ -1,104 +1,104 @@
1
- import { recordSelectedRuntimeLog } from "./runtime-logs.js";
2
-
3
- const DEBUG_ENV_KEYS = ["CODEM_DEBUG", "CODEM_BRIDGE_DEBUG"];
4
- const SENSITIVE_KEY_PATTERN = /^(?:authorization|token|secret|password|apikey|api_key|apiKey|ak|access_key|accessKey|secret_key|secretKey|appsecret|app_secret|login_secret|refresh_token|access_token|user_access_token|userAccessToken|refreshToken|accessToken|uat|rt|deviceSecret|device_secret|deviceSecretPlaintext|device_secret_plaintext)$/iu;
5
-
6
- function enabledValue(value) {
7
- const normalized = String(value ?? "").trim().toLowerCase();
8
- return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "debug" || normalized === "trace";
9
- }
10
-
11
- export function isDebugEnabled(env = process.env) {
12
- return DEBUG_ENV_KEYS.some((key) => enabledValue(env?.[key]));
13
- }
14
-
15
- function redactString(value) {
16
- return String(value ?? "")
17
- .replace(/((?:Authorization|Codem-Login-Secret)\s*:\s*(?:Bearer\s+)?)[^&\s,"'}]+/giu, "$1[REDACTED]")
18
- .replace(/("(?:authorization|token|secret|apikey|api_key|apiKey|ak|access_key|accessKey|secret_key|secretKey|refresh_token|access_token|user_access_token|userAccessToken|refreshToken|accessToken)"\s*:\s*")[^"]*(")/giu, "$1[REDACTED]$2")
19
- .replace(/((?:refresh_token|access_token|user_access_token|refreshToken|accessToken|userAccessToken|apikey|api_key|apiKey|access_key|accessKey|secret_key|secretKey|uat|rt|token|secret|ak)\s*[=:]\s*)[^&\s,"'}]+/giu, "$1[REDACTED]");
20
- }
21
-
22
- export function sanitizeDebugPayload(value, { maxStringLength = 500, depth = 0 } = {}) {
23
- if (value === null || value === undefined) {
24
- return value;
25
- }
26
- if (typeof value === "string") {
27
- const redacted = redactString(value);
28
- return redacted.length > maxStringLength ? `${redacted.slice(0, maxStringLength - 1)}...` : redacted;
29
- }
30
- if (typeof value === "number" || typeof value === "boolean") {
31
- return value;
32
- }
33
- if (Array.isArray(value)) {
34
- if (depth >= 4) {
35
- return `[array:${value.length}]`;
36
- }
37
- return value.slice(0, 50).map((entry) => sanitizeDebugPayload(entry, { maxStringLength, depth: depth + 1 }));
38
- }
39
- if (typeof value === "object") {
40
- if (depth >= 4) {
41
- return "[object]";
42
- }
43
- const output = {};
44
- for (const [key, entry] of Object.entries(value)) {
45
- if (SENSITIVE_KEY_PATTERN.test(key)) {
46
- output[key] = entry ? "[REDACTED]" : entry;
47
- } else {
48
- output[key] = sanitizeDebugPayload(entry, { maxStringLength, depth: depth + 1 });
49
- }
50
- }
51
- return output;
52
- }
53
- return String(value);
54
- }
55
-
56
- export function formatDebugLine(event, payload = {}) {
57
- const safePayload = sanitizeDebugPayload(payload);
58
- return `[codem][debug][${event}] ${JSON.stringify(safePayload)}`;
59
- }
60
-
61
- // debugLogAlways records a decision that can only be diagnosed after the fact,
62
- // regardless of CODEM_DEBUG. Reserve it for identity-changing or self-healing
63
- // actions — a device rebind, an auth retry — where the alternative is a
64
- // user-visible incident with nothing but prose in stderr to explain it. Field
65
- // reports have already hit that wall: a daemon rebound itself once a minute for
66
- // ten minutes and the structured record of *why* was gated behind a flag nobody
67
- // had set. High-frequency loops (per-poll sync, command lists) stay on debugLog.
68
- export function debugLogAlways(event, payload = {}, { logger = console } = {}) {
69
- recordSelectedRuntimeLog("bridge", event, payload);
70
- const line = formatDebugLine(event, payload);
71
- if (logger && typeof logger.info === "function") {
72
- logger.info(line);
73
- return true;
74
- }
75
- process.stderr.write(`${line}\n`);
76
- return true;
77
- }
78
-
79
- export function debugLog(event, payload = {}, {
80
- env = process.env,
81
- logger = console
82
- } = {}) {
83
- recordSelectedRuntimeLog("bridge", event, payload);
84
- if (!isDebugEnabled(env)) {
85
- return false;
86
- }
87
- const line = formatDebugLine(event, payload);
88
- if (logger && logger !== console) {
89
- if (typeof logger.debug === "function") {
90
- logger.debug(line);
91
- return true;
92
- }
93
- if (typeof logger.info === "function") {
94
- logger.info(line);
95
- return true;
96
- }
97
- if (typeof logger.error === "function") {
98
- logger.error(line);
99
- return true;
100
- }
101
- }
102
- process.stderr.write(`${line}\n`);
103
- return true;
104
- }
1
+ import { recordSelectedRuntimeLog } from "./runtime-logs.js";
2
+
3
+ const DEBUG_ENV_KEYS = ["CODEM_DEBUG", "CODEM_BRIDGE_DEBUG"];
4
+ const SENSITIVE_KEY_PATTERN = /^(?:authorization|token|secret|password|apikey|api_key|apiKey|ak|access_key|accessKey|secret_key|secretKey|appsecret|app_secret|login_secret|refresh_token|access_token|user_access_token|userAccessToken|refreshToken|accessToken|uat|rt|deviceSecret|device_secret|deviceSecretPlaintext|device_secret_plaintext)$/iu;
5
+
6
+ function enabledValue(value) {
7
+ const normalized = String(value ?? "").trim().toLowerCase();
8
+ return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "debug" || normalized === "trace";
9
+ }
10
+
11
+ export function isDebugEnabled(env = process.env) {
12
+ return DEBUG_ENV_KEYS.some((key) => enabledValue(env?.[key]));
13
+ }
14
+
15
+ function redactString(value) {
16
+ return String(value ?? "")
17
+ .replace(/((?:Authorization|Codem-Login-Secret)\s*:\s*(?:Bearer\s+)?)[^&\s,"'}]+/giu, "$1[REDACTED]")
18
+ .replace(/("(?:authorization|token|secret|apikey|api_key|apiKey|ak|access_key|accessKey|secret_key|secretKey|refresh_token|access_token|user_access_token|userAccessToken|refreshToken|accessToken)"\s*:\s*")[^"]*(")/giu, "$1[REDACTED]$2")
19
+ .replace(/((?:refresh_token|access_token|user_access_token|refreshToken|accessToken|userAccessToken|apikey|api_key|apiKey|access_key|accessKey|secret_key|secretKey|uat|rt|token|secret|ak)\s*[=:]\s*)[^&\s,"'}]+/giu, "$1[REDACTED]");
20
+ }
21
+
22
+ export function sanitizeDebugPayload(value, { maxStringLength = 500, depth = 0 } = {}) {
23
+ if (value === null || value === undefined) {
24
+ return value;
25
+ }
26
+ if (typeof value === "string") {
27
+ const redacted = redactString(value);
28
+ return redacted.length > maxStringLength ? `${redacted.slice(0, maxStringLength - 1)}...` : redacted;
29
+ }
30
+ if (typeof value === "number" || typeof value === "boolean") {
31
+ return value;
32
+ }
33
+ if (Array.isArray(value)) {
34
+ if (depth >= 4) {
35
+ return `[array:${value.length}]`;
36
+ }
37
+ return value.slice(0, 50).map((entry) => sanitizeDebugPayload(entry, { maxStringLength, depth: depth + 1 }));
38
+ }
39
+ if (typeof value === "object") {
40
+ if (depth >= 4) {
41
+ return "[object]";
42
+ }
43
+ const output = {};
44
+ for (const [key, entry] of Object.entries(value)) {
45
+ if (SENSITIVE_KEY_PATTERN.test(key)) {
46
+ output[key] = entry ? "[REDACTED]" : entry;
47
+ } else {
48
+ output[key] = sanitizeDebugPayload(entry, { maxStringLength, depth: depth + 1 });
49
+ }
50
+ }
51
+ return output;
52
+ }
53
+ return String(value);
54
+ }
55
+
56
+ export function formatDebugLine(event, payload = {}) {
57
+ const safePayload = sanitizeDebugPayload(payload);
58
+ return `[codem][debug][${event}] ${JSON.stringify(safePayload)}`;
59
+ }
60
+
61
+ // debugLogAlways records a decision that can only be diagnosed after the fact,
62
+ // regardless of CODEM_DEBUG. Reserve it for identity-changing or self-healing
63
+ // actions — a device rebind, an auth retry — where the alternative is a
64
+ // user-visible incident with nothing but prose in stderr to explain it. Field
65
+ // reports have already hit that wall: a daemon rebound itself once a minute for
66
+ // ten minutes and the structured record of *why* was gated behind a flag nobody
67
+ // had set. High-frequency loops (per-poll sync, command lists) stay on debugLog.
68
+ export function debugLogAlways(event, payload = {}, { logger = console } = {}) {
69
+ recordSelectedRuntimeLog("bridge", event, payload);
70
+ const line = formatDebugLine(event, payload);
71
+ if (logger && typeof logger.info === "function") {
72
+ logger.info(line);
73
+ return true;
74
+ }
75
+ process.stderr.write(`${line}\n`);
76
+ return true;
77
+ }
78
+
79
+ export function debugLog(event, payload = {}, {
80
+ env = process.env,
81
+ logger = console
82
+ } = {}) {
83
+ recordSelectedRuntimeLog("bridge", event, payload);
84
+ if (!isDebugEnabled(env)) {
85
+ return false;
86
+ }
87
+ const line = formatDebugLine(event, payload);
88
+ if (logger && logger !== console) {
89
+ if (typeof logger.debug === "function") {
90
+ logger.debug(line);
91
+ return true;
92
+ }
93
+ if (typeof logger.info === "function") {
94
+ logger.info(line);
95
+ return true;
96
+ }
97
+ if (typeof logger.error === "function") {
98
+ logger.error(line);
99
+ return true;
100
+ }
101
+ }
102
+ process.stderr.write(`${line}\n`);
103
+ return true;
104
+ }
@@ -1,95 +1,95 @@
1
- // 设备身份(device_id / device_secret)的唯一读取与归一实现(叶子模块,无内部依赖)。
2
- //
3
- // 为什么要有这个模块:在此之前 device_id 的读取被手写了四份(index.js 绑定路径、
4
- // login-state.js 的 isLoggedInConfig、config-store.js 的 logout 墓碑、
5
- // daemon-post-client.ts 的自动重绑),各自认的形状还不一样——绑定路径认四个位置,
6
- // 墓碑只认两个。这种漂移是必然的:读侧每遇到一次「读不到」就加宽一次容忍度,
7
- // 写侧却从没收敛,于是容忍度成了口头约定而不是一个函数。
8
- //
9
- // 事实核对(git 考古):config.json 里 device_id 的**唯一**真实写入形状是嵌套
10
- // camelCase `device.deviceId`,自 initial commit 起从未变过。snake_case 只存在于
11
- // 服务端 JSON 响应,在 API 边界就被归一成字符串了,从未整体落盘;顶层
12
- // `config.deviceId` / `config.device_id` 更是从来没有任何写入代码产生过——它们是
13
- // 防御性代码的化石。所以这里只保留嵌套两种:camelCase 是真实形状,snake_case 是
14
- // 对「服务端响应被整体 spread 进配置」这一真实可能性的收口。顶层形状已删除。
15
- //
16
- // 新增形状请改这里,不要在调用点就地手写回退链。
17
-
18
- function firstString(...values) {
19
- for (const value of values) {
20
- if (typeof value === "string" && value.trim()) {
21
- return value;
22
- }
23
- }
24
- return null;
25
- }
26
-
27
- function deviceOf(config) {
28
- return config?.device && typeof config.device === "object" && !Array.isArray(config.device)
29
- ? config.device
30
- : null;
31
- }
32
-
33
- /** 从 config 读设备 ID;读不到返回 null("本机确实没有设备",不表示"读失败")。 */
34
- export function readDeviceId(config = null) {
35
- const device = deviceOf(config);
36
- return device ? firstString(device.deviceId, device.device_id) : null;
37
- }
38
-
39
- /** 从 config 读设备密钥。logout 墓碑只留 deviceId,故此处会返回 null。 */
40
- export function readDeviceSecret(config = null) {
41
- const device = deviceOf(config);
42
- return device ? firstString(device.deviceSecret, device.device_secret) : null;
43
- }
44
-
45
- /**
46
- * 判定本次设备绑定的意图,供 bind_reason 上报与用户提示使用。
47
- *
48
- * rekey 读到了本地锚点,期望服务端复用同一条设备记录
49
- * first_bind 本机从未绑定过设备,新建是预期行为
50
- * anchor_missing ⚠️ 有登录过的痕迹、却读不到 device_id:不该发生
51
- *
52
- * 判据是「**曾登录过的痕迹**」而不是「配置文件是否存在」。后者会把合法首次登录误
53
- * 判成异常:`codem channel test` 等命令在登录前就会写出一份合法配置(device 为
54
- * null),此时报「历史工作目录仍挂在原设备下」纯属虚惊。
55
- *
56
- * 用 lastLoginUser / auth.oauth 而不是新加一个持久标记,是因为它们对存量用户天然
57
- * 成立、无需迁移,且都由 buildBaseConfig 透传保留 —— 包括 logout(clearLoginIdentity
58
- * 只清 user 和 auth.oauth,lastLoginUser 保留)。所以「device 被误抹成 null」这个
59
- * 事故形态仍会被正确判成 anchor_missing,不会被这次修正掩盖掉。
60
- */
61
- export function resolveBindReason(config = null) {
62
- if (readDeviceId(config)) {
63
- return "rekey";
64
- }
65
- const everLoggedIn = Boolean(
66
- config?.lastLoginUser || config?.auth?.oauth
67
- );
68
- return everLoggedIn ? "anchor_missing" : "first_bind";
69
- }
70
-
71
- /**
72
- * 把 device 子树归一到唯一的存储形状(camelCase),供 buildBaseConfig 在每次写盘
73
- * 时收敛。device 曾是 buildBaseConfig 里唯一被跳过归一化的字段(纯透传),这正是
74
- * 读侧兜底永远删不掉的原因——没有 normalize 就无法证明删掉兜底是安全的。
75
- */
76
- export function normalizeDeviceConfig(device = null) {
77
- if (!device || typeof device !== "object" || Array.isArray(device)) {
78
- return null;
79
- }
80
- const { device_id, device_secret, ...rest } = device;
81
- const deviceId = firstString(device.deviceId, device_id);
82
- const deviceSecret = firstString(device.deviceSecret, device_secret);
83
- const normalized = { ...rest };
84
- if (deviceId) {
85
- normalized.deviceId = deviceId;
86
- } else {
87
- delete normalized.deviceId;
88
- }
89
- if (deviceSecret) {
90
- normalized.deviceSecret = deviceSecret;
91
- } else {
92
- delete normalized.deviceSecret;
93
- }
94
- return normalized;
95
- }
1
+ // 设备身份(device_id / device_secret)的唯一读取与归一实现(叶子模块,无内部依赖)。
2
+ //
3
+ // 为什么要有这个模块:在此之前 device_id 的读取被手写了四份(index.js 绑定路径、
4
+ // login-state.js 的 isLoggedInConfig、config-store.js 的 logout 墓碑、
5
+ // daemon-post-client.ts 的自动重绑),各自认的形状还不一样——绑定路径认四个位置,
6
+ // 墓碑只认两个。这种漂移是必然的:读侧每遇到一次「读不到」就加宽一次容忍度,
7
+ // 写侧却从没收敛,于是容忍度成了口头约定而不是一个函数。
8
+ //
9
+ // 事实核对(git 考古):config.json 里 device_id 的**唯一**真实写入形状是嵌套
10
+ // camelCase `device.deviceId`,自 initial commit 起从未变过。snake_case 只存在于
11
+ // 服务端 JSON 响应,在 API 边界就被归一成字符串了,从未整体落盘;顶层
12
+ // `config.deviceId` / `config.device_id` 更是从来没有任何写入代码产生过——它们是
13
+ // 防御性代码的化石。所以这里只保留嵌套两种:camelCase 是真实形状,snake_case 是
14
+ // 对「服务端响应被整体 spread 进配置」这一真实可能性的收口。顶层形状已删除。
15
+ //
16
+ // 新增形状请改这里,不要在调用点就地手写回退链。
17
+
18
+ function firstString(...values) {
19
+ for (const value of values) {
20
+ if (typeof value === "string" && value.trim()) {
21
+ return value;
22
+ }
23
+ }
24
+ return null;
25
+ }
26
+
27
+ function deviceOf(config) {
28
+ return config?.device && typeof config.device === "object" && !Array.isArray(config.device)
29
+ ? config.device
30
+ : null;
31
+ }
32
+
33
+ /** 从 config 读设备 ID;读不到返回 null("本机确实没有设备",不表示"读失败")。 */
34
+ export function readDeviceId(config = null) {
35
+ const device = deviceOf(config);
36
+ return device ? firstString(device.deviceId, device.device_id) : null;
37
+ }
38
+
39
+ /** 从 config 读设备密钥。logout 墓碑只留 deviceId,故此处会返回 null。 */
40
+ export function readDeviceSecret(config = null) {
41
+ const device = deviceOf(config);
42
+ return device ? firstString(device.deviceSecret, device.device_secret) : null;
43
+ }
44
+
45
+ /**
46
+ * 判定本次设备绑定的意图,供 bind_reason 上报与用户提示使用。
47
+ *
48
+ * rekey 读到了本地锚点,期望服务端复用同一条设备记录
49
+ * first_bind 本机从未绑定过设备,新建是预期行为
50
+ * anchor_missing ⚠️ 有登录过的痕迹、却读不到 device_id:不该发生
51
+ *
52
+ * 判据是「**曾登录过的痕迹**」而不是「配置文件是否存在」。后者会把合法首次登录误
53
+ * 判成异常:`codem channel test` 等命令在登录前就会写出一份合法配置(device 为
54
+ * null),此时报「历史工作目录仍挂在原设备下」纯属虚惊。
55
+ *
56
+ * 用 lastLoginUser / auth.oauth 而不是新加一个持久标记,是因为它们对存量用户天然
57
+ * 成立、无需迁移,且都由 buildBaseConfig 透传保留 —— 包括 logout(clearLoginIdentity
58
+ * 只清 user 和 auth.oauth,lastLoginUser 保留)。所以「device 被误抹成 null」这个
59
+ * 事故形态仍会被正确判成 anchor_missing,不会被这次修正掩盖掉。
60
+ */
61
+ export function resolveBindReason(config = null) {
62
+ if (readDeviceId(config)) {
63
+ return "rekey";
64
+ }
65
+ const everLoggedIn = Boolean(
66
+ config?.lastLoginUser || config?.auth?.oauth
67
+ );
68
+ return everLoggedIn ? "anchor_missing" : "first_bind";
69
+ }
70
+
71
+ /**
72
+ * 把 device 子树归一到唯一的存储形状(camelCase),供 buildBaseConfig 在每次写盘
73
+ * 时收敛。device 曾是 buildBaseConfig 里唯一被跳过归一化的字段(纯透传),这正是
74
+ * 读侧兜底永远删不掉的原因——没有 normalize 就无法证明删掉兜底是安全的。
75
+ */
76
+ export function normalizeDeviceConfig(device = null) {
77
+ if (!device || typeof device !== "object" || Array.isArray(device)) {
78
+ return null;
79
+ }
80
+ const { device_id, device_secret, ...rest } = device;
81
+ const deviceId = firstString(device.deviceId, device_id);
82
+ const deviceSecret = firstString(device.deviceSecret, device_secret);
83
+ const normalized = { ...rest };
84
+ if (deviceId) {
85
+ normalized.deviceId = deviceId;
86
+ } else {
87
+ delete normalized.deviceId;
88
+ }
89
+ if (deviceSecret) {
90
+ normalized.deviceSecret = deviceSecret;
91
+ } else {
92
+ delete normalized.deviceSecret;
93
+ }
94
+ return normalized;
95
+ }
@@ -1,47 +1,47 @@
1
- import { randomBytes } from "node:crypto";
2
- import fs from "node:fs";
3
- import os from "node:os";
4
- import path from "node:path";
5
-
6
- const VALID = /^cm-[a-f0-9]{16}$/u;
7
- let cached;
8
-
9
- // A local support identifier, never an authentication/device-binding identity.
10
- // Exclusive creation avoids overwriting another process's ID. A failed or
11
- // interrupted write only loses persistence; diagnostics never gate startup.
12
- export function resolveDiagnosticId({ env = process.env, io = fs, home = os.homedir, random = randomBytes } = {}) {
13
- try {
14
- const inherited = env.CODEM_DIAGNOSTIC_ID;
15
- if (VALID.test(inherited ?? "")) return inherited;
16
- } catch { /* Unavailable environment must not gate startup. */ }
17
- let generated;
18
- try { generated = `cm-${random(8).toString("hex")}`; }
19
- catch {
20
- // Correlation only: entropy failure must not become a startup failure.
21
- generated = `cm-${Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("")}`;
22
- }
23
- try {
24
- const root = env.CODEM_HOME || env.LINCO_HOME || path.join(home(), ".codem");
25
- const file = path.join(root, "diagnostic-id");
26
- const read = () => {
27
- if (io.statSync(file).size > 64) return undefined;
28
- const value = io.readFileSync(file, "utf8").trim();
29
- return VALID.test(value) ? value : undefined;
30
- };
31
- try { const existing = read(); if (existing) return existing; } catch { /* first run */ }
32
- io.mkdirSync(root, { recursive: true });
33
- try { io.writeFileSync(file, `${generated}\n`, { flag: "wx", mode: 0o600 }); }
34
- catch { return read() ?? generated; }
35
- } catch { /* Read-only or unavailable local storage: process-local fallback. */ }
36
- return generated;
37
- }
38
-
39
- export function diagnosticId() {
40
- if (!cached) {
41
- cached = resolveDiagnosticId();
42
- // Children, including a restarted CLI and Core, inherit the same fallback
43
- // even when local storage is unavailable.
44
- try { process.env.CODEM_DIAGNOSTIC_ID = cached; } catch { /* Child spawn also receives the cached ID explicitly. */ }
45
- }
46
- return cached;
47
- }
1
+ import { randomBytes } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ const VALID = /^cm-[a-f0-9]{16}$/u;
7
+ let cached;
8
+
9
+ // A local support identifier, never an authentication/device-binding identity.
10
+ // Exclusive creation avoids overwriting another process's ID. A failed or
11
+ // interrupted write only loses persistence; diagnostics never gate startup.
12
+ export function resolveDiagnosticId({ env = process.env, io = fs, home = os.homedir, random = randomBytes } = {}) {
13
+ try {
14
+ const inherited = env.CODEM_DIAGNOSTIC_ID;
15
+ if (VALID.test(inherited ?? "")) return inherited;
16
+ } catch { /* Unavailable environment must not gate startup. */ }
17
+ let generated;
18
+ try { generated = `cm-${random(8).toString("hex")}`; }
19
+ catch {
20
+ // Correlation only: entropy failure must not become a startup failure.
21
+ generated = `cm-${Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("")}`;
22
+ }
23
+ try {
24
+ const root = env.CODEM_HOME || env.LINCO_HOME || path.join(home(), ".codem");
25
+ const file = path.join(root, "diagnostic-id");
26
+ const read = () => {
27
+ if (io.statSync(file).size > 64) return undefined;
28
+ const value = io.readFileSync(file, "utf8").trim();
29
+ return VALID.test(value) ? value : undefined;
30
+ };
31
+ try { const existing = read(); if (existing) return existing; } catch { /* first run */ }
32
+ io.mkdirSync(root, { recursive: true });
33
+ try { io.writeFileSync(file, `${generated}\n`, { flag: "wx", mode: 0o600 }); }
34
+ catch { return read() ?? generated; }
35
+ } catch { /* Read-only or unavailable local storage: process-local fallback. */ }
36
+ return generated;
37
+ }
38
+
39
+ export function diagnosticId() {
40
+ if (!cached) {
41
+ cached = resolveDiagnosticId();
42
+ // Children, including a restarted CLI and Core, inherit the same fallback
43
+ // even when local storage is unavailable.
44
+ try { process.env.CODEM_DIAGNOSTIC_ID = cached; } catch { /* Child spawn also receives the cached ID explicitly. */ }
45
+ }
46
+ return cached;
47
+ }