@lark-codem/codem-cli 0.1.281-dev.100104659983.0.g0f105de → 0.1.281-dev.100104666556.0.g558f98c

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,17 @@
1
+ // Server-resolved sandbox policy and correlation. These values never select an
2
+ // upload destination, authenticate a caller, or alter personal-device logging.
3
+ export function sandboxObservationContext(env = process.env, role) {
4
+ if (env.CODEM_SANDBOX_VERSION !== "resource") return {};
5
+ const fields = {};
6
+ for (const [name, key] of [["CODEM_RESOURCE_ID", "resource_id"], ["CODEM_RESOURCE_ENV", "resource_env"], ["CODEM_RESOURCE_OPERATION_ID", "operation_id"]]) {
7
+ const value = env[name];
8
+ if (typeof value === "string" && /^[A-Za-z0-9_.:-]{1,160}$/u.test(value)) fields[key] = value;
9
+ }
10
+ return fields;
11
+ }
12
+
13
+ export function sandboxLogUploadAllowed(env = process.env, role) {
14
+ const sandbox = role === "sandbox" || env.CODEM_SANDBOX_VERSION === "resource" || env.CODEM_SESSION_SOURCE === "sandbox";
15
+ const policy = env.CODEM_SANDBOX_LOG_UPLOAD_ENABLED;
16
+ return !sandbox || policy === undefined || policy === "1";
17
+ }
@@ -1,140 +1,6 @@
1
1
  import https from "node:https";
2
2
  import { gzip } from "node:zlib";
3
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
4
 
139
5
  // PC Custom Log / Custom Event wire format, verified against Parfait 1.7.0.0's
140
6
  // public IUploader callback. This is not the Slardar Web/BID protocol. Keep the
@@ -1,49 +0,0 @@
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
- }
@@ -1,17 +0,0 @@
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
- }