Skip to content
Merged
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
1 change: 0 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
**/cache
**/coverage
**/dist
**/lib
**/node_modules
**/out
**/types
Expand Down
88 changes: 45 additions & 43 deletions packages/sdk-core/src/lib/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,34 @@ import { NetworkError, ValidationError } from "../core/errors.js";
* Handles deeply nested objects and null values correctly.
*/
export function stableStringify(obj: unknown): string | undefined {
if (obj === undefined || typeof obj === "function" || typeof obj === "symbol") {
return undefined;
}
if (obj === null || typeof obj !== "object") {
return JSON.stringify(obj);
}
if (obj === undefined || typeof obj === "function" || typeof obj === "symbol") {
return undefined;
}
if (obj === null || typeof obj !== "object") {
return JSON.stringify(obj);
}

if (Array.isArray(obj)) {
return JSON.stringify(obj.map((item) => {
const val = stableStringify(item);
return val === undefined ? null : JSON.parse(val);
}));
}
if (Array.isArray(obj)) {
return JSON.stringify(
obj.map((item) => {
const val = stableStringify(item);
return val === undefined ? null : JSON.parse(val);
}),
);
}

const sortedKeys = Object.keys(obj as object).sort();
const sortedObj: Record<string, unknown> = {};
const sortedKeys = Object.keys(obj as object).sort();
const sortedObj: Record<string, unknown> = {};

for (const key of sortedKeys) {
const value = (obj as Record<string, unknown>)[key];
const str = stableStringify(value);
// Skip undefined or non-serializable values
if (str === undefined) continue;
sortedObj[key] = JSON.parse(str);
}
for (const key of sortedKeys) {
const value = (obj as Record<string, unknown>)[key];
const str = stableStringify(value);
// Skip undefined or non-serializable values
if (str === undefined) continue;
sortedObj[key] = JSON.parse(str);
}

return JSON.stringify(sortedObj);
return JSON.stringify(sortedObj);
}

/**
Expand All @@ -46,30 +48,30 @@ export function stableStringify(obj: unknown): string | undefined {
* @throws {ValidationError} If content is not serializable (e.g. undefined, function, symbol)
*/
export async function sha256Hash(content: unknown): Promise<string> {
// Use stable stringification to ensure deterministic output
const jsonString = stableStringify(content);
// Use stable stringification to ensure deterministic output
const jsonString = stableStringify(content);

if (jsonString === undefined) {
throw new ValidationError(`Content illegal: not serializable (type: ${typeof content})`);
}
if (jsonString === undefined) {
throw new ValidationError(`Content illegal: not serializable (type: ${typeof content})`);
}

const msgBuffer = new TextEncoder().encode(jsonString);
const msgBuffer = new TextEncoder().encode(jsonString);

if (typeof crypto !== "undefined" && crypto.subtle) {
// Browser / Modern Node.js
const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
} else {
// Fallback for older environments or specific setups if global crypto isn't available
try {
// Dynamic import to avoid breaking browser builds if bundler doesn't handle it
if (typeof crypto !== "undefined" && crypto.subtle) {
// Browser / Modern Node.js
const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
} else {
// Fallback for older environments or specific setups if global crypto isn't available
try {
// Dynamic import to avoid breaking browser builds if bundler doesn't handle it

const { createHash } = await import("node:crypto");
const hash = createHash("sha256").update(jsonString).digest("hex");
return hash;
} catch (e) {
throw new NetworkError("SHA-256 hashing not supported in this environment", e);
}
const { createHash } = await import("node:crypto");
const hash = createHash("sha256").update(jsonString).digest("hex");
return hash;
} catch (e) {
throw new NetworkError("SHA-256 hashing not supported in this environment", e);
}
}
}
125 changes: 62 additions & 63 deletions packages/sdk-core/tests/lib/crypto.test.ts
Original file line number Diff line number Diff line change
@@ -1,82 +1,81 @@

import { describe, it, expect } from "vitest";
import { stableStringify } from "../../src/lib/crypto.js";

describe("stableStringify", () => {
it("should stringify primitives", () => {
expect(stableStringify(1)).toBe("1");
expect(stableStringify("test")).toBe('"test"');
expect(stableStringify(true)).toBe("true");
expect(stableStringify(null)).toBe("null");
});
it("should stringify primitives", () => {
expect(stableStringify(1)).toBe("1");
expect(stableStringify("test")).toBe('"test"');
expect(stableStringify(true)).toBe("true");
expect(stableStringify(null)).toBe("null");
});

it("should sort object keys", () => {
const obj = { c: 3, a: 1, b: 2 };
expect(stableStringify(obj)).toBe('{"a":1,"b":2,"c":3}');
});
it("should sort object keys", () => {
const obj = { c: 3, a: 1, b: 2 };
expect(stableStringify(obj)).toBe('{"a":1,"b":2,"c":3}');
});

it("should sort nested object keys", () => {
const obj = {
z: { y: 2, x: 1 },
a: { c: 3, b: 4 },
};
expect(stableStringify(obj)).toBe('{"a":{"b":4,"c":3},"z":{"x":1,"y":2}}');
});
it("should sort nested object keys", () => {
const obj = {
z: { y: 2, x: 1 },
a: { c: 3, b: 4 },
};
expect(stableStringify(obj)).toBe('{"a":{"b":4,"c":3},"z":{"x":1,"y":2}}');
});

it("should preserve array order", () => {
const arr = [3, 1, 2];
expect(stableStringify(arr)).toBe("[3,1,2]");
});
it("should preserve array order", () => {
const arr = [3, 1, 2];
expect(stableStringify(arr)).toBe("[3,1,2]");
});

it("should sort objects inside arrays", () => {
const arr = [
{ b: 2, a: 1 },
{ d: 4, c: 3 },
];
expect(stableStringify(arr)).toBe('[{"a":1,"b":2},{"c":3,"d":4}]');
});
it("should sort objects inside arrays", () => {
const arr = [
{ b: 2, a: 1 },
{ d: 4, c: 3 },
];
expect(stableStringify(arr)).toBe('[{"a":1,"b":2},{"c":3,"d":4}]');
});

it("should ignore undefined, functions, and symbols", () => {
const obj = {
a: 1,
b: undefined,
c: () => { },
d: Symbol("test"),
e: 2,
};
expect(stableStringify(obj)).toBe('{"a":1,"e":2}');
});
it("should ignore undefined, functions, and symbols", () => {
const obj = {
a: 1,
b: undefined,
c: () => {},
d: Symbol("test"),
e: 2,
};
expect(stableStringify(obj)).toBe('{"a":1,"e":2}');
});

it("should return undefined for non-serializable top-level inputs", () => {
expect(stableStringify(undefined)).toBeUndefined();
expect(stableStringify(() => { })).toBeUndefined();
expect(stableStringify(Symbol("test"))).toBeUndefined();
});
it("should return undefined for non-serializable top-level inputs", () => {
expect(stableStringify(undefined)).toBeUndefined();
expect(stableStringify(() => {})).toBeUndefined();
expect(stableStringify(Symbol("test"))).toBeUndefined();
});

it("should handle mixed complex structures", () => {
const obj = {
id: 1,
meta: {
tags: ["b", "a"], // Array order preserved
info: { y: 2, x: 1 } // Object keys sorted
}
};
expect(stableStringify(obj)).toBe('{"id":1,"meta":{"info":{"x":1,"y":2},"tags":["b","a"]}}');
});
it("should handle mixed complex structures", () => {
const obj = {
id: 1,
meta: {
tags: ["b", "a"], // Array order preserved
info: { y: 2, x: 1 }, // Object keys sorted
},
};
expect(stableStringify(obj)).toBe('{"id":1,"meta":{"info":{"x":1,"y":2},"tags":["b","a"]}}');
});
});

import { sha256Hash } from "../../src/lib/crypto.js";
import { ValidationError } from "../../src/core/errors.js";

describe("sha256Hash", () => {
it("should throw ValidationError for undefined input", async () => {
await expect(sha256Hash(undefined)).rejects.toThrow(ValidationError);
await expect(sha256Hash(undefined)).rejects.toThrow(/Content illegal: not serializable/);
});
it("should throw ValidationError for undefined input", async () => {
await expect(sha256Hash(undefined)).rejects.toThrow(ValidationError);
await expect(sha256Hash(undefined)).rejects.toThrow(/Content illegal: not serializable/);
});

it("should throw ValidationError for function input", async () => {
const func = () => { };
await expect(sha256Hash(func)).rejects.toThrow(ValidationError);
await expect(sha256Hash(func)).rejects.toThrow(/Content illegal: not serializable/);
});
it("should throw ValidationError for function input", async () => {
const func = () => {};
await expect(sha256Hash(func)).rejects.toThrow(ValidationError);
await expect(sha256Hash(func)).rejects.toThrow(/Content illegal: not serializable/);
});
});
Loading