anbot

78ef64a / post-http.mjs

View file at this commit

diff --git a/post-http.mjs b/post-http.mjs
new file mode 100644
index 0000000..0784e31
--- /dev/null
+++ b/post-http.mjs
@@ -0,0 +1,54 @@
+import { parseJson } from './core.mjs'
+import { verifyPost } from './social.mjs'
+import { storePost } from './social-store.mjs'
+
+const maxPostBytes = 32768
+
+function reply(response, status, body) {
+  response.writeHead(status, {
+    'Content-Type': 'application/json', 'Cache-Control': 'no-store'
+  }).end(JSON.stringify(body))
+}
+
+export async function receivePost(root, request, response, isAllowed) {
+  if (!isAllowed) {
+    reply(response, 403, { error: 'Post submission disabled' })
+    return
+  }
+  if (!/^application\/json(?:\s*;|$)/i.test(request.headers['content-type'] ?? '')) {
+    reply(response, 415, { error: 'Expected application/json' })
+    return
+  }
+
+  let record, post
+  try {
+    let size = 0
+    const chunks = []
+    for await (const chunk of request.iterator({ destroyOnReturn: false })) {
+      size += chunk.length
+      if (size > maxPostBytes) {
+        reply(response, 413, { error: 'Post record exceeds 32 KiB' })
+        request.resume()
+        return
+      }
+      chunks.push(chunk)
+    }
+    record = parseJson(Buffer.concat(chunks, size))
+    post = await verifyPost(record)
+  } catch {
+    reply(response, 400, { error: 'Invalid signed post' })
+    return
+  }
+
+  try {
+    if (!isAllowed(post.author)) {
+      reply(response, 403, { error: 'Post author is not allowlisted' })
+      return
+    }
+    const created = await storePost(root, record)
+    reply(response, created ? 201 : 200, { id: post.id })
+  } catch (error) {
+    console.error(error.message)
+    reply(response, 503, { error: 'Post storage unavailable' })
+  }
+}

Git ยท Social feed