import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import Database from "better-sqlite3"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { verifiedLocalKeyId } from "./device-retirement.js"; import type { LegacySourceHistoryEntry } from "./legacy-source-history.js"; import { holdLegacySourcesWithoutFreshHistory, installAuthoritativeLegacySourceHistory, LEGACY_SOURCE_HISTORY_SCHEMA_SQL, } from "./legacy-source-history-store.js"; import { getOrCreateOpaqueProjectAssignment, persistPrivateProjectAssignment, readPrivateProjectAssignment, } from "./opaque-project-assignment.js"; import { acknowledgeInstalledProjectAssignment } from "./source-attachment-ack.js"; import { SOURCE_ATTACHMENT_ACK_PATH, sourceAttachmentAckFields, } from "./source-attachment-ack-wire.js"; import { verifySignature } from "./sync-auth.js"; import type { RequestJsonExecutor } from "./sync-http-client.js"; import { ensureDeviceIdentity, loadPublicKey } from "./sync-identity.js"; import { initTestSchema } from "./test-utils.js"; const projectName = "Local-only Fixture Project"; const request = { groupId: "fixture-group", sourceScopeId: "fixture-source", nonce: "fixture-history", }; let directory: string; let db: Database.Database; beforeEach(() => { directory = mkdtempSync(join(tmpdir(), "source-attachment-ack-")); db = new Database(join(directory, "device.sqlite")); initTestSchema(db); db.exec(LEGACY_SOURCE_HISTORY_SCHEMA_SQL); }); afterEach(() => { db.close(); rmSync(directory, { recursive: true, force: true }); }); function install(entries: LegacySourceHistoryEntry[]) { installAuthoritativeLegacySourceHistory( db, { ...request, request_nonce: request.nonce, version: 2, complete: true, sourceGeneration: entries.length, entries, }, request, ); } function fixture({ persist = true } = {}) { const keysDir = join(directory, "keys"); const [deviceId] = ensureDeviceIdentity(db, { keysDir }); const publicKey = loadPublicKey(keysDir); const keyId = verifiedLocalKeyId(db, deviceId); if (!publicKey || !keyId) throw new Error("fixture local identity unavailable"); install([]); const { key } = getOrCreateOpaqueProjectAssignment(db, { ...request, projectName }); const prepared: LegacySourceHistoryEntry = { key, sourceGeneration: 1, state: "prepared", initiatorDeviceId: deviceId, initiatorKeyId: keyId, participantDeviceIds: [deviceId], createsDestination: true, }; install([prepared]); const persistAssignment = () => persistPrivateProjectAssignment(db, key, { localDeviceId: deviceId, sourceGeneration: 1, initiatorDeviceId: deviceId, initiatorKeyId: keyId, projectName, }); if (persist) expect(persistAssignment()).toBe(true); const options = { coordinatorUrl: "https://coordinator.example.test", keysDir, drainLegacySends: vi.fn(async () => true), requestExecutor: vi.fn(async () => [503, null]), }; return { key, options, publicKey, deviceId, prepared, persistAssignment }; } it("signs only opaque ACK fields after the exact durable pause is drained", async () => { const f = fixture(); f.options.requestExecutor.mockImplementation(async (method, url, opts) => { expect(db.inTransaction).toBe(false); expect(f.options.drainLegacySends).toHaveBeenCalledWith({ sourceScopeId: request.sourceScopeId, sourceGeneration: 1, }); const headers = new Headers(opts?.headers); const bodyBytes = Buffer.from(opts?.bodyBytes ?? []); const nonce = headers.get("X-Opencode-Nonce") ?? ""; expect(method).toBe("POST"); expect(new URL(url).pathname).toBe(SOURCE_ATTACHMENT_ACK_PATH); expect(opts?.redirect).toBe("error"); expect(JSON.parse(bodyBytes.toString())).toEqual(sourceAttachmentAckFields(f.key, 1)); expect(bodyBytes.toString()).not.toContain(projectName); expect( verifySignature({ deviceId: f.deviceId, publicKey: f.publicKey, method, pathWithQuery: SOURCE_ATTACHMENT_ACK_PATH, bodyBytes, nonce, timestamp: headers.get("X-Opencode-Timestamp") ?? "", signature: headers.get("X-Opencode-Signature") ?? "", }), ).toBe(true); return [200, { kind: "acknowledged", request_nonce: nonce }]; }); expect(await acknowledgeInstalledProjectAssignment(db, f.key, f.options)).toBe(true); expect(f.options.requestExecutor).toHaveBeenCalledOnce(); }); it("does not drain or send ACK for an assignment installed in an open transaction", async () => { const f = fixture({ persist: false }); db.exec("BEGIN"); try { expect(f.persistAssignment()).toBe(true); expect(await acknowledgeInstalledProjectAssignment(db, f.key, f.options)).toBe(false); } finally { db.exec("ROLLBACK"); } expect(readPrivateProjectAssignment(db, f.key)).toBeNull(); expect(f.options.requestExecutor).not.toHaveBeenCalled(); expect(f.options.drainLegacySends).not.toHaveBeenCalled(); }); it("does not send ACK when a transaction opens while draining legacy sends", async () => { const f = fixture(); const drained = Promise.withResolvers(); f.options.drainLegacySends.mockReturnValueOnce(drained.promise); const acknowledgement = acknowledgeInstalledProjectAssignment(db, f.key, f.options); expect(f.options.drainLegacySends).toHaveBeenCalledOnce(); db.exec("BEGIN"); try { db.prepare( "UPDATE legacy_source_private_assignments SET project_name = ? WHERE attempt_id = ?", ).run("Uncommitted Fixture Project", f.key.attemptId); drained.resolve(true); expect(await acknowledgement).toBe(false); } finally { db.exec("ROLLBACK"); } expect(readPrivateProjectAssignment(db, f.key)?.projectName).toBe(projectName); expect(f.options.requestExecutor).not.toHaveBeenCalled(); }); it.each([ "missing private assignment", "wrong attempt", "held history", "cancelled attempt", "HTTP", ] as const)("does not drain or send ACK with %s", async (kind) => { const f = fixture({ persist: kind !== "missing private assignment" }); if (kind === "held history") holdLegacySourcesWithoutFreshHistory(db, [request.sourceScopeId]); if (kind === "cancelled attempt") install([{ ...f.prepared, state: "cancelled" }]); if (kind === "HTTP") f.options.coordinatorUrl = "http://coordinator.example.test"; const key = kind === "wrong attempt" ? { ...f.key, attemptId: "wrong-attempt" } : f.key; expect(await acknowledgeInstalledProjectAssignment(db, key, f.options)).toBe(false); expect(f.options.drainLegacySends).not.toHaveBeenCalled(); expect(f.options.requestExecutor).not.toHaveBeenCalled(); }); it.each([false, true])( "does not send if draining is incomplete or the pause becomes stale (stale %s)", async (stale) => { const f = fixture(); f.options.drainLegacySends.mockImplementation(async () => { if (stale) install([{ ...f.prepared, state: "cancelled" }]); return stale; }); expect(await acknowledgeInstalledProjectAssignment(db, f.key, f.options)).toBe(false); expect(f.options.requestExecutor).not.toHaveBeenCalled(); }, ); it.each(["wrong nonce", "late invalidation"] as const)( "does not accept a reply with %s", async (failure) => { const f = fixture(); f.options.requestExecutor.mockImplementation(async (_method, _url, opts) => { if (failure === "late invalidation") holdLegacySourcesWithoutFreshHistory(db, [request.sourceScopeId]); const nonce = new Headers(opts?.headers).get("X-Opencode-Nonce"); return [ 200, { kind: "acknowledged", request_nonce: failure === "wrong nonce" ? "other" : nonce }, ]; }); expect(await acknowledgeInstalledProjectAssignment(db, f.key, f.options)).toBe(false); expect(f.options.requestExecutor).toHaveBeenCalledOnce(); }, );