diff --git a/packages/logging/src/index.test.cjs b/packages/logging/src/index.test.cjs index 3df7b568..433a4532 100644 --- a/packages/logging/src/index.test.cjs +++ b/packages/logging/src/index.test.cjs @@ -35,8 +35,17 @@ test('serializes errors, causes, bigint and circular context safely',()=>{ assert.equal(record.context.error.message,'failure');assert.equal(record.context.error.cause.message,'root'); }); test('redacts URL credentials and query tokens in errors',()=>{ - const {logger,records}=capture();logger.error('failed',new Error('https://user:secret@rpc.example/?token=hidden')); - const text=JSON.stringify(records);assert.ok(!text.includes('user:secret'));assert.ok(!text.includes('token=hidden')); + const {logger,records}=capture();logger.error('failed',new Error('https://user:secret@rpc.example/?token=hidden')); + const text=JSON.stringify(records);assert.ok(!text.includes('user:secret'));assert.ok(!text.includes('token=hidden')); +}); +test('redacts URL query strings and fragments',()=>{ + const {logger,records}=capture();logger.error('failed','https://api.example.com/path?query=value¶m=test#fragment'); + const text=JSON.stringify(records);assert.ok(!text.includes('query=value'));assert.ok(!text.includes('param=test'));assert.ok(!text.includes('#fragment')); + assert.ok(text.includes('[REDACTED]')); +}); +test('redacts URL credentials and query strings together',()=>{ + const {logger,records}=capture();logger.error('failed','https://user:pass@api.example.com/path?query=value#fragment'); + const text=JSON.stringify(records);assert.ok(!text.includes('user:pass'));assert.ok(!text.includes('query=value'));assert.ok(!text.includes('#fragment')); }); test('hostile accessors, circular arrays, deep context and broken sinks do not throw',()=>{ const {logger,records}=capture();const a=[];a.push(a); diff --git a/packages/logging/src/serialization.cjs b/packages/logging/src/serialization.cjs index 31c75c8c..05398c79 100644 --- a/packages/logging/src/serialization.cjs +++ b/packages/logging/src/serialization.cjs @@ -5,8 +5,14 @@ const sensitive = (key) => /secret|token|password|passwd|privatekey|credential|c function scrubText(value, secrets) { let text = value - .replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi, '$1[REDACTED]@') - .replace(/([?&](?:[^=&\s]*(?:secret|token|password|credential|api[_-]?key)[^=&\s]*)=)[^&#\s]*/gi, '$1[REDACTED]') + // Redact username:password@ in URLs, and also redact query string and fragment + .replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@([^\s?#]+)(\?[^\s#]*)?(#[^\s]*)?/gi, '$1[REDACTED]@$2[REDACTED][REDACTED]') + // Also handle URLs without credentials but with query/fragment + .replace(/(https?:\/\/[^\s?#]+)(\?[^\s#]*)?(#[^\s]*)?/gi, (match, prefix, query, fragment) => { + // Don't double-redact if already handled above + if (match.includes('[REDACTED]@')) return match; + return prefix + (query ? '[REDACTED]' : '') + (fragment ? '[REDACTED]' : ''); + }) .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/_=.-]+/gi, '$1 [REDACTED]') .replace(/((?:[\w-]*(?:secret|token|password|credential|authorization|cookie|api[_-]?key)[\w-]*)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi, '$1[REDACTED]') .replace(/\bS[A-Z2-7]{55}\b/g, REDACTED) @@ -63,4 +69,4 @@ function redactValue(value) { exports.redactValue = redactValue; exports.collectSecrets = collectSecrets; exports.scrubText = scrubText; -exports.serialize = serialize; +exports.serialize = serialize; \ No newline at end of file diff --git a/packages/sdk/src/errors.ts b/packages/sdk/src/errors.ts index b7fb3748..abc04206 100644 --- a/packages/sdk/src/errors.ts +++ b/packages/sdk/src/errors.ts @@ -440,3 +440,45 @@ export class SubRosaTimeoutError extends Error { this.pollIntervalMs = params.pollIntervalMs; } } + +export type PaginationErrorReason = + | "invalid_page" + | "repeated_bidder" + | "repeated_cursor"; + +export interface SubRosaPaginationErrorParams { + roundId: bigint; + reason: PaginationErrorReason; + bidder?: string; +} + +/** + * Raised when paginating bidders fails due to an invalid or inconsistent page. + * The error carries the round ID and a machine-readable reason so callers can + * handle specific failure modes (e.g., retry vs. abort). + */ +export class SubRosaPaginationError extends Error { + readonly name = "SubRosaPaginationError"; + readonly roundId: bigint; + readonly reason: PaginationErrorReason; + readonly bidder?: string; + + constructor(params: SubRosaPaginationErrorParams) { + let message: string; + switch (params.reason) { + case "invalid_page": + message = `round ${params.roundId}: page token is invalid or out of range`; + break; + case "repeated_bidder": + message = `round ${params.roundId}: bidder ${params.bidder ?? "unknown"} appears multiple times in the index`; + break; + case "repeated_cursor": + message = `round ${params.roundId}: pagination cursor did not advance`; + break; + } + super(message); + this.roundId = params.roundId; + this.reason = params.reason; + this.bidder = params.bidder; + } +} \ No newline at end of file diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index bbf99fee..09055c50 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -37,6 +37,7 @@ export { SubRosaManifestError, SubRosaMissingReturnValueError, SubRosaNetworkMismatchError, + SubRosaPaginationError, SubRosaPreflightError, SubRosaSessionMismatchError, SubRosaSubmitError, @@ -49,8 +50,10 @@ export type { ManifestErrorParams, NetworkMismatchErrorParams, NetworkMismatchReason, + PaginationErrorReason, PreflightFailureKind, SubRosaPreflightErrorParams, + SubRosaPaginationErrorParams, TimeoutErrorParams, } from "./errors.js"; @@ -138,6 +141,7 @@ export { hasBlockingFailures, nativeXlmSacId, parseMainnetReadinessFixture, + parseMicroStroops, readLiveDeployment, runMainnetReadiness, summarizeDeploymentValue, diff --git a/packages/sdk/src/public-api-snapshot.test.ts b/packages/sdk/src/public-api-snapshot.test.ts index 0a9e6df6..95a69194 100644 --- a/packages/sdk/src/public-api-snapshot.test.ts +++ b/packages/sdk/src/public-api-snapshot.test.ts @@ -41,6 +41,7 @@ const EXPECTED_EXPORTS = [ "SubRosaMissingReturnValueError", "SubRosaNetworkMismatchError", "SubRosaNetworkPassphraseMismatchError", + "SubRosaPaginationError", "SubRosaPreflightError", "SubRosaSessionMismatchError", "SubRosaSubmitError", @@ -87,6 +88,7 @@ const EXPECTED_EXPORTS = [ "networkDisplayName", "parseMainnetManifest", "parseMainnetReadinessFixture", + "parseMicroStroops", "readLiveDeployment", "networkFingerprint", "networkPassphrasesMatch", @@ -125,4 +127,4 @@ describe("SDK public API snapshot", () => { const expected = [...EXPECTED_EXPORTS].sort(); assert.deepEqual(actual, expected); }); -}); +}); \ No newline at end of file diff --git a/packages/tlock/package.json b/packages/tlock/package.json index ba82bb3b..a4ab487e 100644 --- a/packages/tlock/package.json +++ b/packages/tlock/package.json @@ -20,9 +20,9 @@ }, "main": "src/index.ts", "scripts": { - "test": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/seal.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts", + "test": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/seal.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts src/http-client.test.ts", "test:quicknet": "node --import tsx --test src/quicknet.test.ts", - "test:unit": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts", + "test:unit": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts src/http-client.test.ts", "test:seal": "node --import tsx --test src/seal.test.ts", "recover:identities": "node --import tsx src/recover-identities.cli.ts", "typecheck": "tsc --noEmit -p tsconfig.json" diff --git a/packages/tlock/src/ciphertext.test.ts b/packages/tlock/src/ciphertext.test.ts index 506814cb..5d2dc642 100644 --- a/packages/tlock/src/ciphertext.test.ts +++ b/packages/tlock/src/ciphertext.test.ts @@ -42,6 +42,9 @@ const offlineClient = { const ROUND = 1_234_567; const VALUE = 8_675_309n; const NONCE = new Uint8Array(NONCE_BYTES).fill(0x2a); +// Test fixture contract/bidder IDs (valid Soroban strkeys) +const TEST_CONTRACT_ID = "C0000000000000000000000000000000000000000000000000000000000000000"; +const TEST_BIDDER_ID = "GB0000000000000000000000000000000000000000000000000000000000000000"; /** Seal a bid offline. Each call re-encrypts, so ciphertexts differ. */ async function sealFixture(overrides?: { @@ -50,9 +53,12 @@ async function sealFixture(overrides?: { round?: number; }): Promise { return sealBid({ + contractId: TEST_CONTRACT_ID, + bidderId: TEST_BIDDER_ID, value: overrides?.value ?? VALUE, nonce: overrides?.nonce ?? NONCE, round: overrides?.round ?? ROUND, + revealRound: ROUND, client: offlineClient, }); } diff --git a/packages/tlock/src/http-client.test.ts b/packages/tlock/src/http-client.test.ts new file mode 100644 index 00000000..186f35bc --- /dev/null +++ b/packages/tlock/src/http-client.test.ts @@ -0,0 +1,70 @@ +// Copyright (c) 2026 Sub Rosa contributors +// Tests for HTTP client content-type validation. + +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + validateContentType, + ValidatingHttpChainClient, + createValidatingQuicknetClient, +} from "./http-client.js"; + +test("validateContentType accepts application/json", () => { + assert.doesNotThrow(() => validateContentType("application/json")); +}); + +test("validateContentType accepts application/json with charset", () => { + assert.doesNotThrow(() => validateContentType("application/json; charset=utf-8")); + assert.doesNotThrow(() => validateContentType("application/json;charset=utf-8")); + assert.doesNotThrow(() => validateContentType("APPLICATION/JSON; CHARSET=UTF-8")); +}); + +test("validateContentType rejects text/html", () => { + assert.throws( + () => validateContentType("text/html"), + /Unexpected Content-Type: expected application\/json, got text\/html/, + ); +}); + +test("validateContentType rejects text/plain", () => { + assert.throws( + () => validateContentType("text/plain"), + /Unexpected Content-Type: expected application\/json, got text\/plain/, + ); +}); + +test("validateContentType rejects application/xml", () => { + assert.throws( + () => validateContentType("application/xml"), + /Unexpected Content-Type: expected application\/json, got application\/xml/, + ); +}); + +test("validateContentType rejects missing content-type", () => { + assert.throws( + () => validateContentType(null), + /Missing Content-Type header in Drand response/, + ); +}); + +test("validateContentType rejects empty content-type", () => { + assert.throws( + () => validateContentType(""), + /Unexpected Content-Type: expected application\/json, got /, + ); +}); + +test("createValidatingQuicknetClient returns a ChainClient", () => { + const client = createValidatingQuicknetClient(); + assert.ok(typeof client.get === "function"); + assert.ok(typeof client.latest === "function"); + assert.ok(typeof client.chain === "function"); +}); + +test("ValidatingHttpChainClient validates content-type before parsing", async () => { + // This test would require a mock server. We test the validator directly above. + // The client integration is tested by the quicknet tests using the real network. + const client = createValidatingQuicknetClient(); + assert.ok(client instanceof ValidatingHttpChainClient); +}); \ No newline at end of file diff --git a/packages/tlock/src/http-client.ts b/packages/tlock/src/http-client.ts new file mode 100644 index 00000000..f4aae669 --- /dev/null +++ b/packages/tlock/src/http-client.ts @@ -0,0 +1,101 @@ +// Copyright (c) 2026 Sub Rosa contributors +// HTTP client with content-type validation for Drand responses. + +import { + Chain, + ChainClient, + ChainOptions, + defaultChainOptions, + RandomnessBeacon, + HttpCachingChain, +} from "drand-client"; + +const JSON_CONTENT_TYPE = "application/json"; + +export interface HttpOptions { + userAgent?: string; + headers?: Record; +} + +export const defaultHttpOptions: HttpOptions = { + userAgent: `sub-rosa-tlock/0.1.0`, +}; + +function parseMediaType(contentType: string): { type: string; charset?: string } { + const parts = contentType.split(";").map((p) => p.trim().toLowerCase()); + const type = parts[0]; + const charset = parts.find((p) => p.startsWith("charset="))?.split("=")[1]; + return { type, charset }; +} + +export function validateContentType(contentType: string | null): void { + if (contentType === null || contentType === undefined) { + throw new Error("Missing Content-Type header in Drand response"); + } + const { type } = parseMediaType(contentType); + if (type !== JSON_CONTENT_TYPE) { + throw new Error(`Unexpected Content-Type: expected ${JSON_CONTENT_TYPE}, got ${type}`); + } +} + +export interface ValidatingHttpOptions extends HttpOptions { + validateContentType?: (contentType: string | null) => void; +} + +export class ValidatingHttpChainClient implements ChainClient { + public readonly options: ChainOptions; + + constructor( + private readonly chainInstance: Chain, + options: ChainOptions = defaultChainOptions, + private readonly httpOptions: ValidatingHttpOptions = defaultHttpOptions, + ) { + this.options = options; + } + + async get(roundNumber: number): Promise { + const url = this.withCachingParams(`${this.chainInstance.baseUrl}/public/${roundNumber}`); + return await this.jsonOrError(url); + } + + async latest(): Promise { + const url = this.withCachingParams(`${this.chainInstance.baseUrl}/public/latest`); + return await this.jsonOrError(url); + } + + chain(): Chain { + return this.chainInstance; + } + + private withCachingParams(url: string): string { + if (this.options.noCache) { + return `${url}?${Date.now()}`; + } + return url; + } + + private async jsonOrError(url: string): Promise { + const headers = { ...this.httpOptions.headers }; + if (this.httpOptions.userAgent) { + headers["User-Agent"] = this.httpOptions.userAgent; + } + + const response = await fetch(url, { headers }); + if (!response.ok) { + throw new Error(`Error response fetching ${url} - got ${response.status}`); + } + + const contentType = response.headers.get("content-type"); + const validator = this.httpOptions.validateContentType ?? validateContentType; + validator(contentType); + + return await response.json(); + } +} + +const QUICKNET_CHAIN_URL = "https://api.drand.sh/52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971"; + +export function createValidatingQuicknetClient(options?: ChainOptions): ChainClient { + const chain = new HttpCachingChain(QUICKNET_CHAIN_URL, options ?? defaultChainOptions); + return new ValidatingHttpChainClient(chain, options ?? defaultChainOptions); +} \ No newline at end of file diff --git a/packages/tlock/src/index.ts b/packages/tlock/src/index.ts index 57690243..6067fe2b 100644 --- a/packages/tlock/src/index.ts +++ b/packages/tlock/src/index.ts @@ -61,6 +61,13 @@ export { type DrandClient, } from "./quicknet.js"; +export { + createValidatingQuicknetClient, + ValidatingHttpChainClient, + validateContentType, + type ValidatingHttpOptions, +} from "./http-client.js"; + export { drandSignatureToSoroban, encodeG1Soroban } from "./bls.js"; export { diff --git a/packages/tlock/src/quicknet.ts b/packages/tlock/src/quicknet.ts index a11be6ec..dadfa849 100644 --- a/packages/tlock/src/quicknet.ts +++ b/packages/tlock/src/quicknet.ts @@ -4,13 +4,14 @@ import { fetchBeacon, - quicknetClient, roundAt as drandRoundAt, + type ChainClient, } from "drand-client"; import { drandSignatureToSoroban, verifyDrandSignature } from "./bls.js"; import { assertBeacon, assertChainInfo } from "./validate.js"; import { systemClock, type Clock } from "@sub-rosa/time"; +import { createValidatingQuicknetClient } from "./http-client.js"; export const QUICKNET_HASH = "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971"; @@ -47,10 +48,10 @@ export function assertQuicknetFixture(info: { } } -export type DrandClient = ReturnType; +export type DrandClient = ChainClient; export function quicknet(): DrandClient { - return quicknetClient(); + return createValidatingQuicknetClient(); } export async function chainInfo(client: DrandClient) { diff --git a/packages/tlock/src/seal.test.ts b/packages/tlock/src/seal.test.ts index 55fa7a48..d4b83ae6 100644 --- a/packages/tlock/src/seal.test.ts +++ b/packages/tlock/src/seal.test.ts @@ -113,7 +113,7 @@ test( const round = (await currentRound(client)) - 5; const value = 555n; const nonce = generateNonce(); - const sealed = await sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round, client }); + const sealed = await sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round, revealRound: round, client }); const opened = await openBid(sealed.ciphertext, client); const wrongNonce = new Uint8Array(32).fill(0x42); @@ -126,7 +126,7 @@ test("sealBid rejects a non-positive Drand round", async () => { const client = quicknet(); for (const round of [0, -1, -100]) { await assert.rejects( - sealBid({ contractId: validContractId, bidderId: validBidderId, value: 1n, nonce: generateNonce(), round, client }), + sealBid({ contractId: validContractId, bidderId: validBidderId, value: 1n, nonce: generateNonce(), round, revealRound: round, client }), /round must be a positive integer/, ); } @@ -166,19 +166,19 @@ test("sealBid rejects non-positive or non-integer round numbers", async () => { const value = 100n; await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round: 0, client }), + () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round: 0, revealRound: 0, client }), (err: any) => err instanceof RangeError && /round must be a positive integer/.test(err.message), ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round: -5, client }), + () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round: -5, revealRound: -5, client }), (err: any) => err instanceof RangeError && /round must be a positive integer/.test(err.message), ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round: 1.5, client }), + () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round: 1.5, revealRound: 1.5, client }), (err: any) => err instanceof RangeError && /round must be a positive integer/.test(err.message), ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round: NaN, client }), + () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce, round: NaN, revealRound: NaN, client }), (err: any) => err instanceof RangeError && /round must be a positive integer/.test(err.message), ); }); @@ -189,15 +189,15 @@ test("sealBid rejects invalid nonce lengths", async () => { const round = 1000; await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce: new Uint8Array(16), round, client }), + () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce: new Uint8Array(16), round, revealRound: round, client }), /nonce must be 32 bytes/, ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce: new Uint8Array(31), round, client }), + () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce: new Uint8Array(31), round, revealRound: round, client }), /nonce must be 32 bytes/, ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce: new Uint8Array(33), round, client }), + () => sealBid({ contractId: validContractId, bidderId: validBidderId, value, nonce: new Uint8Array(33), round, revealRound: round, client }), /nonce must be 32 bytes/, ); }); @@ -217,52 +217,52 @@ test("sealBid rejects malformed contractId and bidderId", async () => { const nonce = generateNonce(); await assert.rejects( - () => sealBid({ contractId: "", bidderId: validBidderId, value, nonce, round, client }), + () => sealBid({ contractId: "", bidderId: validBidderId, value, nonce, round, revealRound: round, client }), /contractId/ ); await assert.rejects( - () => sealBid({ contractId: " ", bidderId: validBidderId, value, nonce, round, client }), + () => sealBid({ contractId: " ", bidderId: validBidderId, value, nonce, round, revealRound: round, client }), /contractId/ ); await assert.rejects( - () => sealBid({ contractId: "not-a-contract-id", bidderId: validBidderId, value, nonce, round, client }), + () => sealBid({ contractId: "not-a-contract-id", bidderId: validBidderId, value, nonce, round, revealRound: round, client }), /contractId/ ); await assert.rejects( - () => sealBid({ contractId: "CDAZ5AJPVCJ6R3BQUPYISBSWV77HZ52T7YFWZGTVEEEFW5FVHZAK2JIM!", bidderId: validBidderId, value, nonce, round, client }), + () => sealBid({ contractId: "CDAZ5AJPVCJ6R3BQUPYISBSWV77HZ52T7YFWZGTVEEEFW5FVHZAK2JIM!", bidderId: validBidderId, value, nonce, round, revealRound: round, client }), /contractId/ ); await assert.rejects( - () => sealBid({ contractId: "C123", bidderId: validBidderId, value, nonce, round, client }), + () => sealBid({ contractId: "C123", bidderId: validBidderId, value, nonce, round, revealRound: round, client }), /contractId/ ); await assert.rejects( - () => sealBid({ contractId: "GA3AD2G2SGYLMYVV2F6G5BIFU4X2XZIGA44ZF32ZZ645P4LT4N4EKQHY", bidderId: validBidderId, value, nonce, round, client }), + () => sealBid({ contractId: "GA3AD2G2SGYLMYVV2F6G5BIFU4X2XZIGA44ZF32ZZ645P4LT4N4EKQHY", bidderId: validBidderId, value, nonce, round, revealRound: round, client }), /contractId/ ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: "", value, nonce, round, client }), + () => sealBid({ contractId: validContractId, bidderId: "", value, nonce, round, revealRound: round, client }), /bidderId/ ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: " ", value, nonce, round, client }), + () => sealBid({ contractId: validContractId, bidderId: " ", value, nonce, round, revealRound: round, client }), /bidderId/ ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: "not-a-bidder-id", value, nonce, round, client }), + () => sealBid({ contractId: validContractId, bidderId: "not-a-bidder-id", value, nonce, round, revealRound: round, client }), /bidderId/ ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: "GA3AD2G2SGYLMYVV2F6G5BIFU4X2XZIGA44ZF32ZZ645P4LT4N4EKQHY!", value, nonce, round, client }), + () => sealBid({ contractId: validContractId, bidderId: "GA3AD2G2SGYLMYVV2F6G5BIFU4X2XZIGA44ZF32ZZ645P4LT4N4EKQHY!", value, nonce, round, revealRound: round, client }), /bidderId/ ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: "G123", value, nonce, round, client }), + () => sealBid({ contractId: validContractId, bidderId: "G123", value, nonce, round, revealRound: round, client }), /bidderId/ ); await assert.rejects( - () => sealBid({ contractId: validContractId, bidderId: "CDAZ5AJPVCJ6R3BQUPYISBSWV77HZ52T7YFWZGTVEEEFW5FVHZAK2JIM", value, nonce, round, client }), + () => sealBid({ contractId: validContractId, bidderId: "CDAZ5AJPVCJ6R3BQUPYISBSWV77HZ52T7YFWZGTVEEEFW5FVHZAK2JIM", value, nonce, round, revealRound: round, client }), /bidderId/ ); }); diff --git a/packages/tlock/src/seal.ts b/packages/tlock/src/seal.ts index df2eb4d0..73986230 100644 --- a/packages/tlock/src/seal.ts +++ b/packages/tlock/src/seal.ts @@ -14,6 +14,7 @@ import { commitment, decodeBidPreimage, encodeBidPreimage, NONCE_BYTES } from ". import { sealIdentityForBidder } from "./auditor.js"; import type { DrandClient } from "./quicknet.js"; import { assertContractId, assertBidderId } from "./validate.js"; +import { assertSealRoundWindow } from "./window.js"; const utf8Encode = new TextEncoder(); const utf8Decode = new TextDecoder(); @@ -51,7 +52,7 @@ export function generateNonce(): Uint8Array { } export async function sealBid(params: SealBidParams): Promise { - const { contractId, bidderId, value, nonce, round, client, identity, auditorPublicKey } = params; + const { contractId, bidderId, value, nonce, round, client, revealRound, identity, auditorPublicKey } = params; assertContractId(contractId); assertBidderId(bidderId); diff --git a/services/receipt-cli/src/index.ts b/services/receipt-cli/src/index.ts index 4a8a158e..c203457c 100644 --- a/services/receipt-cli/src/index.ts +++ b/services/receipt-cli/src/index.ts @@ -5,23 +5,28 @@ import { createLogger, writeData } from '@sub-rosa/logging'; const diagnostics = createLogger("services.receipt-cli.src.index"); // receipt-cli — export a round receipt from RPC or verify a local file. -import { readFileSync, writeFileSync } from "node:fs"; +import { readFileSync, writeFileSync, renameSync, statSync, existsSync, constants, openSync, closeSync, unlinkSync, writeSync } from "node:fs"; import { createHash } from "node:crypto"; import { SubRosaClient, parseReceipt, serializeReceipt, verifyReceipt, redactReceipt } from "@sub-rosa/sdk"; import { buildJsonOutput } from "./json-output.js"; +const MAX_OUTPUT_FILE_SIZE = 10 * 1024 * 1024; // 10 MiB + function usage(): never { diagnostics.error("usage-receipt-cli-export-roundid-fetch-receipt-from-rpc", ` Usage: - receipt-cli export Fetch receipt from RPC (uses env config) + receipt-cli export [--force] Fetch receipt from RPC (uses env config) receipt-cli verify [--json] [--verify-artifact-checksum ] - receipt-cli redact [out] Redact sensitive fields for public demo + receipt-cli redact [out] [--force] Redact sensitive fields for public demo Options for "verify": --json Print machine-readable verification output --verify-artifact-checksum Verify the checksum of the required artifact file +Options for "export" and "redact": + --force Overwrite existing non-empty output file + Environment for "export": RPC_URL Soroban RPC endpoint (default: https://soroban-testnet.stellar.org) NETWORK_PASSPHRASE Network passphrase (default: Test SDF Network ; September 2015) @@ -30,7 +35,36 @@ Environment for "export": process.exit(1); } -async function cmdExport(roundIdStr: string) { +function writeFileAtomic(filePath: string, data: string, force: boolean): void { + // Check if file exists and is non-empty + if (existsSync(filePath)) { + const stats = statSync(filePath); + if (stats.size > 0 && !force) { + throw new Error(`Output file "${filePath}" exists and is not empty. Use --force to overwrite.`); + } + if (stats.size > MAX_OUTPUT_FILE_SIZE) { + throw new Error(`Output file "${filePath}" exceeds maximum allowed size of ${MAX_OUTPUT_FILE_SIZE} bytes.`); + } + } + + // Write to temporary file first + const tempPath = `${filePath}.tmp.${process.pid}.${Date.now()}`; + try { + // Write with owner-only permissions (0o600) + const fd = openSync(tempPath, 'w', 0o600); + writeSync(fd, data, 0, 'utf-8'); + closeSync(fd); + + // Atomic rename + renameSync(tempPath, filePath); + } catch (e) { + // Clean up temp file on error + try { unlinkSync(tempPath); } catch {} + throw e; + } +} + +async function cmdExport(roundIdStr: string, force: boolean) { const roundId = BigInt(roundIdStr); const rpcUrl = process.env.RPC_URL ?? "https://soroban-testnet.stellar.org"; const networkPassphrase = @@ -45,7 +79,7 @@ async function cmdExport(roundIdStr: string) { const receipt = await client.exportReceipt(roundId); const json = serializeReceipt(receipt); const filename = `round-${roundId}-receipt.json`; - writeFileSync(filename, json, "utf-8"); + writeFileAtomic(filename, json, force); diagnostics.info("wrote", `Wrote ${filename}`); } @@ -158,7 +192,7 @@ async function cmdVerify(path: string, jsonMode: boolean, artifactPath?: string) process.exit(result.valid ? 0 : 1); } -async function cmdRedact(inputPath: string, outputPath?: string) { +async function cmdRedact(inputPath: string, outputPath?: string, force: boolean = false) { let json: string; try { json = readFileSync(inputPath, "utf-8"); @@ -178,7 +212,7 @@ async function cmdRedact(inputPath: string, outputPath?: string) { const redacted = redactReceipt(receipt); const out = serializeReceipt(redacted); const outPath = outputPath ?? inputPath.replace(/\.json$/, ".redacted.json"); - writeFileSync(outPath, out, "utf-8"); + writeFileAtomic(outPath, out, force); diagnostics.info("wrote-redacted-receipt-to", `Wrote redacted receipt to ${outPath}`); } @@ -188,9 +222,12 @@ async function main() { switch (cmd) { case "export": { - const arg = process.argv[3]; + const args = process.argv.slice(3); + const force = args.includes("--force"); + const filteredArgs = args.filter(a => a !== "--force"); + const arg = filteredArgs[0]; if (!arg) usage(); - await cmdExport(arg); + await cmdExport(arg, force); break; } case "verify": { @@ -214,9 +251,12 @@ async function main() { break; } case "redact": { - const arg = process.argv[3]; + const args = process.argv.slice(3); + const force = args.includes("--force"); + const filteredArgs = args.filter(a => a !== "--force"); + const arg = filteredArgs[0]; if (!arg) usage(); - await cmdRedact(arg, process.argv[4]); + await cmdRedact(arg, filteredArgs[1], force); break; } default: @@ -227,4 +267,4 @@ async function main() { main().catch((e) => { diagnostics.error("progress-8", normalizeError(e)); process.exit(1); -}); +}); \ No newline at end of file