@lark-codem/codem-cli 0.1.281-dev.100104631660.0.gd9b8134 → 0.1.281-dev.100104655414.0.gd263b58

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,128 @@
1
+ #!/usr/bin/env node
2
+ // Image bootstrap's dedicated input. Never pipe business stdout/stderr here.
3
+ import os from "node:os";
4
+ import { randomUUID } from "node:crypto";
5
+ import { fileURLToPath } from "node:url";
6
+ import fs from "node:fs";
7
+ import { sendSlardarPcBatch, captureRuntimeLogArguments, formatRuntimeLogText, runtimeLogSecrets } from "./slardar-pc-transport.js";
8
+
9
+ const id = value => typeof value === "string" && /^[a-z\d._:-]{1,128}$/iu.test(value) ? value : undefined;
10
+ const FIELDS = ["stage", "outcome", "startup_id", "controller_id", "logical_sandbox_id", "sandbox_id", "dispatch_id", "request_id", "tenant_id", "tenant_key"];
11
+ const NUMBERS = ["exit_code", "errno", "http_status", "duration_ms"];
12
+
13
+ export function createStartupLogger({ component, startupId, identity = {}, env = process.env, version = "unknown", send = sendSlardarPcBatch } = {}) {
14
+ const processId = randomUUID();
15
+ const startup = id(startupId ?? env.CODEM_STARTUP_ID) ?? processId;
16
+ const source = id(component ?? env.CODEM_LOG_COMPONENT) ?? "sandbox-bootstrap";
17
+ const fields = {
18
+ startup_id: startup,
19
+ controller_id: id(identity.controllerId ?? env.CODEM_SANDBOX_CONTROLLER_ID),
20
+ logical_sandbox_id: id(identity.logicalSandboxId ?? env.CODEM_SANDBOX_LOGICAL_SANDBOX_ID),
21
+ sandbox_id: id(identity.sandboxId ?? env.CODEM_SANDBOX_ID ?? env.CODEM_SANDBOX_DEVICE_ID),
22
+ dispatch_id: id(identity.dispatchId ?? env.CODEM_DISPATCH_ID ?? env.CODEM_SANDBOX_DISPATCH_ID ?? env.DISPATCH_ID),
23
+ tenant_id: id(identity.tenantId ?? env.CODEM_SANDBOX_TENANT_ID),
24
+ tenant_key: id(identity.tenantKey ?? env.CODEM_SANDBOX_TENANT_KEY)
25
+ };
26
+ const header = {
27
+ aid: "1880", device_id: id(identity.deviceId ?? env.CODEM_SANDBOX_DEVICE_ID) ?? processId, user_id: "0",
28
+ parfait_version: "1.0.0.0", channel: "unknown", os: process.platform === "win32" ? "Windows" : process.platform === "darwin" ? "Mac OS X" : process.platform, os_version: os.release()
29
+ };
30
+ const secrets = runtimeLogSecrets(env);
31
+ const queue = [];
32
+ let closed = /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "");
33
+ let inflight;
34
+ let dropped = 0;
35
+ let uploadFailures = 0;
36
+ let activeController;
37
+ const timer = setInterval(() => { void flush(); }, 10_000);
38
+ timer.unref();
39
+
40
+ function log(level, message, context = {}, timestamp = Date.now()) {
41
+ try {
42
+ if (closed || !["info", "warn", "error", "fatal"].includes(level)) return false;
43
+ const safe = { ...fields };
44
+ for (const key of FIELDS) if (id(context[key])) safe[key] = context[key];
45
+ for (const key of NUMBERS) if (Number.isFinite(context[key])) safe[key] = context[key];
46
+ const entry = { level, args: captureRuntimeLogArguments([message]), fields: safe,
47
+ timestamp: Number.isSafeInteger(timestamp) && timestamp >= 0 ? timestamp : Date.now(), observationId: randomUUID() };
48
+ if (queue.length >= 256) { queue.shift(); dropped++; }
49
+ queue.push(entry);
50
+ return true;
51
+ } catch { dropped++; return false; }
52
+ }
53
+
54
+ function flush({ timeoutMs = 3000 } = {}) {
55
+ if (inflight) return inflight;
56
+ if (closed || queue.length === 0) return Promise.resolve();
57
+ inflight = drain(timeoutMs).finally(() => { inflight = undefined; });
58
+ return inflight;
59
+ }
60
+
61
+ async function drain(timeoutMs) {
62
+ const controller = new AbortController();
63
+ activeController = controller;
64
+ let timeout;
65
+ const expired = new Promise((_, reject) => {
66
+ // stdin (or the one EOF deadline below) owns this helper's lifetime.
67
+ // A previous background upload must not extend the short EOF budget.
68
+ timeout = setTimeout(() => { controller.abort(); reject(new Error("upload timeout")); }, timeoutMs);
69
+ timeout.unref();
70
+ });
71
+ try {
72
+ while (!closed && queue.length && !controller.signal.aborted) {
73
+ const batch = queue.splice(0, 8);
74
+ const data = batch.map(entry => ({
75
+ app_version: version, app_minor_version: "", build_id: "", process_type: "codem-sandbox-bootstrap", session_id: "",
76
+ timestamp: entry.timestamp, log_type: "log", log_level: entry.level === "fatal" ? "error" : entry.level,
77
+ category: { reporter: "codem_bootstrap", runtime_role: "sandbox", component: source, event: "application.log", severity: entry.level,
78
+ ...(id(env.CODEM_RESOURCE_ENV) ? { resource_env: env.CODEM_RESOURCE_ENV } : {}),
79
+ ...(id(env.CODEM_SANDBOX_TYPE) ? { sandbox_type: env.CODEM_SANDBOX_TYPE } : {}),
80
+ ...(fields.tenant_id ? { tenant_id: fields.tenant_id } : {}) },
81
+ log_content: `${formatRuntimeLogText(entry.args, secrets)}\n${JSON.stringify({ schema_version: 1, timestamp: entry.timestamp,
82
+ process_instance_id: processId, fields: { ...entry.fields, observation_id: entry.observationId } })}`
83
+ }));
84
+ try { await Promise.race([send({ header, data }, { signal: controller.signal }), expired]); }
85
+ catch { uploadFailures++; dropped += batch.length; break; }
86
+ }
87
+ } catch { uploadFailures++; }
88
+ finally { clearTimeout(timeout); activeController = undefined; }
89
+ }
90
+
91
+ return { log, flush, get pendingCount() { return queue.length; }, get droppedCount() { return dropped; },
92
+ get uploadFailureCount() { return uploadFailures; },
93
+ close() { closed = true; clearInterval(timer); activeController?.abort(); dropped += queue.length; queue.length = 0; } };
94
+ }
95
+
96
+ export async function runStartupLogInput({ input = process.stdin, ...options } = {}) {
97
+ const logger = createStartupLogger(options);
98
+ let pending = "";
99
+ // A dedicated pipe with bounded records. Oversized/malformed input is dropped;
100
+ // it cannot cause an unbounded readline allocation or affect the caller.
101
+ input.setEncoding("utf8");
102
+ input.on("data", chunk => {
103
+ pending += chunk;
104
+ let end;
105
+ while ((end = pending.indexOf("\n")) >= 0) {
106
+ const line = pending.slice(0, end);
107
+ pending = pending.slice(end + 1);
108
+ if (line.length > 8192) continue;
109
+ try {
110
+ const row = JSON.parse(line);
111
+ if (row && typeof row.message === "string") logger.log(row.level, row.message, row.fields, row.timestamp);
112
+ } catch { /* The pipe is optional diagnostic input. */ }
113
+ }
114
+ if (pending.length > 8192) pending = "";
115
+ });
116
+ await new Promise(resolve => { input.once("end", resolve); input.once("error", resolve); });
117
+ let deadline;
118
+ await Promise.race([logger.flush({ timeoutMs: 200 }), new Promise(resolve => { deadline = setTimeout(resolve, 200); })]);
119
+ clearTimeout(deadline);
120
+ logger.close();
121
+ }
122
+
123
+ let isMain = false;
124
+ try { isMain = Boolean(process.argv[1]) && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); }
125
+ catch { /* Importing the helper must not depend on the host entrypoint path. */ }
126
+ if (isMain) {
127
+ runStartupLogInput().catch(() => {});
128
+ }
@@ -0,0 +1,176 @@
1
+ import https from "node:https";
2
+ import { gzip } from "node:zlib";
3
+ import { promisify } from "node:util";
4
+ import { formatWithOptions } from "node:util";
5
+ import { createHash } from "node:crypto";
6
+
7
+ export const MAX_LOG_TEXT_BYTES = 16 * 1024;
8
+ const MAX_ARGUMENT_CHARS = 8192;
9
+ const SECRET_KEY = /token|secret|password|passwd|cookie|authorization|credential|api[_-]?key|access[_-]?key|(?:^|_)(?:ak|uat|rt)(?:_|$)/iu;
10
+ const NON_CREDENTIAL_SETTING = /^(?:enable|disable|max|min|num)_|_(?:enabled|disabled|enable|disable|import|max_tokens|dir|path|file)$/iu;
11
+ const runtimeOutputErrors = new WeakSet();
12
+ const nativeErrorStackGetter = Object.getOwnPropertyDescriptor(new Error(), "stack")?.get;
13
+
14
+ // Explicit provenance at the child/SSE boundary. Never infer it from text or
15
+ // trust an upstream terminal_error.source field to authorize uploading content.
16
+ export function markRuntimeOutputError(error) {
17
+ runtimeOutputErrors.add(error);
18
+ return error;
19
+ }
20
+
21
+ export function isRuntimeOutputError(error) { return runtimeOutputErrors.has(error); }
22
+
23
+ // Called once at the configuration boundary. Keep old values while their logs
24
+ // are queued, including credentials rotated after a log was recorded.
25
+ export function runtimeLogSecrets(source = {}) {
26
+ return Object.entries(source).filter(([key, value]) => SECRET_KEY.test(key) && !NON_CREDENTIAL_SETTING.test(key) &&
27
+ typeof value === "string" && value.length >= 8 && !/^(?:\d+|true|false|none|null|enabled|disabled)$/iu.test(value))
28
+ .slice(0, 64).map(([, value]) => Buffer.from(value.slice(0, 8192), "utf16le").toString("utf16le"));
29
+ }
30
+
31
+ // The application call only retains a bounded argument list. Formatting and
32
+ // redaction happen later in the uploader, never in the logging call.
33
+ export function captureRuntimeLogArguments(args) {
34
+ let remaining = 32 * 1024;
35
+ const seen = new Set();
36
+ const text = value => {
37
+ // Even a short slice can flatten an entire V8 rope. Omit the remote copy
38
+ // before slicing or converting an oversized value; local args stay intact.
39
+ if (value.length > Math.min(MAX_ARGUMENT_CHARS, remaining)) value = "[oversized log argument omitted]";
40
+ // A sliced V8 string can retain its entire upstream allocation. Copy only
41
+ // the bounded UTF-16 code units, including any unmatched surrogate.
42
+ const result = Buffer.from(value.slice(0, Math.min(MAX_ARGUMENT_CHARS, remaining)), "utf16le").toString("utf16le");
43
+ remaining -= result.length;
44
+ return result;
45
+ };
46
+ function snapshot(value, depth = 0, framesOnly = false) {
47
+ if (typeof value === "string") return framesOnly ? { log_error: true, framesOnly: true, message: text(value), stack: "" } : text(value);
48
+ if (value === null || ["number", "boolean", "undefined"].includes(typeof value)) return value;
49
+ if (!(value instanceof Error)) return "[object omitted]";
50
+ if (seen.has(value) || depth >= 8 || remaining === 0) return "[error cause omitted]";
51
+ seen.add(value);
52
+ // Never invoke getters/custom inspection or retain arbitrary object graphs.
53
+ const own = key => Object.getOwnPropertyDescriptor(value, key)?.value;
54
+ function inheritedDescriptor(key) {
55
+ let holder = value;
56
+ for (let i = 0; holder && i < 8; i++, holder = Object.getPrototypeOf(holder)) {
57
+ const descriptor = Object.getOwnPropertyDescriptor(holder, key);
58
+ if (descriptor) return descriptor;
59
+ }
60
+ }
61
+ const messageDescriptor = inheritedDescriptor("message");
62
+ const nameDescriptor = inheritedDescriptor("name");
63
+ const message = messageDescriptor?.value;
64
+ const name = nameDescriptor?.value;
65
+ const capturedMessage = typeof message === "string" ? text(message) : "Error";
66
+ // Some V8 versions materialize lazy stack even when reading its descriptor.
67
+ // Check message/name first, without invoking accessors or coercing objects.
68
+ // Oversized errors omit their remote body and retain the original Error
69
+ // locally; never expand their complete body on this thread.
70
+ const safeLazyStack = typeof message === "string" && typeof name === "string" &&
71
+ message.length + name.length <= MAX_ARGUMENT_CHARS && remaining > 0;
72
+ const stackDescriptor = safeLazyStack ? Object.getOwnPropertyDescriptor(value, "stack") : undefined;
73
+ // Node 22/V8 exposes the genuine lazy stack as a native accessor. Do not
74
+ // execute application-defined getters masquerading as Error properties.
75
+ const rawStack = stackDescriptor?.value ?? (stackDescriptor?.get &&
76
+ stackDescriptor.get === nativeErrorStackGetter
77
+ ? stackDescriptor.get.call(value) : undefined);
78
+ // A preformatted stack can also be arbitrarily large. Reject it before
79
+ // searching for the message or splitting/filtering its lines.
80
+ const stack = typeof rawStack === "string" && rawStack.length <= MAX_ARGUMENT_CHARS ? rawStack : undefined;
81
+ const cause = own("cause");
82
+ framesOnly ||= runtimeOutputErrors.has(value);
83
+ // A provider message can itself contain lines beginning with "at". Remove
84
+ // the complete original message before selecting V8's actual trailing frames.
85
+ const header = framesOnly && typeof stack === "string" ? (!name ? message : !message ? name : `${name}: ${message}`) : undefined;
86
+ const frameStart = typeof stack === "string" && typeof header === "string" && stack.startsWith(header + "\n")
87
+ ? header.length + 1 : -1;
88
+ const frames = framesOnly
89
+ ? frameStart < 0 ? undefined : stack.slice(frameStart).split("\n").filter(line => /^\s+at\s/u.test(line)).join("\n")
90
+ : stack;
91
+ return { log_error: true, framesOnly, stack: typeof frames === "string" ? text(frames) : undefined,
92
+ message: capturedMessage,
93
+ ...(cause === undefined ? {} : { cause: snapshot(cause, depth + 1, framesOnly) }) };
94
+ }
95
+ return args.slice(0, 8).map(value => snapshot(value));
96
+ }
97
+
98
+ export function redactRuntimeLogText(input, secrets = []) {
99
+ let text = input;
100
+ for (const secret of secrets) text = text.split(secret).join("[REDACTED]");
101
+ return text
102
+ .replace(/((?:proxy-authorization|authorization|set-cookie|cookie)["']?\s*:\s*)[^\r\n]*/giu, "$1[REDACTED]")
103
+ .replace(/((?:prompt|tool[_ -]?(?:output|result)|stdout|stderr|response[_ -]?body|request[_ -]?body|payload)["']?\s*[:=]\s*)[^\n]*/giu, "$1[content omitted]")
104
+ .replace(/((?:Bearer|Basic)\s+)[a-z\d._~+/=-]+/giu, "$1[REDACTED]")
105
+ .replace(/(--(?:token|secret|password|passwd|api[_-]?key|access[_-]?key|ak|uat|rt|authorization|credential)\s+)(?:"(?:\\(?:[^\n]|(?=\n|$))|[^"\\\n])*"?|'(?:\\(?:[^\n]|(?=\n|$))|[^'\\\n])*'?|[^\s]+)/giu, "$1[REDACTED]")
106
+ // Scan each complete assignment key once. Matching sensitive substrings
107
+ // between greedy key fragments causes catastrophic backtracking on log text.
108
+ .replace(/\b([a-z_][a-z\d_-]*)(["']?\s*[:=]\s*)("(?:\\(?:[^\n]|(?=\n|$))|[^"\\\n])*"?|'(?:\\(?:[^\n]|(?=\n|$))|[^'\\\n])*'?|[^\s,;"'{}]+)/giu,
109
+ (match, key, separator, value) => {
110
+ if (!SECRET_KEY.test(key) && key.toLowerCase() !== "key") return match;
111
+ const quote = value[0] === '"' || value[0] === "'" ? value[0] : "";
112
+ return `${key}${separator}${quote}[REDACTED]${quote}`;
113
+ })
114
+ .replace(/\b(?:sk-[a-z\d_-]{8,}|(?:ghp|gho|ghu|ghs|ghr)_[a-z\d]{8,}|glpat-[a-z\d_-]{8,}|[ut]-[a-z\d_.-]{16,})\b/giu, "[REDACTED]")
115
+ .replace(/(?:(?<![A-Za-z0-9])(?:codem_at|uat|rt|cat|ak|llm_api_ak)|(?<=sandbox_)(?:codem_at|uat|rt|cat|ak))_[A-Za-z0-9._~+/=-]+/gu, "[REDACTED]")
116
+ .replace(/(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?(?![A-Za-z0-9_-])/gu, "[REDACTED]")
117
+ // Consume the whole token once. Anchored replacements cannot restart at
118
+ // every nested https:// prefix when a query/fragment delimiter is absent.
119
+ .replace(/https?:\/\/[^\s]+/giu, url => url
120
+ .replace(/^(https?:\/\/)[^\s/@:]+:[^\s/@]+@/iu, "$1[REDACTED]@")
121
+ .replace(/^(https?:\/\/[^\s?#]+)[?#][^\s]*/iu, "$1?[REDACTED]")
122
+ .replace(/^(https?:\/\/[^/\s?#]+)\/[^\s?#]*/iu, "$1/[path]"))
123
+ .replace(/(?<![\w:/])(?:file:\/+)?(?:[a-z]:[\\/]|\/)(?:[^\s\\/:()"']+[\\/])+([^\s\\/()"']+)/giu, "<path>/$1");
124
+ }
125
+
126
+ export function formatRuntimeLogText(args, secrets = []) {
127
+ function errorText(value) {
128
+ if (!value?.log_error) return value;
129
+ const ownText = value.framesOnly ? `Runtime output error (fingerprint=${createHash("sha256").update(value.message).digest("hex").slice(0, 24)})\n${value.stack ?? ""}` : (value.stack ?? value.message);
130
+ return ownText + (value.cause === undefined ? "" : `\nCaused by: ${errorText(value.cause)}`);
131
+ }
132
+ const formatted = formatWithOptions({ depth: 3, maxArrayLength: 20, maxStringLength: 8192, customInspect: false, getters: false },
133
+ ...args.map(errorText)).slice(0, 64 * 1024);
134
+ const safe = redactRuntimeLogText(formatted, secrets);
135
+ const bytes = Buffer.from(safe);
136
+ return bytes.length <= MAX_LOG_TEXT_BYTES ? safe : `${bytes.subarray(0, MAX_LOG_TEXT_BYTES - 32).toString("utf8")}\n[log truncated]`;
137
+ }
138
+
139
+ // PC Custom Log / Custom Event wire format, verified against Parfait 1.7.0.0's
140
+ // public IUploader callback. This is not the Slardar Web/BID protocol. Keep the
141
+ // SDK capture fixture and the platform readback procedure with this adapter.
142
+ export const SLARDAR_PC_AID = "1880";
143
+ // Use the native envelope's four-part version convention in this legacy field.
144
+ // This is our JS adapter version; reporter=codem_js distinguishes it
145
+ // from the native Parfait SDK. Do not advertise a native SDK we do not run.
146
+ export const SLARDAR_PC_REPORTER_VERSION = "1.0.0.0";
147
+ const ENDPOINT = `https://pc-mon.zijieapi.com/monitor_pc/collect/api/pc_log?aid=${SLARDAR_PC_AID}`;
148
+ const compress = promisify(gzip);
149
+
150
+ export async function sendSlardarPcBatch(payload, { signal, request = https.request } = {}) {
151
+ signal?.throwIfAborted();
152
+ const body = await compress(Buffer.from(JSON.stringify(payload)));
153
+ signal?.throwIfAborted();
154
+ return new Promise((resolve, reject) => {
155
+ const req = request(ENDPOINT, {
156
+ method: "POST",
157
+ signal,
158
+ headers: {
159
+ "content-type": "application/json",
160
+ "content-encoding": "gzip",
161
+ "content-length": body.length
162
+ }
163
+ }, (res) => {
164
+ // The collector returns an empty 204. Never buffer arbitrary responses.
165
+ res.resume();
166
+ res.once("error", reject);
167
+ res.once("end", () => {
168
+ if (res.statusCode >= 200 && res.statusCode < 300) resolve();
169
+ else reject(new Error(`Slardar PC HTTP ${res.statusCode}`));
170
+ });
171
+ });
172
+ req.on("socket", (socket) => socket.unref?.());
173
+ req.once("error", reject);
174
+ req.end(body);
175
+ });
176
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-codem/codem-cli",
3
- "version": "0.1.281-dev.100104631660.0.gd9b8134",
3
+ "version": "0.1.281-dev.100104655414.0.gd263b58",
4
4
  "codemServiceManagementProtocol": 3,
5
5
  "codemProfileProtocol": 1,
6
6
  "type": "module",
@@ -29,17 +29,17 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@lark-codem/codem-core": "0.8.98-dev.100104631660.0.g5923e0f",
32
+ "@lark-codem/codem-core": "0.8.98-dev.100104655414.0.g6a29399",
33
33
  "zod": "3.25.76",
34
34
  "@lark-codem/lark-cli": "0.1.5"
35
35
  },
36
36
  "optionalDependencies": {
37
- "@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.100104631660.0.gd9b8134",
38
- "@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.100104631660.0.gd9b8134",
39
- "@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.100104631660.0.gd9b8134",
40
- "@lark-codem/codem-cli-linux-x64": "0.1.281-dev.100104631660.0.gd9b8134",
41
- "@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.100104631660.0.gd9b8134",
42
- "@lark-codem/codem-cli-win32-x64": "0.1.281-dev.100104631660.0.gd9b8134"
37
+ "@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.100104655414.0.gd263b58",
38
+ "@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.100104655414.0.gd263b58",
39
+ "@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.100104655414.0.gd263b58",
40
+ "@lark-codem/codem-cli-linux-x64": "0.1.281-dev.100104655414.0.gd263b58",
41
+ "@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.100104655414.0.gd263b58",
42
+ "@lark-codem/codem-cli-win32-x64": "0.1.281-dev.100104655414.0.gd263b58"
43
43
  },
44
44
  "engines": {
45
45
  "node": ">=18"
@@ -17,11 +17,11 @@ export const OAUTH_REAUTHORIZATION_HINT =
17
17
  "上次 OAuth 刷新尚未确认,将在下次连接时重试恢复;也可运行 codem login 重新登录(设备身份会保留)";
18
18
 
19
19
  export class CredentialStorageError extends Error {
20
- constructor(code, kind = null) {
20
+ constructor(code, kind = null, options = undefined) {
21
21
  const recovery = credentialStorageRecovery(code);
22
22
  const rotation = kind === "oauth" && (code === "rotation_pending" || code === "rotation_unknown");
23
23
  const suffix = recovery ? `。${recovery.message}。${recovery.hint}` : rotation ? `。${OAUTH_REAUTHORIZATION_HINT}。` : "";
24
- super(`Credential storage ${code}${kind ? ` (${kind})` : ""}${suffix}`);
24
+ super(`Credential storage ${code}${kind ? ` (${kind})` : ""}${suffix}`, options);
25
25
  this.name = "CredentialStorageError";
26
26
  this.code = `credential_storage_${code}`;
27
27
  this.kind = kind;
@@ -5,7 +5,7 @@ export const CREDENTIAL_SCHEMA = 1;
5
5
  const KINDS = new Set(["oauth", "router-ak"]);
6
6
  const STATES = new Set(["legacy", "preparing", "secure"]);
7
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); }
8
+ function fail(code, kind, options) { throw new CredentialStorageError(code, kind, options); }
9
9
 
10
10
  export async function readCredentialMetadata(metadataPath, marker = null, expectedKind = null) {
11
11
  if (expectedKind && marker && marker.kind !== expectedKind) fail("scope_mismatch", expectedKind);
@@ -14,7 +14,7 @@ export async function readCredentialMetadata(metadataPath, marker = null, expect
14
14
  metadata = JSON.parse(await fs.readFile(metadataPath, "utf8"));
15
15
  } catch (error) {
16
16
  if (error.code === "ENOENT" && !marker) return null;
17
- fail(error.code === "ENOENT" ? "metadata_missing" : "metadata_unreadable");
17
+ fail(error.code === "ENOENT" ? "metadata_missing" : "metadata_unreadable", null, { cause: error });
18
18
  }
19
19
  if (metadata?.schemaVersion !== CREDENTIAL_SCHEMA) fail("incompatible");
20
20
  if (!UUID.test(metadata.scopeId) || !UUID.test(metadata.loginEpoch)
package/profile/debug.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { recordSelectedRuntimeLog } from "./runtime-logs.js";
2
+ import { redactDebugString } from "./diagnostic-text.js";
2
3
 
3
4
  const DEBUG_ENV_KEYS = ["CODEM_DEBUG", "CODEM_BRIDGE_DEBUG"];
4
5
  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;
@@ -12,19 +13,12 @@ export function isDebugEnabled(env = process.env) {
12
13
  return DEBUG_ENV_KEYS.some((key) => enabledValue(env?.[key]));
13
14
  }
14
15
 
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
16
  export function sanitizeDebugPayload(value, { maxStringLength = 500, depth = 0 } = {}) {
23
17
  if (value === null || value === undefined) {
24
18
  return value;
25
19
  }
26
20
  if (typeof value === "string") {
27
- const redacted = redactString(value);
21
+ const redacted = redactDebugString(value);
28
22
  return redacted.length > maxStringLength ? `${redacted.slice(0, maxStringLength - 1)}...` : redacted;
29
23
  }
30
24
  if (typeof value === "number" || typeof value === "boolean") {
@@ -65,8 +59,8 @@ export function formatDebugLine(event, payload = {}) {
65
59
  // reports have already hit that wall: a daemon rebound itself once a minute for
66
60
  // ten minutes and the structured record of *why* was gated behind a flag nobody
67
61
  // 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);
62
+ export function debugLogAlways(event, payload = {}, { logger = console, remoteFields = undefined } = {}) {
63
+ recordSelectedRuntimeLog("bridge", event, remoteFields ? { ...payload, ...remoteFields } : payload);
70
64
  const line = formatDebugLine(event, payload);
71
65
  if (logger && typeof logger.info === "function") {
72
66
  logger.info(line);
@@ -78,9 +72,15 @@ export function debugLogAlways(event, payload = {}, { logger = console } = {}) {
78
72
 
79
73
  export function debugLog(event, payload = {}, {
80
74
  env = process.env,
81
- logger = console
75
+ logger = console,
76
+ capturedError = undefined,
77
+ remoteFields = undefined
82
78
  } = {}) {
83
- recordSelectedRuntimeLog("bridge", event, payload);
79
+ recordSelectedRuntimeLog("bridge", event, remoteFields ? { ...payload, ...remoteFields } : payload, { capturedError });
80
+ return writeDebugLog(event, payload, { env, logger });
81
+ }
82
+
83
+ export function writeDebugLog(event, payload, { env, logger }) {
84
84
  if (!isDebugEnabled(env)) {
85
85
  return false;
86
86
  }
@@ -0,0 +1,49 @@
1
+ const MAX_DIAGNOSTIC_SCAN_CHARS = 32_768;
2
+ const MAX_DIAGNOSTIC_TEXT_CHARS = 4096;
3
+
4
+ function safeString(value) {
5
+ if (value === null || value === undefined) return "";
6
+ if (typeof value === "string") return value;
7
+ try { return String(value); } catch { return "[UNSTRINGIFIABLE_VALUE]"; }
8
+ }
9
+
10
+ export function redactDebugString(value) {
11
+ return safeString(value)
12
+ .replace(/((?:Authorization|Codem-Login-Secret)\s*:\s*(?:(?:Bearer|Basic)\s+)?)[^&\s,"'}]+/giu, "$1[REDACTED]")
13
+ .replace(/("(?:authorization|password|uat|rt|ak|api[_-]?key|access[_-]?key|host[_-]?session|[A-Za-z0-9_.-]{0,64}secret[A-Za-z0-9_.-]{0,64}|[A-Za-z0-9_.-]{0,64}token)"\s*:\s*")[^"]*("|$)/giu, "$1[REDACTED]$2")
14
+ .replace(/(?<![A-Za-z0-9_.-])((?:password|uat|rt|ak|api[_-]?key|access[_-]?key|host[_-]?session|[A-Za-z0-9_.-]{0,64}secret[A-Za-z0-9_.-]{0,64}|[A-Za-z0-9_.-]{0,64}token)\s*[=:]\s*)(?:(["'])([^\r\n]*?)(?:\2|$)|[^&\s,"'}]+)/giu, (_, prefix, quote) => quote ? `${prefix}${quote}[REDACTED]${quote}` : `${prefix}[REDACTED]`);
15
+ }
16
+
17
+ /** @param {unknown} value */
18
+ export function safeDiagnosticEndpoint(value) {
19
+ try {
20
+ const url = new URL(safeString(value));
21
+ url.username = "";
22
+ url.password = "";
23
+ url.search = "";
24
+ url.hash = "";
25
+ return url.toString();
26
+ } catch {
27
+ return "";
28
+ }
29
+ }
30
+
31
+ /** @param {unknown} value */
32
+ export function redactDiagnosticText(value, { redactURLPath = false, preserveURLPunctuation = true } = {}) {
33
+ const input = safeString(value);
34
+ const bounded = input.length > MAX_DIAGNOSTIC_SCAN_CHARS ? input.slice(0, MAX_DIAGNOSTIC_SCAN_CHARS) : input;
35
+ const withSafeURLs = bounded.replace(/https?:\/\/[^\s"'<>]+/giu, (rawURL) => {
36
+ let end = rawURL.length;
37
+ while (end > 0 && "),.;".includes(rawURL[end - 1])) end -= 1;
38
+ const url = rawURL.slice(0, end);
39
+ const safe = safeDiagnosticEndpoint(url);
40
+ const display = safe && redactURLPath ? new URL(safe).origin : safe;
41
+ return (display || "[REDACTED_URL]") + (preserveURLPunctuation ? rawURL.slice(end) : "");
42
+ });
43
+ const redacted = redactDebugString(withSafeURLs)
44
+ .replace(/\bBearer\s+[^&\s,"'}]+/giu, "Bearer [REDACTED]")
45
+ .replace(/\b((?:Set-)?Cookie:[ \t]*)[^\r\n]+/giu, "$1[REDACTED]")
46
+ .replace(/(?:(?<![A-Za-z0-9])(?:codem_at|uat|rt|cat|ak|llm_api_ak)|(?<=sandbox_)(?:codem_at|uat|rt|cat|ak))_[A-Za-z0-9._~+/=-]+/gu, "[REDACTED]")
47
+ .replace(/(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?(?![A-Za-z0-9_-])/gu, "[REDACTED_JWT]");
48
+ return redacted.length > MAX_DIAGNOSTIC_TEXT_CHARS ? redacted.slice(0, MAX_DIAGNOSTIC_TEXT_CHARS) : redacted;
49
+ }
@@ -0,0 +1,17 @@
1
+ /** @param {unknown} value */
2
+ export function safeServerLogId(value) {
3
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/u.test(value) ? value : undefined;
4
+ }
5
+
6
+ export function httpReadDiagnostics(response, reason) {
7
+ let logId = null;
8
+ try {
9
+ logId = safeServerLogId(response?.headers?.get?.("x-tt-logid")) ?? null;
10
+ } catch {}
11
+ return {
12
+ httpStatus: Number.isInteger(response?.status) && response.status >= 100 && response.status <= 599
13
+ ? response.status : null,
14
+ logId,
15
+ reason
16
+ };
17
+ }
@@ -53,7 +53,7 @@ async function readLockedProfileSnapshot(home) {
53
53
  } catch (error) {
54
54
  if (!(error instanceof CredentialStorageError)) throw error;
55
55
  const kind = ["oauth", "router-ak"].includes(error.kind) ? error.kind : null;
56
- throw new CredentialStorageError(error.code.replace(/^credential_storage_/, ""), kind);
56
+ throw new CredentialStorageError(error.code.replace(/^credential_storage_/, ""), kind, error.cause !== undefined ? { cause: error.cause } : undefined);
57
57
  }
58
58
  if (!config && metadata && !metadata.loggedOut) throw new CredentialStorageError("config_missing", "oauth");
59
59
  const device = record(config?.device);