diff --git a/packages/sdk/package.json b/packages/sdk/package.json index b6c5692d..acd5d656 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -25,7 +25,7 @@ "./network": "./src/network.ts" }, "scripts": { - "test": "node --import tsx --test src/asset-config.test.ts src/client.test.ts src/conservation.test.ts src/encoding.test.ts src/encrypted-blob.test.ts src/errors.test.ts src/export-receipt.test.ts src/ids.test.ts src/mainnet-readiness.test.ts src/network.test.ts src/preflight.test.ts src/public-api-snapshot.test.ts src/receipt.test.ts src/redact.test.ts src/round-status.test.ts src/status-client.test.ts src/verify.test.ts", + "test": "node --import tsx --test src/asset-config.test.ts src/client.test.ts src/conservation.test.ts src/encoding.test.ts src/encrypted-blob.test.ts src/errors.test.ts src/export-receipt.test.ts src/ids.test.ts src/mainnet-readiness.test.ts src/network.test.ts src/preflight.test.ts src/public-api-snapshot.test.ts src/receipt.test.ts src/redact.test.ts src/round-status.test.ts src/status-client.test.ts src/truncate.test.ts src/verify.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index bbf99fee..787298f0 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -165,6 +165,7 @@ export { type BidReceiptEntry, RECEIPT_VERSION, } from "./receipt.js"; +export { truncateStrings, truncateError, type TruncateOptions } from "./truncate.js"; export { redactReceipt, type RedactOptions, diff --git a/packages/sdk/src/public-api-snapshot.test.ts b/packages/sdk/src/public-api-snapshot.test.ts index 0a9e6df6..97ae3dec 100644 --- a/packages/sdk/src/public-api-snapshot.test.ts +++ b/packages/sdk/src/public-api-snapshot.test.ts @@ -106,6 +106,8 @@ const EXPECTED_EXPORTS = [ "runMainnetReadiness", "summarizeDeploymentValue", "serializeReceipt", + "truncateError", + "truncateStrings", "tryDecodeBase64", "tryDecodeHex", "validateAssetConfig", diff --git a/packages/sdk/src/truncate.test.ts b/packages/sdk/src/truncate.test.ts new file mode 100644 index 00000000..d54e3f26 --- /dev/null +++ b/packages/sdk/src/truncate.test.ts @@ -0,0 +1,163 @@ +// Copyright (c) 2026 Sub Rosa contributors +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; + +import { + DEFAULT_MAX_LENGTH, + DEFAULT_TRUNCATED_SUFFIX, + truncateError, + truncateStrings, + type TruncateOptions, +} from "./truncate.js"; + +function asRecord(value: unknown): Record { + assert.ok(value !== null && typeof value === "object" && !Array.isArray(value)); + return value as Record; +} + +function asArray(value: unknown): unknown[] { + assert.ok(Array.isArray(value)); + return value; +} + +describe("truncateStrings", () => { + it("keeps the first maxLength characters and marks the truncated value", () => { + const result = truncateStrings("Hello, this is a very long string", { maxLength: 10 }); + assert.equal(result, "Hello, thi..."); + assert.equal(result.length, 13); + }); + + it("leaves strings at or below maxLength untouched", () => { + assert.equal(truncateStrings("Short", { maxLength: 10 }), "Short"); + assert.equal(truncateStrings("ExactlyTen", { maxLength: 10 }), "ExactlyTen"); + }); + + it("does not include the discarded remainder in the result", () => { + const secretTail = "sk_live_do_not_log_me"; + const result = truncateStrings(`prefix-${secretTail}`, { maxLength: 6 }); + assert.equal(result, "prefix..."); + assert.ok(!result.includes("sk_live")); + }); + + it("uses the documented default limit and marker", () => { + const long = "a".repeat(DEFAULT_MAX_LENGTH); + assert.equal(truncateStrings(long), long); + assert.equal( + truncateStrings(`${long}b`), + `${long}${DEFAULT_TRUNCATED_SUFFIX}`, + ); + }); + + it("applies the limit to nested object fields at every depth", () => { + const input = { + round: 42, + message: "Hello world", + nested: { deep: { deeper: "A very deep nested string that needs truncation" } }, + }; + const result = asRecord(truncateStrings(input, { maxLength: 10 })); + assert.equal(result.round, 42); + assert.equal(result.message, "Hello worl..."); + assert.equal(asRecord(asRecord(result.nested).deep).deeper, "A very dee..."); + }); + + it("truncates strings inside arrays and nested arrays", () => { + const input = ["short", "A very long string that should be truncated", ["Nested array value that is long"]]; + const result = asArray(truncateStrings(input, { maxLength: 10 })); + assert.deepEqual(result[0], "short"); + assert.deepEqual(result[1], "A very lon..."); + assert.deepEqual(asArray(result[2])[0], "Nested arr..."); + }); + + it("passes non-string values through unchanged", () => { + const input = { nullValue: null, undefinedValue: undefined, count: 7, enabled: true, total: 10n }; + assert.deepEqual(truncateStrings(input, { maxLength: 1 }), input); + assert.equal(truncateStrings(null, { maxLength: 1 }), null); + assert.equal(truncateStrings(undefined, { maxLength: 1 }), undefined); + assert.equal(truncateStrings(1234, { maxLength: 1 }), 1234); + }); + + it("handles empty strings", () => { + assert.equal(truncateStrings("", { maxLength: 0 }), ""); + }); + + it("supports a zero limit by keeping only the marker", () => { + assert.equal(truncateStrings("anything", { maxLength: 0 }), "..."); + }); + + it("honours a custom marker", () => { + const options: TruncateOptions = { maxLength: 10, truncatedSuffix: "[TRUNCATED]" }; + assert.equal(truncateStrings("This is a test string", options), "This is a [TRUNCATED]"); + }); + + it("rejects an invalid maxLength", () => { + assert.throws(() => truncateStrings("x", { maxLength: -1 }), RangeError); + assert.throws(() => truncateStrings("x", { maxLength: 1.5 }), RangeError); + assert.throws(() => truncateStrings("x", { maxLength: Number.NaN }), RangeError); + }); +}); + +describe("truncateError", () => { + it("truncates the message and keeps the error name", () => { + const err = new Error("This is a test error message that is long enough to truncate"); + const result = truncateError(err, { maxLength: 20 }); + assert.equal(result.name, "Error"); + assert.equal(result.message, "This is a test error..."); + }); + + it("preserves a custom error subclass name", () => { + class DomainError extends Error { + override name = "DomainError"; + } + const result = truncateError(new DomainError("closed"), { maxLength: 20 }); + assert.equal(result.name, "DomainError"); + assert.equal(result.message, "closed"); + }); + + it("copies own properties of every type", () => { + const err = Object.assign(new Error("test message"), { code: "ERR_TEST", attempt: 2 }); + const result = truncateError(err, { maxLength: 100 }); + assert.equal(result.code, "ERR_TEST"); + assert.equal(result.attempt, 2); + }); + + it("truncates custom string properties", () => { + const err = Object.assign(new Error("test"), { detail: "A custom detail string that is too long" }); + assert.equal(truncateError(err, { maxLength: 8 }).detail, "A custom..."); + }); + + it("truncates nested properties and causes", () => { + const cause = new Error("the underlying provider failure"); + const err = Object.assign(new Error("wrapper"), { + nested: { deep: "A very deeply nested string that needs truncation" }, + cause, + }); + const result = truncateError(err, { maxLength: 15 }); + assert.equal(asRecord(result.nested).deep, "A very deeply n..."); + const serializedCause = asRecord(nestedCause(result)); + assert.equal(serializedCause.name, "Error"); + assert.equal(serializedCause.message, "the underlying ..."); + }); + + it("omits the stack", () => { + const result = truncateError(new Error("boom"), { maxLength: 100 }); + assert.ok(!("stack" in result)); + }); + + it("handles an empty message", () => { + const result = truncateError(new Error(""), { maxLength: 10 }); + assert.equal(result.message, ""); + assert.equal(result.name, "Error"); + }); + + it("handles errors inside arrays", () => { + const result = truncateStrings([new Error("first"), new Error("second")], { maxLength: 100 }); + const [first, second] = asArray(result); + assert.equal(asRecord(first).message, "first"); + assert.equal(asRecord(second).message, "second"); + }); +}); + +function nestedCause(result: Record): unknown { + assert.ok("cause" in result, "cause must be preserved"); + return result.cause; +} diff --git a/packages/sdk/src/truncate.ts b/packages/sdk/src/truncate.ts new file mode 100644 index 00000000..1ef3446d --- /dev/null +++ b/packages/sdk/src/truncate.ts @@ -0,0 +1,99 @@ +// Copyright (c) 2026 Sub Rosa contributors +/** + * Truncates oversized string fields in structured data (objects, arrays and + * error objects) so a single large upstream error or malformed input cannot + * inflate log volume or carry more sensitive context than the caller intended. + * + * Acceptance criteria for issue #667: + * - A configurable maximum serialized string length. + * - Truncated values are marked without retaining the discarded content. + * - Nested fields are handled consistently. + * - Tests cover strings, arrays and error objects. + * + * A string is truncated only when it is strictly longer than `maxLength`. The + * retained prefix is at most `maxLength` characters and the marker records that + * content was dropped. The discarded tail is never copied into the result. + */ + +/** Marker used when the caller does not supply `truncatedSuffix`. */ +export const DEFAULT_TRUNCATED_SUFFIX = "..."; + +/** Retained characters per string when the caller does not supply `maxLength`. */ +export const DEFAULT_MAX_LENGTH = 100; + +export interface TruncateOptions { + /** Maximum number of characters retained from any single string. Defaults to 100. */ + maxLength?: number; + /** Marker appended to a truncated string. Defaults to "...". */ + truncatedSuffix?: string; +} + +function resolveOptions(options: TruncateOptions): Required { + const maxLength = options.maxLength ?? DEFAULT_MAX_LENGTH; + if (!Number.isInteger(maxLength) || maxLength < 0) { + throw new RangeError(`maxLength must be a non-negative integer; received ${String(options.maxLength)}`); + } + return { + maxLength, + truncatedSuffix: options.truncatedSuffix ?? DEFAULT_TRUNCATED_SUFFIX, + }; +} + +function truncateString(value: string, maxLength: number, truncatedSuffix: string): string { + return value.length > maxLength ? value.slice(0, maxLength) + truncatedSuffix : value; +} + +/** + * Recursively truncates string values in a data structure. + * + * - Strings longer than `maxLength` keep their first `maxLength` characters and + * gain the marker; the discarded remainder is dropped. + * - Arrays and plain objects are recursed into, preserving their shape and order. + * - Every other value (null, undefined, numbers, booleans, bigint) is returned as + * it was, so callers can pass a heterogeneous log context directly. + * + * @throws RangeError when `maxLength` is negative or not an integer. + */ +export function truncateStrings(value: string, options?: TruncateOptions): string; +export function truncateStrings(value: unknown, options?: TruncateOptions): unknown; +export function truncateStrings(data: unknown, options: TruncateOptions = {}): unknown { + const { maxLength, truncatedSuffix } = resolveOptions(options); + + if (typeof data === "string") return truncateString(data, maxLength, truncatedSuffix); + // Error members are non-enumerable, so an Error needs its own pass before the + // generic object walk; callers often nest errors inside log context. + if (data instanceof Error) return truncateError(data, options); + if (Array.isArray(data)) return data.map((item) => truncateStrings(item, options)); + if (data !== null && typeof data === "object") { + const result: Record = {}; + for (const [key, value] of Object.entries(data)) { + result[key] = truncateStrings(value, options); + } + return result; + } + return data; +} + +/** + * Serializes an Error for logging with every string field truncated. + * + * Own enumerable properties are kept (including `cause` and custom fields such + * as `code`), `name` and `message` are preserved, and `stack` is omitted: it is + * the largest and most incidental field of a logged error and its content is + * already represented by the message. + * + * @throws RangeError when `maxLength` is negative or not an integer. + */ +export function truncateError(err: Error, options: TruncateOptions = {}): Record { + const { maxLength, truncatedSuffix } = resolveOptions(options); + const result: Record = { + name: truncateString(err.name, maxLength, truncatedSuffix), + message: truncateString(err.message, maxLength, truncatedSuffix), + }; + + for (const [key, value] of Object.entries(err)) { + if (key === "name" || key === "message" || key === "stack") continue; + result[key] = truncateStrings(value, { maxLength, truncatedSuffix }); + } + return result; +}