source: Klonkt/src/routes/activitypub.js@ 3654057

main
Last change on this file since 3654057 was f3caf19, checked in by Robin Genis <roboburr@…>, 6 weeks ago

shaer:booster.emojis: custom-emoji in de booster-naam (X boosted)

De 'X boosted'-regel toonde nog letterlijke shortcodes als de booster een
emoji-naam heeft. Klonkt geeft de booster-emoji's nu mee als shaer:booster.emojis.
Nieuwe boosts: direct uit de capture (booster.emojis). Bestaande boosts: de rij
bewaart geen booster-URI, dus self-heal (v13 -> v14) resolvet 'm via webfinger op
de reblog_handle, gescoped op id+slug (een note kan door verschillenden geboost
zijn).

Changed files:
src/config/database.js

  • ap_timeline.reblog_emoji_json kolom

src/services/ActivityPubService.js

  • boost-capture bewaart booster.emojis in reblog_emoji_json
  • self-heal v14: booster-emoji backfillen via webfinger (gated op shortcode-naam)

src/routes/activitypub.js

  • shaer:booster.emojis meegeserveerd

remarks: 180 tests groen.

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 21.4 KB
RevLine 
[6bd25d1]1/**
2 * ActivityPub — public endpoints (Phase 1: discover + fetch).
3 *
4 * GET /.well-known/webfinger?resource=acct:<slug>@<host>
5 * GET /ap/users/:slug actor (content-negotiated: AP-JSON vs redirect to HTML profile)
6 * GET /ap/users/:slug/outbox OrderedCollection of Create(Note)
7 * GET /ap/users/:slug/followers count-only OrderedCollection
[75bda38]8 * GET /ap/users/:slug/featured pinned posts (Mastodon "Featured" tab)
[6bd25d1]9 * GET /ap/notes/:id a single Note
10 * POST /ap/users/:slug/inbox, /ap/inbox → 202 (Follow/Accept + signature verify: next step)
11 *
12 * Mounted before resolveSite; resolves the site by slug itself.
13 */
14import express from 'express';
[d7526bd]15import { readFileSync } from 'fs';
[6bd25d1]16import db from '../config/database.js';
17import AP from '../services/ActivityPubService.js';
[75ab393]18import { apReadLimiter, apInboxLimiter } from '../middleware/rate-limit.js';
[283f618]19import { apEnabled } from '../services/SettingsService.js';
[dd568e7]20import OAuth from '../services/OAuthService.js';
[e61c289]21import * as Guardianship from '../services/guardianship/index.js';
[e6c6e6f]22import multer from 'multer';
23import path from 'path';
24import fs from 'fs';
25import { fileURLToPath } from 'url';
26import { randomUUID } from 'crypto';
[6bd25d1]27
28const router = express.Router();
[283f618]29// The whole fediverse layer can be turned off (solo "no federation" mode):
30// then /ap/*, WebFinger and NodeInfo are simply gone — the site is undiscoverable
[89cc8c4]31// and unfederatable. CRITICAL: this router is mounted at root (app.use(apRoutes)), so a
32// blanket res.status(404) here ran for EVERY request and 404'd the whole site when AP was
33// off. Use next('router') to SKIP this router entirely and let the normal routes handle it
34// (the /ap/* paths then fall through to the app's normal 404, which is correct).
35router.use((req, res, next) => { if (!apEnabled()) return next('router'); next(); });
[75ab393]36// Generous per-IP baseline over all /ap/* (reads). The inbox POST gets an
37// additional, tighter cap inline (it triggers outbound fetches).
38router.use(apReadLimiter);
[d7526bd]39let _ver = '1.0.0';
40try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
[6bd25d1]41
42const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
43const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
44const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
45const primarySlug = () => { const r = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get(); return r && r.slug; };
46
47// ── WebFinger ─────────────────────────────────────────────────────
48router.get('/.well-known/webfinger', (req, res) => {
49 const m = String(req.query.resource || '').match(/^acct:([^@]+)@(.+)$/i);
50 if (!m) return res.status(400).type('text/plain').send('bad resource');
51 const site = publicSite(m[1]);
52 if (!site) return res.status(404).end();
53 res.type('application/jrd+json; charset=utf-8');
54 res.set('Cache-Control', 'public, max-age=300');
[f2796d3]55 const actorUri = AP.actorId(baseUrl(req), site.slug);
56 const profileUrl = baseUrl(req) + (site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`);
[6bd25d1]57 res.send(JSON.stringify({
58 subject: `acct:${site.slug}@${hostOf(req)}`,
[f2796d3]59 aliases: [actorUri, profileUrl],
60 links: [
61 { rel: 'self', type: 'application/activity+json', href: actorUri },
62 { rel: 'http://webfinger.net/rel/profile-page', type: 'text/html', href: profileUrl },
63 ],
[6bd25d1]64 }));
65});
66
67// ── Actor ─────────────────────────────────────────────────────────
68router.get('/ap/users/:slug', (req, res) => {
69 const site = publicSite(req.params.slug);
70 if (!site) return res.status(404).end();
71 if (!AP.apWants(req)) {
72 // A browser hit the AP actor URL → send them to the human profile.
73 const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
74 return res.redirect(302, baseUrl(req) + human);
75 }
76 site.primary_slug = primarySlug();
77 AP.sendAP(res, AP.buildActor(baseUrl(req), site));
78});
79
80// ── Outbox ────────────────────────────────────────────────────────
[c66cbb4]81router.get('/ap/users/:slug/outbox', async (req, res) => {
[6bd25d1]82 const site = publicSite(req.params.slug);
83 if (!site) return res.status(404).end();
[c66cbb4]84 // Authorized fetch (FEP-633c §5.3 note): a committed guardian doing a SIGNED
85 // GET may read the ward's fan-only history too, without appearing as a
86 // follower. Unsigned / non-guardian callers get the public collection only.
87 let asGuardian = false;
88 if (req.headers['signature']) {
89 const verified = await AP.verifyRequest(req).catch(() => null);
90 asGuardian = !!(verified && AP.isWardGuardian(req.params.slug, verified.id));
91 }
92 const fanClause = asGuardian ? '' : "AND (fan_only IS NULL OR fan_only = 0)";
[6bd25d1]93 const posts = db.prepare(
[857a06f]94 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
[c66cbb4]95 FROM posts WHERE site_id = ? AND status = 'published' ${fanClause}
[6bd25d1]96 ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
97 ).all(site.id);
[c66cbb4]98 AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, posts), asGuardian ? 'private, no-store' : undefined);
[6bd25d1]99});
100
[8b07c12]101// ── Blocked collection (owner only, AP §5.6) ──────────────────────
102// The server blocklist is the source of truth for Shaer's "in Orbit":
103// clients read it here instead of keeping their own state. Actor-kind
104// blocks only (domain blocks are instance policy, not an Orbit member).
105router.get('/ap/users/:slug/blocked', (req, res) => {
106 const auth = OAuth.verifyBearer(req.headers.authorization);
107 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
108 const base = baseUrl(req);
109 const items = AP.listBlocks(auth.site.slug)
110 .filter((b) => b.kind === 'actor')
111 .map((b) => b.target);
112 AP.sendAP(res, {
113 '@context': AP.AP_CONTEXT,
114 id: `${base}/ap/users/${auth.site.slug}/blocked`,
115 type: 'OrderedCollection',
116 totalItems: items.length,
117 orderedItems: items,
118 });
119});
120
[e61c289]121// ── Guardian queues (owner only, FEP-633c, shaer:queues) ──────────
122// The dashboard collections the Shaer clients read: pending adoption offers,
123// gated follows (empty in Klonkt for now) and the guardian's wards. Same
124// contract as the Shaer test daemon.
125function queueRoute(name, build) {
126 router.get(`/ap/users/:slug/queues/${name}`, (req, res) => {
127 const auth = OAuth.verifyBearer(req.headers.authorization);
128 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
129 const base = baseUrl(req);
130 const me = `${base}/ap/users/${auth.site.slug}`;
131 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...build(`${me}/queues/${name}`, auth.site.slug, me) });
132 });
133}
134queueRoute('offers', (id, slug, me) => Guardianship.offersCollection(id, slug, me));
135queueRoute('follows', (id) => Guardianship.followsCollection(id));
136queueRoute('wards', (id, slug) => Guardianship.wardsCollection(id, slug));
137
[0cea12b]138// ── Inbox read (owner only, AP C2S) ───────────────────────────────
139// GET on the inbox is part of ActivityPub C2S: the account owner (a bearer
140// scoped to this site) reads recent inbound posts (the timeline: accounts
141// they follow) as Create(Note) items, so an app (Shaer) can build a unified
142// feed. Anyone else gets 403; the inbox stays write-only for the public.
143router.get('/ap/users/:slug/inbox', (req, res) => {
144 const auth = OAuth.verifyBearer(req.headers.authorization);
145 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
146 const base = baseUrl(req);
147 const items = AP.getTimeline(auth.site.slug, 60).map((t) => ({
148 id: `${t.id}#create`,
149 type: 'Create',
150 actor: t.author_uri,
151 published: t.published || t.created_at || undefined,
152 object: {
153 id: t.id,
154 type: 'Note',
155 attributedTo: t.author_uri,
156 content: t.content,
157 url: t.url || undefined,
158 published: t.published || t.created_at || undefined,
159 sensitive: !!t.nsfw,
160 summary: t.cw || undefined,
[fb30b5d]161 // Friends' media travels along (media_json → AS2 attachment), so the
162 // client renders their images/audio like own outbox posts.
163 attachment: AP.timelineAttachments(t.media_json),
[eb36688]164 // The note's preserved tags, so the client can render them: FEP-9098
165 // Emoji tags (:shortcode: → image) and FEP-e232 Link tags (quotes /
166 // inline object references). Combined into one `tag` array; omitted
167 // when the note has neither.
168 tag: (() => {
169 const tags = [...(AP.timelineEmojis(t.emoji_json) || []), ...(AP.timelineObjectLinks(t.link_json) || [])];
170 return tags.length ? tags : undefined;
171 })(),
[6fd0e20]172 // FEP-044f: the resolved quoted post (author + content), so the client
173 // renders an embedded quote card instead of a bare link. Omitted when the
174 // note has no quote or the quoted post could not be resolved.
175 'shaer:quote': AP.timelineQuote(t.quote_json),
[46a30f0]176 // The post author's display info (name / @handle / avatar), so every card
177 // gets a byline header like the quote card. attributedTo stays the bare
178 // actor URI; this is the resolved presentation Klonkt already stored.
179 'shaer:author': (t.author_name || t.author_handle || t.author_icon) ? {
180 name: t.author_name || undefined, handle: t.author_handle || undefined,
181 icon: t.author_icon || undefined, url: t.author_url || undefined,
[a677616]182 // FEP-9098: emojis in the display name (":shortcode:"), if any.
183 emojis: (() => { try { return t.author_emoji_json ? JSON.parse(t.author_emoji_json) : undefined; } catch { return undefined; } })(),
[46a30f0]184 } : undefined,
185 // When a followed account boosted this, who did ("X boosted"). Omitted for
186 // ordinary posts.
187 'shaer:booster': (t.reblog_name || t.reblog_handle || t.reblog_icon) ? {
188 name: t.reblog_name || undefined, handle: t.reblog_handle || undefined,
189 icon: t.reblog_icon || undefined,
[f3caf19]190 // FEP-9098: emojis in the booster's display name (":shortcode:"), if any.
191 emojis: (() => { try { return t.reblog_emoji_json ? JSON.parse(t.reblog_emoji_json) : undefined; } catch { return undefined; } })(),
[46a30f0]192 } : undefined,
[0cea12b]193 },
194 }));
195 AP.sendAP(res, {
196 '@context': AP.AP_CONTEXT,
197 id: `${base}/ap/users/${auth.site.slug}/inbox`,
198 type: 'OrderedCollection',
199 totalItems: items.length,
200 orderedItems: items,
201 });
202});
203
[e6c6e6f]204// ── uploadMedia (owner only, AP C2S) ──────────────────────────────
205// The actor advertises endpoints.uploadMedia; this implements it. A bearer
206// scoped to this site uploads one image/audio/video (multipart field "file",
207// AP convention) into the same store the reply editor uses, and gets back
208// { url, mediaType, name } to attach on a note (e.g. the help-buoy capture).
209const AP_MEDIA_DIR = path.resolve(
210 process.env.REPLY_MEDIA_PATH ||
211 path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'storage', 'media', 'reply-media')
212);
213fs.mkdirSync(AP_MEDIA_DIR, { recursive: true });
214const AP_MEDIA_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.m4a', '.ogg', '.opus', '.flac', '.wav', '.mp4', '.webm', '.mov']);
215const apMediaUpload = multer({
216 storage: multer.diskStorage({
217 destination: (req, file, cb) => cb(null, AP_MEDIA_DIR),
218 filename: (req, file, cb) => cb(null, `${randomUUID()}${path.extname(file.originalname || '').toLowerCase()}`),
219 }),
220 limits: { fileSize: 32 * 1024 * 1024 },
221 fileFilter: (req, file, cb) => {
222 const ext = path.extname(file.originalname || '').toLowerCase();
223 if (!AP_MEDIA_EXT.has(ext)) return cb(new Error('Media must be an image, audio or video file'));
224 cb(null, true);
225 },
226});
227router.post('/ap/users/:slug/uploadMedia', (req, res) => {
228 const auth = OAuth.verifyBearer(req.headers.authorization);
229 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
230 apMediaUpload.single('file')(req, res, (err) => {
231 if (err) return res.status(400).json({ error: err.message });
232 if (!req.file) return res.status(400).json({ error: 'No file' });
233 const mime = String(req.file.mimetype || '');
234 if (!/^(image|audio|video)\//.test(mime)) {
235 try { fs.unlinkSync(req.file.path); } catch { /* best effort */ }
236 return res.status(400).json({ error: 'Media must be an image, audio or video file' });
237 }
238 res.status(201).json({
239 url: '/media/reply-media/' + req.file.filename,
240 mediaType: mime,
241 name: String(req.file.originalname || '').slice(0, 120),
242 });
243 });
244});
245
[4407c67]246// ── Followers (count-only public, full for the owner) ─────────────
247// A C2S bearer scoped to this site (the account owner) gets the real actor
248// URIs so their own client can build a friends list; everyone else gets the
249// count only (privacy).
[30871c1]250// FEP-9876: enrichment is opt-in via `Prefer: return=representation` (RFC 7240).
251// Returns true and sets the response headers when the owner asked for it.
252function wantsEnriched(req, res) {
253 res.set('Vary', 'Prefer'); // enriched and bare are two representations
254 if (AP.prefersEnriched(req.get('Prefer'))) {
255 res.set('Preference-Applied', 'return=representation');
256 return true;
257 }
258 return false;
259}
260
[6bd25d1]261router.get('/ap/users/:slug/followers', (req, res) => {
[4407c67]262 const auth = OAuth.verifyBearer(req.headers.authorization);
263 const owner = auth && auth.site.slug === req.params.slug;
264 const site = owner ? auth.site : publicSite(req.params.slug);
[6bd25d1]265 if (!site) return res.status(404).end();
[4407c67]266 if (owner) {
[7922694]267 const uris = db.prepare('SELECT actor_uri FROM ap_followers WHERE slug = ? ORDER BY created_at').all(site.slug).map((r) => r.actor_uri);
[30871c1]268 // Default = bare references; enrich only when the client asks (FEP-9876).
269 const items = wantsEnriched(req, res) ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
[4407c67]270 return AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, items.length, items));
271 }
[6bd25d1]272 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
273 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
274});
275
[4407c67]276// ── Following (count-only public, full for the owner) ─────────────
[f2796d3]277router.get('/ap/users/:slug/following', (req, res) => {
[4407c67]278 const auth = OAuth.verifyBearer(req.headers.authorization);
279 const owner = auth && auth.site.slug === req.params.slug;
280 const site = owner ? auth.site : publicSite(req.params.slug);
[f2796d3]281 if (!site) return res.status(404).end();
[4407c67]282 if (owner) {
[30871c1]283 const enrich = wantsEnriched(req, res); // FEP-9876 opt-in
[4407c67]284 let items = [];
[30871c1]285 try {
286 const uris = db.prepare("SELECT actor_uri FROM ap_following WHERE slug = ? AND status = 'accepted' ORDER BY created_at").all(site.slug).map((r) => r.actor_uri);
287 items = enrich ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
288 } catch { /* table may not exist */ }
[4407c67]289 return AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, items.length, items));
290 }
[f2796d3]291 let n = 0;
292 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
293 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n));
294});
295
[75bda38]296// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
297router.get('/ap/users/:slug/featured', (req, res) => {
298 const site = publicSite(req.params.slug);
299 if (!site) return res.status(404).end();
[2af2e69]300 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
301 // last-processed-first). So we emit it reversed (lowest pin priority first,
302 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
[75bda38]303 const posts = db.prepare(
[857a06f]304 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
[75bda38]305 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
306 AND pinned IS NOT NULL AND pinned > 0
[2af2e69]307 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
[75bda38]308 ).all(site.id);
309 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
310});
311
[6bd25d1]312// ── Note ──────────────────────────────────────────────────────────
313router.get('/ap/notes/:id', (req, res) => {
314 const post = db.prepare(
315 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
316 ).get(req.params.id);
[55bc7f9]317 if (!post) {
318 // Could be one of OUR outbound replies (ap_outbox), not a post.
319 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
[49edc72]320 if (!note) return res.status(404).end();
321 if (!AP.apWants(req)) {
322 // A browser hit a reply's AP URL → send them to the source it replies to
323 // (where the post + its reactions live), falling back to the site home.
324 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
325 ? note.inReplyTo : (baseUrl(req) + '/');
326 return res.redirect(302, src);
327 }
[d3b9f68]328 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
[55bc7f9]329 }
[6bd25d1]330 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
331 if (!site) return res.status(404).end();
[49edc72]332 const note = AP.buildNote(baseUrl(req), site, post);
333 if (!AP.apWants(req)) {
334 // A browser hit a post's AP note URL → send them to the human post page
335 // (which shows the post + its "from the fediverse" reactions).
336 return res.redirect(302, note.url || (baseUrl(req) + '/'));
337 }
[d3b9f68]338 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
[6bd25d1]339});
340
[d7526bd]341// ── Replies collection ── lets remote servers fetch a post's whole thread.
342router.get('/ap/notes/:id/replies', (req, res) => {
343 const base = baseUrl(req);
344 const items = AP.getReplyUris(base, req.params.id);
345 AP.sendAP(res, {
[d3b9f68]346 '@context': AP.AP_CONTEXT,
[d7526bd]347 id: `${base}/ap/notes/${req.params.id}/replies`,
348 type: 'OrderedCollection',
349 totalItems: items.length,
350 orderedItems: items,
351 });
352});
353
354// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
355router.get('/.well-known/nodeinfo', (req, res) => {
356 res.type('application/json');
357 res.set('Cache-Control', 'public, max-age=3600');
358 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
359});
360router.get('/nodeinfo/2.1', (req, res) => {
361 let users = 0; let posts = 0;
[f2796d3]362 // "users" = public AP actors (sites), not the admin/member account rows.
363 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
[d7526bd]364 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
365 res.type('application/json; charset=utf-8');
366 res.set('Cache-Control', 'public, max-age=600');
367 res.send(JSON.stringify({
368 version: '2.1',
369 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
370 protocols: ['activitypub'],
371 services: { inbound: [], outbound: [] },
372 openRegistrations: false,
373 usage: { users: { total: users }, localPosts: posts },
374 metadata: { nodeName: 'Klonkt' },
375 }));
376});
377
[5bf63b7]378// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
379const apJson = express.json({
380 type: ['application/activity+json', 'application/ld+json', 'application/json'],
381 limit: '1mb',
382 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
383});
[75ab393]384router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
[5bf63b7]385 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
386 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
[6bd25d1]387});
388
[dd568e7]389// ── Outbox POST: ActivityPub Client-to-Server ─────────────────────
390// A bearer-authenticated client (Shaer) POSTs an activity; we translate it onto
391// the normal delivery machinery. The token is scoped to one user+site (OAuth
392// consent), so it must match the slug in the URL. (Declared after apJson, which
393// this shares with the inbox handler.)
394router.post('/ap/users/:slug/outbox', apInboxLimiter, apJson, async (req, res) => {
395 const auth = OAuth.verifyBearer(req.headers.authorization);
396 if (!auth) { res.set('WWW-Authenticate', 'Bearer'); return res.status(401).json({ error: 'invalid_token' }); }
397 if (auth.site.slug !== req.params.slug) return res.status(403).json({ error: 'wrong_site', detail: 'token is scoped to a different site' });
398 if (auth.user.readonly) return res.status(403).json({ error: 'read_only_account' });
399
400 const out = await AP.ingestOutboxActivity(auth.site, auth.user, req.body);
401 if (out.error) return res.status(out.status || 400).json({ error: out.error, detail: out.detail });
402 // 201 Created → Location header (AP spec); 202 Accepted for side-effect verbs.
403 if (out.status === 201 && out.url) res.set('Location', out.url);
404 return res.status(out.status || 202).json({ ok: true, id: out.id, url: out.url });
405});
406
[6bd25d1]407export default router;
Note: See TracBrowser for help on using the repository browser.