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

johnandersen777.bsky.social/socialweb-computer-console

console.socialweb.computer: kcp, kubectl and ssh compiled to wasm in a browser tab with a terminal; a kcp fork

0
0
main
79 lines · 3.2 KB Raw History
// This is free and unencumbered software released into the public domain.
// See UNLICENSE.

// The requester's market calls to a bidder's `webrtc` offering endpoint:
// HTTP/1.1 over a datachannel, signalled through computer.socialweb.ingress.*
// records (@publicdomainrelay/atlibs-webrtc). RTCPeerConnection lives on the
// page; kcp.wasm (a worker) sends each call here and writes the offer record.

import { recordSignals, WebrtcHost } from "https://cdn.jsdelivr.net/npm/@publicdomainrelay/atlibs-webrtc@0.4.0/js/index.js";
import * as age from "https://esm.sh/age-encryption@0.3.1";

const PLC = "https://plc.directory";

export function pdsResolver(fetchFn = globalThis.fetch) {
  const known = new Map();
  return (did) => {
    if (!known.has(did)) {
      const url = did.startsWith("did:web:")
        ? `https://${decodeURIComponent(did.slice("did:web:".length).split(":")[0])}/.well-known/did.json`
        : `${PLC}/${did}`;
      const found = fetchFn(url).then(async (res) => {
        if (!res.ok) throw new Error(`${did}: DID document HTTP ${res.status}`);
        const pds = (await res.json()).service?.find((s) => s.id === "#atproto_pds" || s.id === `${did}#atproto_pds`)?.serviceEndpoint;
        if (typeof pds !== "string") throw new Error(`${did}: no PDS in its DID document`);
        return pds.replace(/\/+$/, "");
      });
      found.catch(() => known.delete(did));
      known.set(did, found);
    }
    return known.get(did);
  };
}

export function recordReader(fetchFn = globalThis.fetch, pdsOf = pdsResolver(fetchFn)) {
  return async ({ repo, collection, rkey }) => {
    const query = new URLSearchParams({ repo, collection, rkey });
    const res = await fetchFn(`${await pdsOf(repo)}/xrpc/com.atproto.repo.getRecord?${query}`, { cache: "no-store" });
    if (res.status === 400 || res.status === 404) {
      await res.body?.cancel();
      return null;
    }
    if (!res.ok) throw new Error(`${repo}/${collection}/${rkey}: HTTP ${res.status}`);
    const { value, cid } = await res.json();
    return { value, cid };
  };
}

/**
 * One transport per requester DID. fetch({did, method, url, headers, body},
 * {putRecord, deleteRecord}) answers {status, headers, body}; the record
 * writers are the caller's (the requester's own repo).
 */
export function marketTransport({ fetchFn = globalThis.fetch, makePeer = (config) => new RTCPeerConnection(config) } = {}) {
  const getRecord = recordReader(fetchFn);
  const hosts = new Map();
  const writers = new Map();
  const hostFor = (did) => {
    if (!hosts.has(did)) {
      const repo = {
        did,
        getRecord,
        putRecord: (record) => writers.get(did).putRecord(record),
        deleteRecord: (record) => writers.get(did).deleteRecord(record),
      };
      hosts.set(did, new WebrtcHost({ records: recordSignals({ repo, subhandle: "requester" }), makePeer, age }));
    }
    return hosts.get(did);
  };
  return {
    fetch({ did, method, url, headers, body }, { putRecord, deleteRecord }) {
      writers.set(did, { putRecord, deleteRecord });
      return hostFor(did).fetch({ method, url, headers, body });
    },
    close() {
      for (const host of hosts.values()) host.close();
      hosts.clear();
    },
  };
}