main
Kyle Bergstedt Publish 0.1.7 8783e4a
// Entry point: launched by bin/adom-forum (a shell shim) via node.
// adom-forum — post to and read the Adom Forum from a container or a laptop.
//
// Auth: a Carbon session token. Resolution order mirrors adom-wiki:
//   ADOM_FORUM_TOKEN → /var/run/adom/api-key → /run/adom/api-key → ~/.config/adom-forum/token
// The token is only ever sent to *.adom.inc, *.adom.internal, or a loopback host.
//
// Every write goes through the forum's Bearer API, which records it as posted
// through an agent and shows a "via <agent>" badge next to the author. Pass
// --agent "Codex Astra" (or set ADOM_AGENT_NAME) so the badge names the tool.
//
// Consent: `thread create`, `reply`, and `edit` print a preview and exit 2 unless
// --permission-to-post-given is passed. Show the user the preview first.

// CommonJS on purpose: this file has no extension, and Node 18 (the version
// in Adom containers) only auto-detects ES modules from Node 22 onward.
'use strict'
const { readFileSync, existsSync, statSync } = require('node:fs')
const { basename, dirname, resolve: resolvePath, extname } = require('node:path')
const { homedir } = require('node:os')
const { createHash } = require('node:crypto')

const VERSION = '0.1.7'

// The CLI runs in the shared Linux runtime behind Hydrogen web, macOS, and
// Windows alike. It depends only on Node 18+ (global fetch, FormData, Blob)
// and the container token file; nothing here touches the host OS.
const NODE_MAJOR = Number(process.versions.node.split('.')[0])
if (NODE_MAJOR < 18) {
  process.stderr.write(`adom-forum: Node 18 or newer is required (found ${process.versions.node})\n`)
  process.exit(1)
}
const DEFAULT_URL = 'https://forum.adom.inc'
const HELP = `adom-forum ${VERSION} — Adom Forum from the terminal

USAGE
  adom-forum spaces [--json]
  adom-forum threads [--space <slug>] [--sort hot|new|top] [--limit N] [--json]
  adom-forum thread get <id> [--json]
  adom-forum thread create --space <slug> --title "<title>" --body <text|@file|-> [--agent "<name>"]
                           [--idempotency-key <key>] [--permission-to-post-given] [--json]
  adom-forum reply <thread-id> --body <text|@file|-> [--agent "<name>"] [--idempotency-key <key>]
                           [--permission-to-post-given] [--json]
  adom-forum edit <post-id> --body <text|@file|-> [--title "<title>"] [--permission-to-post-given] [--json]
  adom-forum history <post-id> [--json]           (forum admins only)
  adom-forum media upload <file> [--json]
  adom-forum widgets [--json]
  adom-forum whoami [--json]

BODY
  --body takes Markdown inline, @path/to/file.md, or - for stdin. Local images referenced as
  ![caption](./photo.png) or ![clip](./demo.mp4) are uploaded and rewritten to gated /media/ URLs
  before posting, so images and videos land exactly where they sit in the Markdown.

WIDGETS
  A line holding only ::name{key="value"} embeds a wiki widget (3D viewer, video player, …).
  \`adom-forum widgets\` lists the ones the forum can render and their attributes.

EDITING
  Only your own posts. --title applies to a thread's opening post. The post is marked edited and
  every earlier version is kept as an internal record; \`history\` prints them for forum admins.
  Post ids are shown by \`thread get\`.

CONSENT
  Writes preview first and exit 2. Re-run with --permission-to-post-given after the user says yes.

ENV
  FORUM_URL (default ${DEFAULT_URL})   ADOM_FORUM_TOKEN   ADOM_AGENT_NAME
`

function fail(message, code = 1, extra = {}) {
  if (flags.json) process.stdout.write(JSON.stringify({ status: 'error', error: message, ...extra }) + '\n')
  else process.stderr.write(`adom-forum: ${message}\n`)
  process.exit(code)
}

function parseArgs(argv) {
  const positional = []
  const flags = {}
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index]
    if (arg.startsWith('--')) {
      const key = arg.slice(2)
      const next = argv[index + 1]
      if (['json', 'permission-to-post-given', 'help', 'version'].includes(key) || next === undefined || next.startsWith('--')) flags[key] = true
      else { flags[key] = next; index += 1 }
    } else positional.push(arg)
  }
  return { positional, flags }
}

const { positional, flags } = parseArgs(process.argv.slice(2))

function resolveToken() {
  if (process.env.ADOM_FORUM_TOKEN) return { token: process.env.ADOM_FORUM_TOKEN.trim(), source: 'env:ADOM_FORUM_TOKEN' }
  for (const path of ['/var/run/adom/api-key', '/run/adom/api-key', resolvePath(homedir(), '.config/adom-forum/token')]) {
    try {
      const value = readFileSync(path, 'utf8').trim()
      if (value) return { token: value, source: `file:${path}` }
    } catch { /* try the next one */ }
  }
  return { token: null, source: null }
}

function baseUrl() {
  return (process.env.FORUM_URL || DEFAULT_URL).replace(/\/+$/, '')
}

function trustedHost(url) {
  const host = new URL(url).hostname
  return host === 'localhost' || host === '127.0.0.1' || host.endsWith('.adom.inc') || host.endsWith('.adom.internal')
}

async function api(method, path, { body, form, idempotencyKey } = {}) {
  const url = `${baseUrl()}${path}`
  const { token, source } = resolveToken()
  // SvelteKit rejects form-encoded and multipart POSTs whose Origin does not
  // match the site (its CSRF guard), which covers the image upload. Sending
  // the forum's own origin satisfies it; JSON requests are unaffected.
  const headers = { 'user-agent': `adom-forum/${VERSION}`, accept: 'application/json', origin: baseUrl() }
  if (token) {
    if (!trustedHost(url)) fail(`refusing to send the Adom token to ${new URL(url).hostname}`)
    headers.authorization = `Bearer ${token}`
  }
  const agent = flags.agent || process.env.ADOM_AGENT_NAME
  if (agent) headers['x-adom-agent'] = String(agent)
  if (idempotencyKey) headers['idempotency-key'] = idempotencyKey
  let payload
  if (form) payload = form
  else if (body !== undefined) { headers['content-type'] = 'application/json'; payload = JSON.stringify(body) }
  const response = await fetch(url, { method, headers, body: payload })
  const text = await response.text()
  let data = null
  try { data = text ? JSON.parse(text) : null } catch { data = { raw: text } }
  if (!response.ok) {
    const message = data?.error || `${response.status} ${response.statusText}`
    const hint = response.status === 401 ? (token ? ` (token from ${source} was rejected)` : ' (no token found; set ADOM_FORUM_TOKEN or run inside an Adom container)') : ''
    fail(`${message}${hint}`, response.status === 429 ? 3 : 1, { code: data?.code, status: response.status, data: data?.data })
  }
  return { data, headers: response.headers }
}

function readBody(value) {
  if (value === undefined || value === true) fail('--body is required (text, @file, or - for stdin)')
  if (value === '-') return { text: readFileSync(0, 'utf8'), dir: process.cwd() }
  if (String(value).startsWith('@')) {
    const path = resolvePath(String(value).slice(1))
    return { text: readFileSync(path, 'utf8'), dir: dirname(path) }
  }
  return { text: String(value), dir: process.cwd() }
}

const IMAGE_TYPES = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' }
const VIDEO_TYPES = { '.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime' }

// Videos go straight to object storage: presign, PUT, confirm. The forum
// never proxies the bytes.
async function uploadVideo(path, type) {
  const size = statSync(path).size
  const { data: ticket } = await api('POST', '/api/media/videos/presign', { body: { filename: basename(path), content_type: type, size } })
  const put = await fetch(ticket.upload_url, { method: ticket.upload_method || 'PUT', headers: { 'content-type': type }, body: readFileSync(path) })
  if (!put.ok) fail(`${basename(path)}: storage rejected the upload (${put.status})`)
  const { data } = await api('POST', '/api/media/videos/confirm', { body: { id: ticket.id } })
  return data
}

async function uploadFile(path) {
  const extension = extname(path).toLowerCase()
  if (VIDEO_TYPES[extension]) return uploadVideo(path, VIDEO_TYPES[extension])
  const type = IMAGE_TYPES[extension]
  if (!type) fail(`${path}: only PNG, JPEG, GIF, WebP images and MP4, WebM, MOV videos can be uploaded`)
  const bytes = readFileSync(path)
  const form = new FormData()
  form.append('file', new Blob([bytes], { type }), basename(path))
  const { data } = await api('POST', '/api/media', { form })
  return data
}

const IMAGE_PATTERN = /!\[([^\]]*)\]\(([^)\s]+)(\s+"[^"]*")?\)/g

function localImagePaths(markdown, dir) {
  const paths = new Set()
  for (const match of markdown.matchAll(IMAGE_PATTERN)) {
    const target = match[2]
    if (/^(https?:)?\/\//i.test(target) || target.startsWith('/media/') || target.startsWith('data:')) continue
    const path = resolvePath(dir, target)
    if (existsSync(path) && statSync(path).isFile()) paths.add(path)
  }
  return [...paths]
}

// Upload local images referenced in the Markdown and rewrite their URLs.
// Only called once the user has approved the post, so a preview never leaves
// orphaned uploads behind.
async function localizeImages(markdown, dir) {
  const pattern = IMAGE_PATTERN
  const uploads = new Map()
  for (const path of localImagePaths(markdown, dir)) {
    if (!uploads.has(path)) {
      const uploaded = await uploadFile(path)
      uploads.set(path, uploaded.url)
      if (!flags.json) process.stderr.write(`   ${VIDEO_TYPES[extname(path).toLowerCase()] ? 'video' : 'image'} → ${uploaded.url} (${basename(path)})\n`)
    }
  }
  const rewritten = markdown.replace(pattern, (whole, alt, target, title = '') => {
    if (/^(https?:)?\/\//i.test(target) || target.startsWith('/media/') || target.startsWith('data:')) return whole
    const path = resolvePath(dir, target)
    return uploads.has(path) ? `![${alt}](${uploads.get(path)}${title})` : whole
  })
  return { markdown: rewritten, uploaded: uploads.size }
}

function preview(kind, fields, markdown) {
  process.stdout.write(`\n──── preview: ${kind} ────\n`)
  for (const [key, value] of Object.entries(fields)) process.stdout.write(`${key}: ${value}\n`)
  process.stdout.write(`\n${markdown.trim()}\n──────────────────────────\n`)
  process.stdout.write(`Not posted. Show this to the user; re-run with --permission-to-post-given once they approve.\n`)
}

function out(value, human) {
  if (flags.json) process.stdout.write(JSON.stringify({ status: 'ok', data: value }) + '\n')
  else process.stdout.write(human)
}

function idempotencyFor(explicit, parts) {
  if (explicit && explicit !== true) return String(explicit)
  return `adom-forum:${createHash('sha256').update(parts.join('')).digest('hex').slice(0, 32)}`
}

async function main() {
  if (flags.version) { process.stdout.write(`adom-forum ${VERSION}\n`); return }
  if (flags.help || positional.length === 0) { process.stdout.write(HELP); return }
  const [command, sub, ...rest] = positional

  if (command === 'whoami') {
    const { token, source } = resolveToken()
    if (!token) fail('no token found; set ADOM_FORUM_TOKEN or run inside an Adom container', 1)
    const { data } = await api('GET', '/api/activity-counts')
    out({ forum: baseUrl(), token_source: source, unread: data }, `forum: ${baseUrl()}\ntoken: ${source}\nunread messages: ${data?.messages ?? 0}, notifications: ${data?.notifications ?? 0}\n`)
    return
  }

  if (command === 'spaces') {
    const { data } = await api('GET', '/api/spaces')
    out(data.spaces, data.spaces.map((space) => `${space.slug.padEnd(16)} ${space.name.padEnd(16)} ${String(space.thread_count).padStart(4)}  ${space.description}`).join('\n') + '\n')
    return
  }

  if (command === 'threads') {
    const params = new URLSearchParams()
    if (flags.space) params.set('space', String(flags.space))
    if (flags.sort) params.set('sort', String(flags.sort))
    if (flags.limit) params.set('limit', String(flags.limit))
    const { data } = await api('GET', `/api/threads?${params}`)
    out(data.threads, data.threads.map((thread) => `${thread.id}  ${String(thread.votes).padStart(3)}▲ ${String(thread.replies).padStart(3)}💬  [${thread.space}] ${thread.title} — ${thread.author.display_name}${thread.agent ? ` via ${thread.agent}` : ''}`).join('\n') + '\n')
    return
  }

  if (command === 'thread' && sub === 'get') {
    const id = rest[0]
    if (!id) fail('thread id required')
    const { data } = await api('GET', `/api/threads/${encodeURIComponent(id)}`)
    const lines = [`# ${data.thread.title}`, `${data.thread.url} · ${data.thread.space} · by ${data.thread.author.display_name}${data.thread.agent ? ` via ${data.thread.agent}` : ''}`, '']
    for (const post of data.posts) lines.push(`--- ${post.opener ? 'opener' : 'reply'} ${post.id} · ${post.author.display_name}${post.agent ? ` via ${post.agent}` : ''} · ${post.created_at}${post.edited_at ? ` · edited ${post.edited_at}` : ''}`, post.body ?? '(hidden)', '')
    out(data, lines.join('\n'))
    return
  }

  if (command === 'thread' && sub === 'create') {
    const space = flags.space
    const title = flags.title
    if (!space || space === true) fail('--space is required (see `adom-forum spaces`)')
    if (!title || title === true) fail('--title is required')
    const { text, dir } = readBody(flags.body)
    if (!flags['permission-to-post-given']) {
      preview('new thread', { space, title, agent: flags.agent || process.env.ADOM_AGENT_NAME || '(none)', images_to_upload: localImagePaths(text, dir).map((path) => basename(path)).join(', ') || 'none' }, text)
      process.exit(2)
    }
    // Keyed on the source Markdown so a retry replays even though uploads mint new URLs.
    const key = idempotencyFor(flags['idempotency-key'], ['thread', String(space), String(title), text])
    const { markdown } = await localizeImages(text, dir)
    const { data, headers } = await api('POST', '/api/threads', { body: { space, title, body: markdown }, idempotencyKey: key })
    out({ ...data, replayed: headers.get('idempotent-replayed') === 'true' }, `${headers.get('idempotent-replayed') === 'true' ? 'already posted' : 'posted'}: ${data.url}\n`)
    return
  }

  if (command === 'reply') {
    const id = sub
    if (!id) fail('thread id required')
    const { text, dir } = readBody(flags.body)
    if (!flags['permission-to-post-given']) {
      preview('reply', { thread: id, agent: flags.agent || process.env.ADOM_AGENT_NAME || '(none)', images_to_upload: localImagePaths(text, dir).map((path) => basename(path)).join(', ') || 'none' }, text)
      process.exit(2)
    }
    const key = idempotencyFor(flags['idempotency-key'], ['reply', String(id), text])
    const { markdown } = await localizeImages(text, dir)
    const { data, headers } = await api('POST', `/api/threads/${encodeURIComponent(id)}/posts`, { body: { body: markdown }, idempotencyKey: key })
    out({ ...data, replayed: headers.get('idempotent-replayed') === 'true' }, `${headers.get('idempotent-replayed') === 'true' ? 'already posted' : 'posted'}: ${data.url}\n`)
    return
  }

  if (command === 'edit') {
    const id = sub
    if (!id) fail('post id required (see `adom-forum thread get <id>`)')
    const { text, dir } = readBody(flags.body)
    const title = flags.title === undefined ? undefined : String(flags.title)
    if (flags.title === true) fail('--title needs a value')
    if (!flags['permission-to-post-given']) {
      preview('edit', { post: id, ...(title !== undefined ? { title } : {}), images_to_upload: localImagePaths(text, dir).map((path) => basename(path)).join(', ') || 'none' }, text)
      process.exit(2)
    }
    const { markdown } = await localizeImages(text, dir)
    const { data } = await api('PATCH', `/api/posts/${encodeURIComponent(id)}`, { body: { body: markdown, ...(title !== undefined ? { title } : {}) } })
    out(data, `${data.changed ? 'edited' : 'unchanged'}: ${data.url}\n`)
    return
  }

  if (command === 'history') {
    const id = sub
    if (!id) fail('post id required')
    const { data } = await api('GET', `/api/posts/${encodeURIComponent(id)}/revisions`)
    const lines = []
    data.versions.forEach((version, index) => lines.push(`--- ${version.current ? 'current' : `version ${data.versions.length - index}`} · ${version.written_at}`, ...(version.title ? [`# ${version.title}`] : []), version.body, ''))
    out(data, lines.join('\n'))
    return
  }

  if (command === 'media' && sub === 'upload') {
    const path = rest[0]
    if (!path) fail('file path required')
    const data = await uploadFile(resolvePath(path))
    out(data, `${data.url}\n`)
    return
  }

  if (command === 'widgets') {
    const { data } = await api('GET', '/api/widgets')
    const width = Math.max(...data.widgets.map((widget) => widget.name.length))
    const lines = data.widgets.map((widget) => `${widget.name.padEnd(width)}  ::${widget.name}{${widget.attrs.map((attr) => `${attr}=""`).join(' ')}}`)
    if (!data.available) lines.push('', 'The wiki registry is unreachable right now; only built-in widgets will render.')
    lines.push('', 'Put the line alone in the body. Paths point at files on a public wiki page, e.g. src="/owner/slug/render/board.glb".')
    out(data, lines.join('\n') + '\n')
    return
  }

  fail(`unknown command: ${positional.join(' ')}\n\n${HELP}`)
}

main().catch((cause) => fail(cause instanceof Error ? cause.message : String(cause)))