~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/atlibs-socialweb-computer-requester

socialweb.computer market requester and policy modules for atlibs, with its web pages and lexicons

0
0
main
115 lines · 7.1 KB Raw History
// The requester's fake market (hat-7 bids free, hat-9 refuses), shared by modules/*/test.mjs.
import { createHash } from "node:crypto";

import { did } from "../../../atlibs/rust/src/harness.mjs";

export const T = "com.publicdomainrelay.temp";
export const KEY = "did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme";
export const HAT7 = "did:plc:7q5lnitxv4meizdon5fmhzrq";
export const HAT9 = "did:plc:4vcig7s43z3nyqrnepmcfzqt";
export const ENDPOINT = "https://did-key-zq3shvhqouzmc7kkgijo8q4z6hjfrpmxmgst2x8ybpjpivumr.xrpc.fedproxy.com";
// A bidder's offering endpoints (kcp market.offering endpoints): its iroh ticket first, then https.
export const EP7 = [{ kind: "iroh", address: "endpointhat7aaaa" }, { kind: "https", address: ENDPOINT }];
export const ref = (collection, rkey) => ({ $type: "com.atproto.repo.strongRef", uri: `at://${did}/${collection}/${rkey}`, cid: `bafy${rkey}` });
export const signature = { $type: "network.attested.signature", issuer: did, key: KEY, cid: "bafyatt", signature: { $bytes: "c2ln" } };
export const POLICY = `${T}.market.evaluatePolicy`;

// A host: createRecord echoes a ref, attest appends a signature, the rest is per test.
export function host(extra = () => undefined) {
	let n = 0;
	const calls = [];
	const respond = (call) => {
		const out = extra(call);
		// handle() runs the module bare (no hooks): the policy hook reaches the host, which allows.
		if (call.nsid === POLICY) return out ?? { ok: true, output: { allow: true, violations: [] } };
		calls.push(call);
		if (out) return out;
		if (call.nsid === "com.fedfork.exec.attest") {
			const output = { key: KEY };
			if (call.input.record) output.record = { ...call.input.record, signatures: [signature] };
			return { ok: true, output };
		}
		if (call.nsid === "com.atproto.repo.createRecord") {
			const { uri, cid } = ref(call.input.collection, call.input.rkey ?? `r${++n}`);
			return { ok: true, output: { uri, cid } };
		}
		return { ok: false, error: `unexpected ${call.nsid}` };
	};
	return { calls, respond };
}

export const hex = (key) => createHash("sha256").update(key).digest("hex").slice(0, 32);

export const ENDPOINT9 = "https://did-key-zq3shwdpefrgzvctdhzeracana2dsvt1spqe22htelbwapqwu.xrpc.fedproxy.com";
export const EP9 = [{ kind: "iroh", address: "endpointhat9aaaa" }, { kind: "https", address: ENDPOINT9 }];
export const offering = (endpoints) => ({ value: { endpoints, appliesTo: [`${T}.compute.vm`] } });
export const isOffering = (call) => call.nsid === "com.atproto.repo.getRecord" && call.params.collection === `${T}.market.offering` && call.params.rkey === "self";
export const report = (bidder, collection, prefix, key) => `at://${bidder}/${T}.compute.events.${collection}/${prefix}-payload-${hex(key)}`;
// A kept VM's MCP server URL: <scheme>///<b64url(JSON ref)>/<tag>/<path>, split into [scheme, ref, rest].
export const serverRef = (url) => {
	const [, scheme, ref, rest] = url.match(/^([a-z]+:)\/\/\/([A-Za-z0-9_-]+)(\/.*)$/);
	return [scheme, JSON.parse(Buffer.from(ref, "base64url").toString()), rest];
};
export const uriOf = (call) => `at://${call.params.repo}/${call.params.collection}/${call.params.rkey}`;

// One fake market: hat-7 bids free (published on the second read), hat-9 refuses the rfp; the
// receipt and the guest's reports appear after a miss each, as on the live nodes.
export function market({ via = "iroh", bidders = [HAT7], receipts = true, mcp = "shell", ssh = true, boots = true, bound = false, refuses = false } = {}) {
	const store = new Map();
	const misses = new Map();
	const later = (key, value) => {
		const n = misses.get(key) ?? 0;
		misses.set(key, n + 1);
		return n === 0 ? { ok: false, error: "RecordNotFound" } : { ok: true, output: value };
	};
	const keys = [{ type: "ssh-ed25519", publicKey: "ssh-ed25519 AAAA", fingerprint: "SHA256:x" }];
	const { calls, respond: base } = host((call) => {
		const { nsid } = call;
		if (nsid === "com.atproto.repo.listRecords") return { ok: true, output: { records: [] } };
		if (isOffering(call)) return { ok: true, output: offering(call.params.repo === HAT7 ? EP7 : EP9) };
		if (nsid.endsWith("submitRfp")) {
			if (call.service === `${HAT7}#pdr_temp_market`) return { ok: true, output: { ok: true, name: "bid-7", phase: "Deciding" } };
			return bidders.includes(HAT9) ? { ok: true, output: { ok: true, name: "bid-9", phase: "Deciding" } } : { ok: false, error: "submitRfp failed with 503" };
		}
		if (nsid.endsWith("submitAccept")) return { ok: true, output: { ok: true, id: "accept-1" } };
		if (nsid.endsWith("submitEvent")) return refuses ? { ok: false, error: "submitEvent failed with 400: the inbound event is not signed" } : { ok: true, output: { ok: true } };
		if (nsid === "com.fedfork.exec.iroh.connect" || nsid === "com.fedfork.exec.webrtc.connect") return { ok: true, output: { output: "fc\n", exitCode: 0, input: call.input } };
		if (nsid === "com.atproto.repo.deleteRecord") return { ok: true, output: {} };
		if (nsid !== "com.atproto.repo.getRecord") return undefined;
		const uri = uriOf(call);
		if (call.params.collection === `${T}.badgeBlueKeys`) return bound ? { ok: true, output: { uri, cid: "bafybadge", value: { keyId: KEY } } } : { ok: false, error: "RecordNotFound" };
		const rfp = store.get("rfp");
		for (const [bidder, name] of [[HAT7, "bid-7"], [HAT9, "bid-9"]]) {
			if (bidders.includes(bidder) && uri === `at://${bidder}/${T}.market.bid/${name}`) {
				return later(uri, { uri, cid: `bafy${name}`, value: { rfp: { uri: rfp.uri }, payload: { $type: "com.atproto.repo.strongRef", uri: `at://${bidder}/${T}.market.bids.free/x` } } });
			}
		}
		const accept = store.get("accept");
		const winner = bidders.find((b) => uri.startsWith(`at://${b}/`)) ?? HAT7;
		const receipt = accept && `at://${winner}/${T}.market.receipt/receipt-${hex(`${accept.uri}\n${accept.cid}`)}`;
		if (uri === receipt && receipts) return later(uri, { uri, cid: "bafyrc", value: { accept: { uri: accept.uri } } });
		const reports = receipt && {
			[report(winner, "vm.onNetwork", "onnetwork", `onNetwork:${receipt}`)]: { address: "iroh://endpointaabm6" },
			...(ssh && { [report(winner, "vm.onNetwork", "onnetwork", `onNetwork:ssh:${receipt}`)]: { address: "sha-256 29:D7", kind: "webrtc", tag: "ssh" } }),
			...(mcp && { [report(winner, "vm.onNetwork", "onnetwork", `onNetwork:${mcp}:${receipt}`)]: { address: "sha-256 4D:C7", kind: "webrtc", tag: mcp } }),
			[report(winner, "vm.hostKeys", "hostkeys", `hostKeys:${receipt}`)]: { keys },
			[report(winner, "vm.terminated", "termination", `terminated:${receipt}`)]: { reason: "deleted_on_request" },
		};
		if (reports?.[uri]) {
			if (uri.includes("vm.terminated") && !store.get("released")) return { ok: false, error: "RecordNotFound" };
			if (!boots && !uri.includes("vm.terminated")) return { ok: false, error: "RecordNotFound" };
			return later(uri, { uri, cid: "c", value: reports[uri] });
		}
		return { ok: false, error: "RecordNotFound" };
	});
	const respond = (call) => {
		const out = base(call);
		if (call.nsid === "com.atproto.repo.createRecord" && out.ok) {
			const name = call.input.collection.split(".").pop();
			store.set(name, out.output);
			if (name === "event") store.set("released", true);
		}
		return out;
	};
	return { calls, respond, keys, via };
}