Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
1 change: 1 addition & 0 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ export {
type BidReceiptEntry,
RECEIPT_VERSION,
} from "./receipt.js";
export { truncateStrings, truncateError, type TruncateOptions } from "./truncate.js";
export {
redactReceipt,
type RedactOptions,
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/public-api-snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ const EXPECTED_EXPORTS = [
"runMainnetReadiness",
"summarizeDeploymentValue",
"serializeReceipt",
"truncateError",
"truncateStrings",
"tryDecodeBase64",
"tryDecodeHex",
"validateAssetConfig",
Expand Down
163 changes: 163 additions & 0 deletions packages/sdk/src/truncate.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> {
assert.ok(value !== null && typeof value === "object" && !Array.isArray(value));
return value as Record<string, unknown>;
}

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<string, unknown>): unknown {
assert.ok("cause" in result, "cause must be preserved");
return result.cause;
}
99 changes: 99 additions & 0 deletions packages/sdk/src/truncate.ts
Original file line number Diff line number Diff line change
@@ -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<TruncateOptions> {
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<string, unknown> = {};
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<string, unknown> {
const { maxLength, truncatedSuffix } = resolveOptions(options);
const result: Record<string, unknown> = {
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;
}