anbot

root / core.mjs

10002 bytes

// Platform-free ANBot core. Only platform built-ins are used here:
// WebCrypto, TextEncoder, and TextDecoder. There are no imports, so this
// module runs unchanged in every runtime that provides those built-ins.
// The ANProto envelope stays byte-identical to SPEC: records written by
// earlier code keep verifying, and records written here verify under
// earlier code.

export function requireThat(condition, message) {
  if (!condition) throw new Error(message)
}

const utf8Encoder = new TextEncoder()
const utf8Decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })

export const utf8Encode = text => utf8Encoder.encode(text)
export const utf8Decode = bytes => utf8Decoder.decode(bytes)

function latin1Decode(bytes) {
  let text = ''
  for (const byte of bytes) text += String.fromCharCode(byte)
  return text
}

export function parseJson(input) {
  const text = typeof input === 'string' ? input : utf8Decode(input)
  const value = JSON.parse(text)
  // JSON.parse checks syntax. Track decoded object keys before trusting its result.
  const containers = []
  const tokens = /"(?:[^"\\]|\\[\s\S])*"|[{}\[\]:]/g
  for (const match of text.matchAll(tokens)) {
    const token = match[0]
    if (token === '{') containers.push(new Set())
    if (token === '[') containers.push(null)
    if (token === '}' || token === ']') containers.pop()
    if (token.startsWith('"') && /^\s*:/.test(text.slice(match.index + token.length))) {
      const keys = containers.at(-1)
      const key = JSON.parse(token)
      requireThat(!keys.has(key), 'Duplicate JSON member')
      keys.add(key)
    }
  }
  return value
}

const base64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
const base64UrlAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'

export function base64Encode(bytes, url = false) {
  const alphabet = url ? base64UrlAlphabet : base64Alphabet
  let text = ''
  for (let i = 0; i < bytes.length; i += 3) {
    const a = bytes[i]
    const b = i + 1 < bytes.length ? bytes[i + 1] : 0
    const c = i + 2 < bytes.length ? bytes[i + 2] : 0
    const n = (a << 16) | (b << 8) | c
    text += alphabet[(n >> 18) & 63] + alphabet[(n >> 12) & 63]
    text += i + 1 < bytes.length ? alphabet[(n >> 6) & 63] : '='
    text += i + 2 < bytes.length ? alphabet[n & 63] : '='
  }
  return url ? text.replaceAll('=', '') : text
}

export function base64Decode(text, url = false) {
  requireThat(typeof text === 'string', 'Expected a hash or envelope string')
  if (url) {
    requireThat(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/.test(text), 'Invalid encoding')
  } else {
    requireThat(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text), 'Invalid encoding')
  }
  const alphabet = url ? base64UrlAlphabet : base64Alphabet
  const values = new Map()
  for (let i = 0; i < alphabet.length; i++) values.set(alphabet[i], i)
  const padded = url ? text + '='.repeat((4 - (text.length % 4)) % 4) : text
  const bytes = new Uint8Array((padded.length / 4) * 3 - (padded.endsWith('==') ? 2 : padded.endsWith('=') ? 1 : 0))
  let offset = 0
  for (let i = 0; i < padded.length; i += 4) {
    const n = ((values.get(padded[i]) ?? 0) << 18) | ((values.get(padded[i + 1]) ?? 0) << 12) |
      ((values.get(padded[i + 2]) ?? 0) << 6) | (values.get(padded[i + 3]) ?? 0)
    if (offset < bytes.length) bytes[offset++] = (n >> 16) & 255
    if (offset < bytes.length) bytes[offset++] = (n >> 8) & 255
    if (offset < bytes.length) bytes[offset++] = n & 255
  }
  requireThat(base64Encode(bytes, url) === text, 'Invalid encoding')
  return bytes
}

export function decodeHash(value, size, url = false) {
  const bytes = base64Decode(value, url)
  requireThat(bytes.length === size, 'Invalid encoding')
  return bytes
}

export function concat(...arrays) {
  const total = arrays.reduce((sum, array) => sum + array.length, 0)
  const out = new Uint8Array(total)
  let offset = 0
  for (const array of arrays) {
    out.set(array, offset)
    offset += array.length
  }
  return out
}

export async function sha256(bytes) {
  return new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes))
}

const spkiPrefix = Uint8Array.from([0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00])

export async function importPrivateKey(der) {
  try {
    return await globalThis.crypto.subtle.importKey('pkcs8', der, 'Ed25519', true, ['sign'])
  } catch {
    throw new Error('Expected an Ed25519 identity')
  }
}

export async function generatePrivateKey() {
  const pair = await globalThis.crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify'])
  return pair.privateKey
}

export async function exportPrivateKeyPkcs8(privateKey) {
  return new Uint8Array(await globalThis.crypto.subtle.exportKey('pkcs8', privateKey))
}

export async function authorFromPrivateKey(privateKey) {
  const jwk = await globalThis.crypto.subtle.exportKey('jwk', privateKey)
  return base64Encode(base64Decode(jwk.x, true))
}

export async function importAuthorKey(author) {
  const spki = concat(spkiPrefix, decodeHash(author, 32))
  return globalThis.crypto.subtle.importKey('spki', spki, 'Ed25519', true, ['verify'])
}

export async function signBytes(privateKey, bytes) {
  return new Uint8Array(await globalThis.crypto.subtle.sign('Ed25519', privateKey, bytes))
}

export async function verifyBytes(publicKey, bytes, signature) {
  try {
    return await globalThis.crypto.subtle.verify('Ed25519', publicKey, signature, bytes)
  } catch {
    return false
  }
}

export function pemEncodePkcs8(der) {
  const lines = base64Encode(der).match(/.{1,64}/g) ?? []
  return `-----BEGIN PRIVATE KEY-----\n${lines.join('\n')}\n-----END PRIVATE KEY-----\n`
}

export function pemDecodePkcs8(input) {
  const text = typeof input === 'string' ? input : utf8Decode(input)
  const lines = text.split('\n').map(line => line.trim()).filter(Boolean)
  requireThat(lines.length >= 3 && lines[0] === '-----BEGIN PRIVATE KEY-----' &&
    lines.at(-1) === '-----END PRIVATE KEY-----', 'Invalid identity key')
  return base64Decode(lines.slice(1, -1).join(''))
}

export const recordPath = id => base64Encode(decodeHash(id, 32), true)

// The author claimed by a record: the first 44 characters of its signature,
// validated as a canonical 32-byte key. Claiming an author proves nothing;
// callers must verify the record against this key with verifyRecord.
export function recordAuthor(record) {
  requireThat(record && typeof record === 'object' && typeof record.signature === 'string' &&
    record.signature.length === 208, 'Invalid record')
  const author = record.signature.slice(0, 44)
  decodeHash(author, 32)
  return author
}

// The signer-asserted payload timestamp in milliseconds. This extracts and
// validates the 13-digit field without verifying the signature; callers
// must verify the record first.
export function envelopeTimestamp(signature) {
  requireThat(typeof signature === 'string' && signature.length === 208, 'Invalid ANProto envelope')
  const signed = decodeHash(signature.slice(44), 121)
  const payloadText = latin1Decode(signed.subarray(64))
  requireThat(/^[0-9]{13}$/.test(payloadText.slice(0, 13)), 'Invalid ANProto payload')
  return Number(payloadText.slice(0, 13))
}

export async function createRecord(identity, body) {
  const content = JSON.stringify(body)
  const contentHash = base64Encode(await sha256(utf8Encode(content)))
  const payload = utf8Encode(String(Date.now()) + contentHash)
  const proof = await signBytes(identity.privateKey, payload)
  const signature = identity.author + base64Encode(concat(proof, payload))
  const id = base64Encode(await sha256(utf8Encode(signature)))
  return { id, signature, content }
}

export async function verifyRecord(record, author) {
  return (await verifyRecordDetails(record, author)).body
}

export async function verifyRecordDetails(record, author) {
  requireThat(record && typeof record === 'object' && typeof record.id === 'string' &&
    typeof record.signature === 'string' && typeof record.content === 'string' &&
    record.content.isWellFormed() && utf8Encode(record.content).length <= 65536, 'Invalid record')
  const { signature, content } = record
  requireThat(signature.length === 208 && signature.slice(0, 44) === author &&
    base64Encode(await sha256(utf8Encode(signature))) === record.id, 'Record ID or author mismatch')
  const signed = decodeHash(signature.slice(44), 121)
  const payload = signed.subarray(64)
  const key = await importAuthorKey(author)
  requireThat(await verifyBytes(key, payload, signed.subarray(0, 64)), 'Invalid signature')
  const payloadText = latin1Decode(payload)
  const timestamp = payloadText.slice(0, 13)
  requireThat(/^[0-9]{13}$/.test(timestamp) &&
    payloadText.slice(13) === base64Encode(await sha256(utf8Encode(content))), 'Invalid ANProto payload')
  return { body: parseJson(content), timestamp: Number(timestamp) }
}

export const chunkSize = 262144
export const maxChunks = 16384
export const maxManifest = 1048576

export function splitChunks(bytes) {
  const chunks = []
  for (let offset = 0; offset < bytes.length; offset += chunkSize) {
    chunks.push(bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)))
  }
  return chunks
}

export function createManifest(size, chunks) {
  return utf8Encode(JSON.stringify({ andfs: 1, size, chunkSize, chunks }))
}

export function validateManifest(bytes) {
  const manifest = parseJson(bytes)
  requireThat(manifest?.andfs === 1 && Number.isSafeInteger(manifest.size) &&
    manifest.size >= 0 && manifest.chunkSize === chunkSize && Array.isArray(manifest.chunks) &&
    manifest.chunks.length <= maxChunks &&
    manifest.chunks.length === Math.ceil(manifest.size / chunkSize), 'Invalid AndFS manifest')
  return manifest
}

export async function blockId(bytes) {
  return base64Encode(await sha256(bytes), true)
}

export async function verifyBlock(bytes, id) {
  return (await blockId(bytes)) === id
}

Git ยท Social feed