source: Klonkt/test/activitypub-as2.test.js@ a95dbfd

main
Last change on this file since a95dbfd was 432831c, checked in by roboburr <roboburr@…>, 2 months ago

test(federation): AS2/JSON-LD validity guard — every emitted term must be declared

Builds the actor, a kitchen-sink note/Create and the collections via the real builders and
asserts every property key + type value is an AS2-core/security term OR declared in AP_CONTEXT.
A future feature that emits an undeclared term fails this test → declare it in AP_CONTEXT (or
the AS2 allowlist). Keeps Klonkt's output valid AS2/JSON-LD permanently — not just "Mastodon
tolerates it". node:test, in-memory SQLite, no extra deps. Run: npm test

  • test/activitypub-as2.test.js (new)

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 4.5 KB
Line 
1// AS2 / JSON-LD validity guard.
2//
3// Every property key and `type` value our ActivityPub objects emit MUST be either an AS2-core
4// (or security/v1) term OR declared in the federation @context (AP_CONTEXT). A new feature that
5// emits an undeclared term fails this test → declare it in AP_CONTEXT (extensions) or add it to
6// the AS2 allowlist below. This keeps Klonkt's output valid AS2/JSON-LD forever — not just
7// "Mastodon tolerates it". No extra deps; in-memory SQLite. Run: npm test
8import { test } from 'node:test';
9import assert from 'node:assert/strict';
10
11process.env.DATABASE_PATH = ':memory:';
12process.env.PUBLIC_BASE_URL = 'https://test.example';
13
14const dbMod = await import('../src/config/database.js');
15const db = dbMod.default;
16dbMod.initializeDatabase();
17const AP = (await import('../src/services/ActivityPubService.js')).default;
18
19const BASE = 'https://test.example';
20
21// AS2-core + security/v1 vocabulary Klonkt uses (stable — only extend when AS2/security itself
22// adds a term we adopt). JSON-LD keywords included.
23const AS2 = new Set([
24 '@context', '@id', '@type',
25 'id', 'type', 'actor', 'object', 'target', 'to', 'cc',
26 'content', 'name', 'summary', 'url', 'href', 'mediaType',
27 'published', 'updated', 'attributedTo', 'inReplyTo', 'replies',
28 'attachment', 'tag', 'icon', 'image', 'duration',
29 'totalItems', 'orderedItems', 'items', 'first', 'last', 'partOf', 'next', 'prev',
30 'preferredUsername', 'inbox', 'outbox', 'followers', 'following', 'endpoints', 'sharedInbox',
31 'publicKey', 'owner', 'publicKeyPem',
32 'Note', 'Person', 'Create', 'Update', 'Delete', 'Tombstone', 'Announce', 'Like', 'Follow',
33 'Accept', 'Reject', 'Undo', 'Add', 'Remove', 'Document', 'Image', 'Audio', 'Video',
34 'Mention', 'Link', 'Collection', 'OrderedCollection', 'OrderedCollectionPage',
35]);
36
37// The extension terms = exactly the keys declared in AP_CONTEXT's term-definition object.
38const ctxTerms = new Set();
39for (const part of AP.AP_CONTEXT) if (part && typeof part === 'object') for (const k of Object.keys(part)) ctxTerms.add(k);
40const allowed = new Set([...AS2, ...ctxTerms]);
41
42// Collect every property key + every `type` string value, recursively.
43function collect(obj, keys = new Set()) {
44 if (Array.isArray(obj)) { for (const x of obj) collect(x, keys); return keys; }
45 if (obj && typeof obj === 'object') {
46 for (const [k, v] of Object.entries(obj)) {
47 keys.add(k);
48 if (k === 'type' && typeof v === 'string') keys.add(v);
49 collect(v, keys);
50 }
51 }
52 return keys;
53}
54function assertValid(obj, label) {
55 const undeclared = [...collect(obj)].filter((k) => !allowed.has(k));
56 assert.deepEqual(undeclared, [],
57 `${label}: undeclared AS2/JSON-LD term(s) — declare in AP_CONTEXT (extension) or the AS2 allowlist: ${undeclared.join(', ')}`);
58}
59
60// Seed one site that exercises the extension-heavy actor fields (profile links → PropertyValue,
61// photo → icon, primary → featured).
62db.prepare('INSERT INTO users (id, username, email, password_hash, role) VALUES (?,?,?,?,?)').run('u1', 'u1', 'u1@test', 'x', 'god');
63db.prepare('INSERT INTO sites (id, slug, title, owner_id, is_primary, profile_links, profile_photo) VALUES (?,?,?,?,?,?,?)')
64 .run('s1', 'demo', 'Demo', 'u1', 1, JSON.stringify([{ platform: 'website', url: 'https://x.test' }]), '/media/x.png');
65const site = db.prepare('SELECT * FROM sites WHERE id = ?').get('s1');
66site.primary_slug = 'demo';
67
68// Kitchen-sink note: nsfw (→ sensitive + summary), a hashtag (→ Hashtag), a cover (→ attachment).
69const post = {
70 id: 'p1', slug: 'hello', title: 'Hi', content: '<p>hello #music</p>',
71 nsfw: 1, content_warning: 'cw', tags: JSON.stringify(['mood']),
72 cover_image_url: '/media/c.webp',
73 published_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
74};
75
76test('actor is valid AS2 (every term declared)', () => assertValid(AP.buildActor(BASE, site), 'actor'));
77test('create+note is valid AS2 (every term declared)', () => assertValid(AP.buildCreate(BASE, site, post), 'create/note'));
78test('outbox/followers/featured collections are valid AS2', () => {
79 assertValid(AP.buildOutbox(BASE, site, [post]), 'outbox');
80 assertValid(AP.buildFollowers(BASE, site, 3), 'followers');
81 assertValid(AP.buildFollowing(BASE, site, 2), 'following');
82 assertValid(AP.buildFeatured(BASE, site, [post]), 'featured');
83});
84test('AP_CONTEXT declares every extension term we rely on', () => {
85 for (const t of ['sensitive', 'Hashtag', 'manuallyApprovesFollowers', 'discoverable', 'featured', 'PropertyValue', 'embedUrl'])
86 assert.ok(ctxTerms.has(t), `AP_CONTEXT must declare "${t}"`);
87});
Note: See TracBrowser for help on using the repository browser.