import assert from "node:assert/strict"; import { readdir, readFile } from "node:fs/promises"; import { resolve, sep } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; // Use a checkout with the draft space/space-ref extensions, without vendoring // upstream schemas or depending on an incompatible published SDK release. const root = fileURLToPath(new URL("../", import.meta.url)); const atproto = resolve(process.argv[2] ?? resolve(root, "../atproto")); const moduleAt = (path) => import(pathToFileURL(resolve(atproto, path)).href); const { lexiconDoc, Lexicons } = await moduleAt( "packages/lexicon/dist/index.js", ); const { LexiconIterableIndexer, LexiconSchemaBuilder } = await moduleAt( "packages/lex/lex-document/dist/index.js", ); const { parseAtUriString } = await moduleAt("packages/syntax/dist/index.js"); const { IncludeScope, RpcPermission, SpacePermission } = await moduleAt( "packages/oauth/oauth-scopes/dist/index.js", ); const ns = "org.atgrp."; const label = "com.atproto.label.record"; const directory = resolve(root, "lexicons"); const files = (await readdir(directory, { recursive: true })) .filter((file) => file.endsWith(".json")) .sort(); const docs = await Promise.all( files.map(async (file) => { const doc = JSON.parse(await readFile(resolve(directory, file), "utf8")); assert.equal( doc.id, file.slice(0, -5).split(sep).join("."), `NSID/path mismatch: ${file}`, ); // Also catch unsupported fields that the schema parser would silently strip. assert.deepEqual(lexiconDoc.parse(doc), doc, `Invalid schema: ${file}`); return doc; }), ); assert.equal(new Set(docs.map((doc) => doc.id)).size, docs.length); // Upstream schemas referenced by the group lexicons. const upstream = await Promise.all( [ "com/atproto/label/defs.json", "com/atproto/label/record.json", "com/atproto/repo/strongRef.json", "com/atproto/space/policy.json", "com/atproto/personalspace/policy.json", "com/atproto/memberspace/policy.json", "com/atproto/managedspace/policy.json", ].map(async (file) => JSON.parse(await readFile(resolve(atproto, "lexicons", file), "utf8")), ), ); const lexicons = new Lexicons(structuredClone([...docs, ...upstream])); function checkRefs(value, id) { if (!value || typeof value !== "object") return; if (value.type === "ref" || value.type === "union") { for (const ref of value.refs ?? [value.ref]) { assert.ok( lexicons.getDef(ref.startsWith("#") ? id + ref : ref), `Missing ref: ${ref}`, ); } } if (value.type === "space") { assert.equal(value.key, "literal:self"); assert.equal(new Set(value.collections).size, value.collections.length); for (const collection of value.collections) { assert.equal( lexicons.getDef(collection)?.type, "record", `Not a record: ${collection}`, ); } } for (const item of Object.values(value)) checkRefs(item, id); } for (const doc of docs) checkRefs(doc, doc.id); // The schema builder needs refs to spell out #main, which some upstream // schemas (e.g. com.atproto.space.policy's union) omit. function explicitMain(value) { if (Array.isArray(value)) return value.map(explicitMain); if (!value || typeof value !== "object") return value; const out = {}; for (const [key, item] of Object.entries(value)) out[key] = explicitMain(item); const withMain = (ref) => (ref.includes("#") ? ref : ref + "#main"); if (out.type === "ref") out.ref = withMain(out.ref); if (out.type === "union") out.refs = out.refs.map(withMain); return out; } const schemas = await LexiconSchemaBuilder.buildAll( new LexiconIterableIndexer([...docs, ...upstream.map(explicitMain)]), ); // Guard against accidentally leaving an entry from the spec unimplemented. const spec = await readFile(resolve(root, "spec.md"), "utf8"); for (const match of spec.matchAll(/^\| `org\.atgrp\.([A-Za-z]+)` \|/gm)) { assert.ok(lexicons.get(ns + match[1]), `Missing spec entry: ${match[1]}`); } for (const match of spec .split("### Methods")[1] .matchAll(/^\| `([A-Za-z.]+)` \|/gm)) { assert.ok( ["query", "procedure"].includes(lexicons.getDef(ns + match[1])?.type), `Missing method: ${match[1]}`, ); } assert.equal(lexicons.getDef(ns + "mod.submitReport")?.type, "procedure"); const examples = JSON.parse( await readFile(resolve(root, "examples/records.json"), "utf8"), ); const covered = new Set(); const authorityAuthored = new Set( ["about", "config", "rule", "role", "space", "membership", "labeler"] .map((name) => ns + name) .concat(label, "com.atproto.space.policy"), ); for (const { uri, value } of examples) { const parsed = parseAtUriString(uri); assert.ok(parsed.success, `Invalid example URI: ${uri}`); assert.equal(parsed.value.collection, value.$type); const schema = schemas.get(value.$type + "#main"); schema.parse(value); lexicons.assertValidRecord(value.$type, value); covered.add(value.$type); const author = parsed.value.authorDid ?? parsed.value.authority; if (authorityAuthored.has(value.$type)) { assert.equal(author, parsed.value.authority, `Wrong record author: ${uri}`); } if (value.$type === ns + "membership") assert.match( parsed.value.rkey, /^did:/, `Membership rkey isn't a DID: ${uri}`, ); if (value.$type === ns + "confirmation") { assert.equal(parsed.value.rkey, "self"); // These fixtures demonstrate a bidirectional membership pair. This is not // a requirement that all confirmation records have a current membership. assert.ok( examples.some(({ uri: candidateUri, value: candidate }) => { if (candidate.$type !== ns + "membership") return false; const candidateParts = parseAtUriString(candidateUri); return ( candidateParts.success && candidateParts.value.rkey === author && candidateParts.value.authority === parsed.value.authority ); }), `Confirmation example has no matching membership: ${uri}`, ); } if (value.$type === ns + "invite") assert.notEqual(author, parsed.value.authority); // The policy union is open, so validate the group policy inside it directly. if (value.$type === "com.atproto.space.policy") { assert.equal(parsed.value.rkey, "self"); assert.equal(value.policy.$type, ns + "policy"); assert.ok(lexicons.validate(ns + "policy", value.policy).success, uri); } } for (const doc of docs) { if (doc.defs.main?.type === "record") assert.ok(covered.has(doc.id), `No example: ${doc.id}`); } const group = "did:plc:abcdefghijklmnopqrstuvwx"; const member = "did:plc:zyxwvutsrqponmlkjihgfedcb"; const space = `at:space/${group}/${ns}members/self`; const recordUri = `${space}/${member}/${ns}confirmation/self`; const cid = "bafyreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku"; const input = (name, value) => lexicons.assertValidXrpcInput(ns + name, value); const output = (name, value) => lexicons.assertValidXrpcOutput(ns + name, value); const params = (name, value) => lexicons.assertValidXrpcParams(ns + name, value); const rejects = (fn) => assert.throws(fn); // Exercise permission-set expansion with the actual OAuth scope implementation: // valid Lexicon shape alone does not establish that permissions survive expansion. const permissionSets = new Map(); const authorizedMethods = new Set(); for (const doc of docs) { if (doc.defs.main?.type !== "permission-set") continue; const expanded = new IncludeScope(doc.id).toPermissions(doc.defs.main); assert.equal( expanded.length, doc.defs.main.permissions.length, `Dropped permission in ${doc.id}`, ); permissionSets.set(doc.id, expanded); for (const permission of expanded) { if (permission instanceof RpcPermission) { for (const method of permission.lxm) { assert.ok( ["query", "procedure"].includes(lexicons.getDef(method)?.type), `Unknown RPC: ${method}`, ); authorizedMethods.add(method); } } else { assert.ok( permission instanceof SpacePermission, `Unexpected resource in ${doc.id}`, ); assert.equal(lexicons.getDef(permission.spaceType)?.type, "space"); } } } for (const doc of docs) { if (["query", "procedure"].includes(doc.defs.main?.type)) { assert.ok(authorizedMethods.has(doc.id), `No permission set for ${doc.id}`); } } // Group spaces are created through com.atproto.space.createSpace, whose policy // union is open, so the group policy must be a plain object def. assert.equal(lexicons.getDef(ns + "policy")?.type, "object"); assert.ok(!lexicons.validate(ns + "policy", { publicRead: true }).success); assert.ok( lexicons.validate(ns + "policy", { unlisted: true, grants: [] }).success, ); // Member access and group account permissions are independent parts of a grant. assert.ok( lexicons.validate(ns + "policy", { grants: [{ role: "member", read: true }], }).success, ); assert.ok( !lexicons.validate(ns + "policy", { grants: [{ read: true }] }).success, ); // Group account sets resolve `self` to the group; authParticipate resolves it to the member. const allowsSpace = (set, target, self = group) => permissionSets .get(ns + set) .some( (permission) => permission instanceof SpacePermission && permission.withResolvedAuthority(self).matches(target), ); const allowsRpc = (set, method) => permissionSets.get(ns + set).some( (permission) => permission instanceof RpcPermission && permission.matches({ aud: `${group}#atproto_space_host`, lxm: ns + method, }), ); const metaSpace = { spaceType: ns + "meta", authority: group, skey: "self" }; const memberSpace = { spaceType: ns + "members", authority: group, skey: "self", }; const write = (target, collection) => ({ ...target, action: "create", collection, }); const inbox = { spaceType: ns + "inbox", authority: member, skey: "self" }; // Group account sets can read the group spaces they write in, but never an inbox. const groupSets = [ "authManageBasic", "authManageMembers", "authModerate", "authManageAdmin", ]; for (const set of groupSets) { assert.equal( allowsSpace(set, { ...metaSpace, action: "read" }), set !== "authManageMembers", ); assert.ok(allowsSpace(set, { ...memberSpace, action: "read" })); assert.ok(!allowsSpace(set, { ...inbox, action: "read" })); assert.equal( allowsSpace(set, { ...inbox, action: "read_self" }), ["authManageMembers", "authManageAdmin"].includes(set), ); } // Each group account set writes exactly the records the spec assigns to it. // The admin set covers everything the others do. const profileWrites = [ [metaSpace, ns + "about"], [memberSpace, ns + "rule"], ]; const memberWrites = [ [memberSpace, ns + "membership"], [inbox, ns + "invite"], ]; const moderateWrites = [ [metaSpace, label], [memberSpace, label], ]; const setWrites = { authManageBasic: profileWrites, authManageMembers: memberWrites, authModerate: moderateWrites, authManageAdmin: [ ...profileWrites, ...memberWrites, ...moderateWrites, [metaSpace, ns + "config"], [memberSpace, ns + "labeler"], [memberSpace, ns + "role"], ], }; for (const [set, writes] of Object.entries(setWrites)) { for (const entry of setWrites.authManageAdmin) { const [target, collection] = entry; const expected = writes.includes(entry); assert.equal( allowsSpace(set, write(target, collection)), expected, `${set} ${expected ? "cannot" : "can"} write ${collection}`, ); } assert.ok(!allowsSpace(set, { ...memberSpace, manage: "delete" })); // The host maintains the space index, so no set writes it directly. assert.ok(!allowsSpace(set, write(memberSpace, ns + "space"))); // Only the top tier can update the meta and members policies. for (const target of [metaSpace, memberSpace]) { assert.equal( allowsSpace(set, { ...target, manage: "update" }), set === "authManageAdmin", ); } assert.ok( !allowsSpace( set, write({ ...memberSpace, authority: member }, ns + "role"), ), ); } // Moderators can eject members but not admit them or change their roles. const membership = { ...memberSpace, collection: ns + "membership" }; for (const set of groupSets) { assert.equal( allowsSpace(set, { ...membership, action: "delete" }), set !== "authManageBasic", ); assert.equal( allowsSpace(set, { ...membership, action: "update" }), ["authManageMembers", "authManageAdmin"].includes(set), ); assert.equal( allowsRpc(set, "denyJoinRequest"), ["authManageMembers", "authManageAdmin"].includes(set), ); for (const method of [ "mod.querySubjects", "mod.querySubjectHistory", "mod.updateSubject", ]) { assert.equal( allowsRpc(set, method), ["authModerate", "authManageAdmin"].includes(set), ); } } // Personal-account participation. assert.ok( allowsSpace("authParticipate", { ...memberSpace, action: "read" }, member), ); assert.ok( allowsSpace("authParticipate", write(memberSpace, ns + "confirmation"), member), ); assert.ok( !allowsSpace("authParticipate", { ...memberSpace, manage: "update" }, member), ); for (const collection of ["membership", "role"]) { assert.ok( !allowsSpace( "authParticipate", write(memberSpace, ns + collection), member, ), ); } assert.ok(!allowsSpace("authParticipate", write(memberSpace, label), member)); assert.ok(allowsSpace("authParticipate", { ...inbox, action: "read" }, member)); assert.ok( allowsSpace("authParticipate", { ...inbox, manage: "create" }, member), ); assert.ok( !allowsSpace( "authParticipate", { ...inbox, authority: group, action: "read" }, member, ), ); for (const method of [ "mod.submitReport", "mod.submitAppeal", "mod.querySelfHistory", ]) { assert.ok(allowsRpc("authParticipate", method)); } assert.ok(!allowsRpc("authParticipate", "denyJoinRequest")); assert.ok(!allowsRpc("authParticipate", "mod.querySubjects")); // Personal calls name the group; group account calls take it from the session. input("mod.submitReport", { group, subject: recordUri, cid, reasonType: ns + "mod.defs#reasonOther", }); output("mod.querySubjectHistory", { events: [ { eventId: "label-1", createdAt: "2026-09-29T12:00:00.000Z", subject: recordUri, event: { $type: ns + "mod.defs#labelEvent", uri: `${space}/${group}/${label}/3jzfcijpj2z2a`, val: "!hide", deleted: true, }, }, { eventId: "tag-1", createdAt: "2026-09-29T12:00:00.000Z", subject: recordUri, event: { $type: ns + "mod.defs#tagEvent", add: ["escalated"] }, }, ], }); rejects(() => input("mod.submitReport", { group, subject: "not-a-uri", reasonType: ns + "mod.defs#reasonOther", }), ); // Appeals and self history name the group and work without membership. input("mod.submitAppeal", { group, subject: member, note: "Wrong person." }); rejects(() => input("mod.submitAppeal", { subject: member })); params("mod.querySelfHistory", { group }); params("mod.querySelfHistory", { group, subject: recordUri, sort: "oldest", limit: 100, }); rejects(() => params("mod.querySelfHistory", {})); output("mod.querySelfHistory", { events: [ { eventId: "eject-1", createdAt: "2026-09-29T12:00:00.000Z", subject: member, event: { $type: ns + "mod.defs#ejectEvent" }, }, ], }); rejects(() => output("mod.querySelfHistory", { events: [ { eventId: "eject-1", createdAt: "2026-09-29T12:00:00.000Z", event: { $type: ns + "mod.defs#ejectEvent" }, }, ], }), ); // Member-authored confirmation needs no group role or permission payload. lexicons.assertValidRecord(ns + "confirmation", { $type: ns + "confirmation", createdAt: "2026-09-29T12:00:00.000Z", }); input("requestJoin", { group }); rejects(() => input("requestJoin", {})); output("requestJoin", { status: "admitted", membership: { uri: recordUri, cid }, }); output("requestJoin", { status: "pending", request: { member, createdAt: "2026-09-29T12:00:00.000Z" }, }); input("denyJoinRequest", { member }); rejects(() => input("denyJoinRequest", { member: "not-a-did" })); // Moderator transitions and query bounds are constrained at the schema layer. input("mod.updateSubject", { subject: recordUri, cid, status: "resolved", note: "Labeled !hide.", }); input("mod.updateSubject", { subject: recordUri, status: "open" }); rejects(() => input("mod.updateSubject", { subject: recordUri, status: "escalated" }), ); // Tags change without restating the status. input("mod.updateSubject", { subject: recordUri, addTags: ["escalated"], removeTags: ["spam-wave"], }); rejects(() => input("mod.updateSubject", { subject: recordUri, addTags: [""] })); output("mod.updateSubject", { subject: recordUri, status: "open", createdAt: "2026-09-29T12:00:00.000Z", updatedAt: "2026-09-29T12:00:00.000Z", tags: ["escalated"], }); params("mod.querySubjects", { tags: ["escalated", "spam-wave"] }); params("mod.querySubjectHistory", { subject: recordUri, cid, limit: 100 }); params("mod.querySubjectHistory", { subject: member, sort: "oldest" }); params("mod.querySubjects", { status: "open", sort: "updated" }); // Both histories list events in the same order by default. const sortDefault = (name) => lexicons.getDef(ns + name).parameters.properties.sort.default; assert.equal( sortDefault("mod.querySubjectHistory"), sortDefault("mod.querySelfHistory"), ); rejects(() => params("mod.querySubjects", { limit: 101 })); rejects(() => params("mod.querySubjects", { status: "escalated" })); // Omitting status spans every status, so it must not default to one. assert.equal( lexicons.getDef(ns + "mod.querySubjects").parameters.properties.status .default, undefined, ); // Hosts may skip counting reports. output("mod.querySubjects", { subjects: [ { subject: member, status: "open", createdAt: "2026-09-29T12:00:00.000Z", updatedAt: "2026-09-29T12:00:00.000Z", }, ], }); rejects(() => params("listJoinRequests", { limit: 0 })); console.log( `Validated ${docs.length} documents, compiled ${schemas.size} definitions, checked ${examples.length} records, ${permissionSets.size} permission sets, and API boundary cases.`, );