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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,24 @@ All notable changes to this project are documented here. Format follows

## [Unreleased]

### Added

- `probeRoomCreation()` helper to check venue capacity before attempting a deal. When a venue
is at its room limit (global cap or per-client daily budget), `tclk-offers` cannot be created
and no deal can bootstrap. The probe attempts to create an ephemeral test room and reports
whether creation is available or refused. `examples/live-deal.mjs` now probes up front and
provides clear guidance when capacity is exhausted, addressing the bootstrap half of #3.
- SPEC.md §2 now documents the bootstrap dependency on room creation as a known sharp edge,
including the two capacity mechanisms venues typically enforce and mitigation guidance.

### Fixed

- `foldTranscript` now emits warnings when transcript metadata anomalies (sequence gaps,
ordering violations, backwards timestamps) or deadline-sensitive transitions rely on
unsigned venue timestamps. Detects the exact attack from #96: tampered `timestampMs`
fields that flip claimed→refunded outcomes while all signatures remain valid. Anomaly
checks run only on signed records; unsigned records are skipped to avoid false positives
when partial transcripts are analyzed.
- `tclk_post_frame` now accepts exact decimal-string nonces in addition to safe integer
numbers, so signed Technocore nonces above JavaScript's safe-integer range are preserved
without precision loss. Unsafe numeric nonces (> 2^53 - 1) are rejected at the MCP schema
Expand Down
8 changes: 8 additions & 0 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ the public manual (`/llms.txt`), and any self-hosted deployment works identicall
the venue's retention are fine — they bind the rail, not the room.
- *Room epochs*: `seq` restarts if a room is reaped and recreated; contract ids are
self-contained hashes, never `room/seq` references, so nothing here dedupes on `seq`.
- *Bootstrap depends on room creation* (#3): a deal cannot start when the venue refuses new
room creation. `tclk-offers` is the fixed rendezvous name strangers use to find each other,
so when it does not exist and cannot be created (global room cap reached or per-client daily
budget exhausted), no offer can be posted. Venues typically enforce two capacity mechanisms:
a global room limit and a per-client-IP daily budget (e.g. 20 new rooms per day). The daily
budget is the durable constraint and resets at UTC midnight. Callers should probe room
creation capability before attempting a deal (`probeRoomCreation`) and provide clear guidance
when creation is refused, directing users to run their own instance or wait for capacity.

## 3. Wire format

Expand Down
16 changes: 16 additions & 0 deletions examples/audit-export.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ if (handshake === null) {
}

const folded = foldTranscript([handshake.offer, handshake.accept, ...deal]);

if (folded.warnings.length > 0) {
console.error("\nWARNINGS:");
for (const warning of folded.warnings) {
console.error(` ${warning}`);
}
}

for (const step of folded.steps) {
const verdict = step.ok ? "ok " : "BAD";
console.log(`${verdict} ${step.room}#${step.seq} ${step.type ?? "record"}${step.reason ? ` — ${step.reason}` : ""}`);
Expand All @@ -48,6 +56,14 @@ if (folded.state === null) {
process.exit(1);
}

const hasOrderingIssues = folded.warnings.some(w =>
w.includes("seq gap") || w.includes("seq ordering") || w.includes("backwards timestamp")
);
if (hasOrderingIssues) {
console.error("\nTranscript has sequence or timestamp ordering issues");
process.exit(1);
}

const terminal = ["claimed", "refunded", "cancelled"].includes(folded.state.status);
console.log(`\nfold → ${folded.state.status}${terminal ? "" : " (not terminal)"}`);
process.exit(terminal ? 0 : 1);
38 changes: 37 additions & 1 deletion examples/live-deal.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { randomBytes } from "node:crypto";
import {
OFFER_ROOM, PaperRail, applyFrame, dealRoom, encodeFrame, findContractHandshake, foldTranscript,
generateHashLock, lockTerms, makeAccept, makeOffer, openContract, paperNote,
parseTranscriptExport, stateNote, stateNoteValue, transcriptRecord,
parseTranscriptExport, probeRoomCreation, stateNote, stateNoteValue, transcriptRecord,
} from "../dist/index.js";
import { canonicalMessage, nextNonce, signerFromSeed, sweep } from "../mcp/dist/signing.js";

Expand Down Expand Up @@ -251,6 +251,42 @@ log("", `payer ${payer.did}`);
log("", `payee ${payee.did}`);
console.log();

// Pre-flight check: probe room creation capacity before attempting the deal.
// Issue #3 documents that when the venue is at capacity (global room cap or per-client
// daily budget), tclk-offers cannot be created and no deal can bootstrap. Probing up front
// gives clear guidance instead of a raw 400 mid-choreography.
log("", "Checking venue capacity...");
const probe = await probeRoomCreation(BASE, fetch);
if (!probe.available) {
console.error(
[
"",
`✗ Room creation refused: ${probe.reason}`,
"",
"A deal needs two rooms this venue will not create right now:",
" - tclk-offers (the public rendezvous where strangers meet)",
" - mb-p-tclk-<contract-id> (the derived deal room)",
"",
"When the venue refuses new room creation, no deal can start.",
"",
"Run against your own instance instead:",
"",
" bash/zsh TECHNOCORE_URL=http://localhost:8080 node examples/live-deal.mjs",
' PowerShell $env:TECHNOCORE_URL = "http://localhost:8080"; node examples/live-deal.mjs',
" cmd.exe set TECHNOCORE_URL=http://localhost:8080 && node examples/live-deal.mjs",
"",
"The hosted venue clears on its own:",
" - Idle rooms are reclaimed after 7 days",
" - Single-message rooms after 24 hours",
" - Per-client daily budget (20 new rooms/day) resets at UTC midnight",
"",
].join("\n"),
);
process.exit(1);
}
log("✓", "Venue accepting new rooms");
console.log();

// 0 — the job spec goes in a note, and the offer points at it. A frame carries the
// payment leg only: no field of it describes the work, deliberately, so the spec lives
// in whatever vocabulary the parties already use and the contract just references it.
Expand Down
1 change: 1 addition & 0 deletions mcp/src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ export function createHandlers(options: HandlerOptions = {}) {
// caller already holds, and this server never republishes secret material.
secretRevealed: open.secret !== undefined,
steps: folded.steps,
warnings: folded.warnings,
};
},

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export type { LockTerms, SettlementRail } from "./rail.js";
export {
OFFER_ROOM, capabilityToken, parseCapabilityToken,
dealRoom, stateNote, stateNoteValue, parseStateNoteValue,
probeRoomCreation,
} from "./technocore.js";

export {
Expand Down
56 changes: 56 additions & 0 deletions src/technocore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,59 @@ export function parseStateNoteValue(value: string): { status: TclkStatus; railRe
if (railRef === undefined) return { status: status as TclkStatus };
return RAIL_REF.test(railRef) ? { status: status as TclkStatus, railRef } : null;
}

/**
* Probe whether the venue will accept new room creation. Returns an object indicating
* whether creation is available and, if refused, the venue's reason.
*
* This checks the bootstrap constraint documented in issue #3: when a venue is at its
* room capacity (global cap or per-client daily budget), `tclk-offers` cannot be created
* and no deal can start. Callers should probe before attempting a deal and provide clear
* guidance when creation is refused.
*
* The probe attempts to create an ephemeral test room with a random name, then immediately
* reads it back to confirm. The room is not deleted (the venue has no delete operation),
* but it will be reaped after 24 hours of idleness per the venue's policy.
*
* @param venueUrl - Base URL of the technocore deployment (e.g. "https://technocore.chat")
* @param fetch - Fetch implementation to use (allows testing without network)
* @returns Promise resolving to {available: true} or {available: false, status, reason}
*
* @example
* ```ts
* const probe = await probeRoomCreation("https://technocore.chat", fetch);
* if (!probe.available) {
* console.error(`Room creation refused: ${probe.reason}`);
* // Guide user to run against their own instance or wait for capacity
* }
* ```
*/
export async function probeRoomCreation(
venueUrl: string,
fetchImpl: typeof fetch = fetch,
): Promise<
| { available: true }
| { available: false; status: number; reason: string }
> {
const testRoom = `p-tclk-probe-${Math.random().toString(36).slice(2, 10)}`;
const url = `${venueUrl}/r/${testRoom}/say/probe/test`;

try {
const res = await fetchImpl(url);
const status = res.status;

if (!res.ok) {
const body = await res.text();
const firstLine = body.split("\n").filter((line) => line.trim())[0] ?? "";
return { available: false, status, reason: firstLine };
}

return { available: true };
} catch (error) {
return {
available: false,
status: 0,
reason: error instanceof Error ? error.message : String(error),
};
}
}
55 changes: 54 additions & 1 deletion src/transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export interface TranscriptStep {
export interface TranscriptFoldResult {
state: ContractState | null;
steps: TranscriptStep[];
warnings: string[];
}

export interface ContractHandshake {
Expand Down Expand Up @@ -235,8 +236,49 @@ export function findContractHandshake(
*/
export function foldTranscript(records: readonly TranscriptRecord[]): TranscriptFoldResult {
const steps: TranscriptStep[] = [];
const warnings: string[] = [];
let state: ContractState | null = null;

// Detect sequence and timestamp anomalies per room, only on signed records
const roomState = new Map<string, { prevSeq: number; prevTimestampMs: number; seenGap: boolean; seenOrderViolation: boolean; seenBackwards: boolean }>();
let hasSuccessfulDeadlineFrame = false;

// First pass: check for anomalies on signed records only
for (let i = 0; i < records.length; i++) {
const record = records[i];
const isSigned = record?.signature !== null && record?.nonce !== null;

// Only check anomalies on signed records
if (!isSigned) continue;

const room = record.room ?? "";
let state = roomState.get(room);
if (!state) {
state = { prevSeq: record.seq, prevTimestampMs: record.timestampMs, seenGap: false, seenOrderViolation: false, seenBackwards: false };
roomState.set(room, state);
continue;
}

if (record?.seq !== undefined && Number.isSafeInteger(record.seq)) {
if (record.seq <= state.prevSeq && !state.seenOrderViolation) {
warnings.push(`seq ordering: record ${i} has seq ${record.seq} which is not greater than previous seq ${state.prevSeq}`);
state.seenOrderViolation = true;
} else if (record.seq !== state.prevSeq + 1 && !state.seenGap) {
warnings.push(`seq gap: record ${i} jumps from seq ${state.prevSeq} to ${record.seq} in room ${room}`);
state.seenGap = true;
}
state.prevSeq = record.seq;
}

if (record?.timestampMs !== undefined && Number.isSafeInteger(record.timestampMs)) {
if (record.timestampMs < state.prevTimestampMs && !state.seenBackwards) {
warnings.push(`backwards timestamp: record ${i} has timestampMs ${record.timestampMs} which is earlier than previous ${state.prevTimestampMs}`);
state.seenBackwards = true;
}
state.prevTimestampMs = record.timestampMs;
}
}

records.forEach((record, index) => {
const base = { index, room: record?.room ?? "", seq: record?.seq ?? -1 };
const verification = verifyTranscriptRecord(record);
Expand Down Expand Up @@ -308,7 +350,18 @@ export function foldTranscript(records: readonly TranscriptRecord[]): Transcript
const result = applyFrame(state, frame, record.timestampMs);
state = result.state;
steps.push({ ...base, type: frame.type, ok: result.ok, reason: result.reason });

// Track successful deadline-sensitive frames
if (result.ok && ["accept", "lock", "reveal", "refund"].includes(frame.type)) {
hasSuccessfulDeadlineFrame = true;
}
});

return { state, steps };
// Emit generic warning when deadline-sensitive frames succeeded
// because timestampMs and seq are venue metadata NOT covered by signatures
if (hasSuccessfulDeadlineFrame) {
warnings.push("unsigned metadata: transcript contains deadline-sensitive frames (accept/lock/reveal/refund) but some records lack signatures; seq and timestampMs are not authenticated and may be forged");
}

return { state, steps, warnings };
}
78 changes: 78 additions & 0 deletions tests/technocore-probe.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: Apache-2.0

import { describe, expect, test } from "vitest";
import { probeRoomCreation } from "../src/technocore.js";

describe("probeRoomCreation", () => {
test("reports available when room creation succeeds", async () => {
const mockFetch = async () => new Response("OK", { status: 200 });
const result = await probeRoomCreation("https://example.test", mockFetch);
expect(result).toEqual({ available: true });
});

test("reports unavailable on 400 room limit reached", async () => {
const mockFetch = async () =>
new Response("400 room limit reached (81920 is the cap, and this would be a new one).", {
status: 400,
});
const result = await probeRoomCreation("https://example.test", mockFetch);
expect(result).toEqual({
available: false,
status: 400,
reason: "400 room limit reached (81920 is the cap, and this would be a new one).",
});
});

test("reports unavailable on other 400 errors", async () => {
const mockFetch = async () => new Response("400 bad request\ndetails", { status: 400 });
const result = await probeRoomCreation("https://example.test", mockFetch);
expect(result).toEqual({
available: false,
status: 400,
reason: "400 bad request",
});
});

test("reports unavailable on other HTTP errors", async () => {
const mockFetch = async () => new Response("500 internal error", { status: 500 });
const result = await probeRoomCreation("https://example.test", mockFetch);
expect(result).toEqual({
available: false,
status: 500,
reason: "500 internal error",
});
});

test("reports unavailable on network error", async () => {
const mockFetch = async () => {
throw new Error("network unreachable");
};
const result = await probeRoomCreation("https://example.test", mockFetch);
expect(result).toEqual({
available: false,
status: 0,
reason: "network unreachable",
});
});

test("extracts first non-empty line from multi-line body", async () => {
const mockFetch = async () =>
new Response("\n\n400 room limit reached (cap 102400)\nSome other detail", { status: 400 });
const result = await probeRoomCreation("https://example.test", mockFetch);
expect(result).toEqual({
available: false,
status: 400,
reason: "400 room limit reached (cap 102400)",
});
});

test("handles empty response body", async () => {
const mockFetch = async () => new Response("", { status: 400 });
const result = await probeRoomCreation("https://example.test", mockFetch);
expect(result).toEqual({
available: false,
status: 400,
reason: "",
});
});
});
Loading
Loading