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

chadtmiller.com/spaces-bookclub

Book club: a Svelte demo app for atproto spaces (@atproto/lex-space)

0
0
main
95 lines · 3.5 KB Raw History
// Local atproto network for the book club app:
//
// - a PLC directory (did:plc registry)            http://localhost:2582
// - PDS 1, handles *.test                         http://localhost:2583
// - PDS 2, handles *.test2                        (random port, printed below)
// - a lexicon authority account on PDS 1, which publishes this app's lexicons.
//   Both PDSes resolve every NSID against it, so the OAuth consent screen can
//   show the `com.example.bookclub.club` space type and its collections.
// - a handle resolver                             http://localhost:2580
//   Each test PDS only resolves its own handles (there is no DNS for .test):
//   this asks each of them, like DNS or an AppView would on the real network.
//
// Everything lives in memory: restarting wipes accounts, spaces and records.

import { readFile, readdir } from 'node:fs/promises'
import { createServer } from 'node:http'
import { join } from 'node:path'
import { TestNetworkNoAppView, type TestPds } from '@atproto/dev-env'

const LEXICONS_DIR = new URL('../lexicons/', import.meta.url).pathname

const network = await TestNetworkNoAppView.create({
  plc: { port: 2582 },
  pds: { port: 2583, hostname: 'localhost' },
  extraPdses: 1,
  lexiconAuthority: true,
})
const [pds2] = network.extraPdses

const handleResolver = createServer(async (req, res) => {
  res.setHeader('access-control-allow-origin', '*')
  const url = new URL(req.url ?? '/', 'http://localhost')
  const handle = url.searchParams.get('handle')
  if (url.pathname !== '/xrpc/com.atproto.identity.resolveHandle' || !handle) {
    res.writeHead(404).end()
    return
  }
  for (const pds of [network.pds, ...network.extraPdses]) {
    const response = await fetch(new URL(req.url!, pds.url))
    if (response.ok) {
      res.writeHead(200, { 'content-type': 'application/json' })
      res.end(await response.text())
      return
    }
  }
  res.writeHead(400, { 'content-type': 'application/json' })
  res.end(
    JSON.stringify({ error: 'InvalidRequest', message: 'Unable to resolve handle' }),
  )
}).listen(2580)

// Publish the app's lexicons from the authority's repo
const authority = network.pds.getAgent()
await authority.login({ identifier: 'lex-authority.test', password: 'hunter2' })
for (const path of await readdir(LEXICONS_DIR, { recursive: true })) {
  if (!path.endsWith('.json')) continue
  const doc = JSON.parse(await readFile(join(LEXICONS_DIR, path), 'utf8'))
  await authority.com.atproto.repo.createRecord({
    repo: authority.assertDid,
    collection: 'com.atproto.lexicon.schema',
    rkey: doc.id,
    record: { $type: 'com.atproto.lexicon.schema', ...doc },
  })
  console.log(`📖 Published lexicon ${doc.id}`)
}

async function createUser(pds: TestPds, handle: string) {
  const agent = pds.getAgent()
  const password = 'password'
  await agent.createAccount({ handle, password, email: `${handle}@example.com` })
  return { handle, password, did: agent.assertDid, pds: pds.url }
}

const users = [
  await createUser(network.pds, 'alice.test'),
  await createUser(pds2, 'bob.test2'),
  await createUser(network.pds, 'carol.test'),
]

console.log(`
👤 PLC directory     ${network.plc.url}
🌞 PDS 1             ${network.pds.url}
🌞 PDS 2             ${pds2.url}
🔎 Handle resolver   http://localhost:2580
`)
console.table(users)
console.log('\n✅ Network ready. Ctrl-C to stop.')

const shutdown = async () => {
  handleResolver.close()
  await network.close()
  process.exit(0)
}
process.once('SIGINT', shutdown)
process.once('SIGTERM', shutdown)