@drfed/graphql 0.2.0-dev.712 → 0.2.0-dev.716
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -3
- package/dist/account.mjs +1 -1
- package/dist/activity-delivery/entry.mjs +2 -2
- package/dist/{actor-B1FAD_C_.mjs → actor-Bd7xAMeW.mjs} +6 -30
- package/dist/actor-Bd7xAMeW.mjs.map +1 -0
- package/dist/actor.mjs +1 -1
- package/dist/{builder-BLioFAdv.mjs → builder-BrcxJqIz.mjs} +6 -4
- package/dist/builder-BrcxJqIz.mjs.map +1 -0
- package/dist/builder-CSxRffRp.d.mts.map +1 -1
- package/dist/builder.mjs +1 -1
- package/dist/classification.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instance.mjs +1 -1
- package/dist/object.d.mts.map +1 -1
- package/dist/object.mjs +26 -8
- package/dist/object.mjs.map +1 -1
- package/dist/readable.d.mts +177 -0
- package/dist/readable.d.mts.map +1 -0
- package/dist/readable.mjs +339 -0
- package/dist/readable.mjs.map +1 -0
- package/dist/schema-eJO_-DWq.mjs +707 -0
- package/dist/schema-eJO_-DWq.mjs.map +1 -0
- package/dist/schema.d.mts.map +1 -1
- package/dist/schema.mjs +1 -1
- package/package.json +13 -8
- package/dist/actor-B1FAD_C_.mjs.map +0 -1
- package/dist/builder-BLioFAdv.mjs.map +0 -1
- package/dist/readable-CSN0MPlO.mjs +0 -140
- package/dist/readable-CSN0MPlO.mjs.map +0 -1
- package/dist/schema-f-SnZVb9.mjs +0 -275
- package/dist/schema-f-SnZVb9.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-eJO_-DWq.mjs","names":["eq","and","schema"],"sources":["../src/auth/hash.ts","../src/auth/expand.ts","../src/auth/mail.ts","../src/auth/magic-link.ts","../src/auth/challenge.ts","../src/auth/revoke.ts","../src/auth/entry.ts","../src/revision.ts","../src/key.ts","../src/schema.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n// oxlint-disable func-names func-style id-length\n\nexport const hashSecret = async (raw: string): Promise<string> =>\n new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", textEncoder.encode(raw)),\n ).toHex();\n\nconst textEncoder = new TextEncoder();\n\nconst ACCESS_TOKEN_BYTES = 32;\n\nexport const generateAccessToken = (): string =>\n crypto.getRandomValues(new Uint8Array(ACCESS_TOKEN_BYTES)).toBase64({\n alphabet: \"base64url\",\n omitPadding: true,\n });\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { Template } from \"@fedify/uri-template\";\nimport { GraphQLError } from \"graphql\";\n\nexport interface ExpandVerifyUrlParams {\n template: Template;\n challengeId: `${string}-${string}-${string}-${string}-${string}`;\n code: string;\n loginOrigins: ReadonlySet<string>;\n}\n\nexport default function expandVerifyUrl({\n template,\n challengeId,\n code,\n loginOrigins,\n}: ExpandVerifyUrlParams): string {\n assertVariable(template, \"challengeId\");\n assertVariable(template, \"code\");\n\n let url: URL;\n try {\n url = new URL(template.expand({ challengeId, code }));\n } catch {\n throw invalidVerifyUrl(\n \"Verify URL template must expand to an absolute URL.\",\n );\n }\n\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw invalidVerifyUrl(\"Verify URL must use HTTP or HTTPS.\");\n }\n if (!loginOrigins.has(url.origin)) {\n throw invalidVerifyUrl(`Verify URL origin is not allowed: ${url.origin}.`);\n }\n return url.href;\n}\n\nfunction assertVariable(template: Template, name: string): void {\n const found = template.tokens.some(\n (token) =>\n token.kind === \"expression\" &&\n token.vars.some(\n (variable) => variable.name === name && variable.prefix == null,\n ),\n );\n if (!found) {\n throw invalidVerifyUrl(`Verify URL template must include {${name}}.`);\n }\n}\n\nconst invalidVerifyUrl = (message: string) =>\n new GraphQLError(message, { extensions: { code: \"BAD_USER_INPUT\" } });\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { getLogger } from \"@logtape/logtape\";\nimport { type MessageContent, type Receipt, createMessage } from \"@upyo/core\";\n\nimport type { UserContext } from \"../builder.ts\";\n\n/** Send login mail without exposing non-cancellation provider failures. */\nexport async function sendMail(\n to: string,\n loginUrl: string,\n ctx: UserContext,\n): Promise<void> {\n const signal = ctx.operationSignal ?? ctx.request.signal;\n if (signal.aborted) {\n throw new DOMException(\"Mail sending cancelled.\", \"AbortError\");\n }\n try {\n const receipt = await ctx.mailer.send(\n createMessage({\n from: ctx.emailFrom,\n to,\n // FIXME: https://github.com/fedify-dev/drfed/issues/35\n subject: \"Sign in to DrFed\",\n content: renderLoginEmail(loginUrl),\n }),\n { signal },\n );\n if (signal.aborted) {\n throw new DOMException(\"Mail sending cancelled.\", \"AbortError\");\n }\n logReceipt(receipt);\n } catch {\n if (signal.aborted) {\n throw new DOMException(\"Mail sending cancelled.\", \"AbortError\");\n }\n logger.warn(\"Login mail delivery failed.\", { outcome: \"exception\" });\n }\n}\n\nconst renderLoginEmail = (loginUrl: string): MessageContent => ({\n // FIXME: https://github.com/fedify-dev/drfed/issues/35\n // oxlint-disable no-inline-comments\n text: `Hello, Welcome to DrFed! If you request to login to DrFed, please visit:\n\nopen ${loginUrl}${/* Split between the link and the last `\\n` */ \" \"}\n\nOtherwise, please just ignore this mail.`,\n});\n// oxlint-enable no-inline-comments\n\nexport function logReceipt(receipt: Receipt<string>): void {\n if (receipt.successful) {\n logger.debug(\"Login mail delivery succeeded.\", { outcome: \"sent\" });\n return;\n }\n logger.warn(\"Login mail delivery failed.\", { outcome: \"failed\" });\n}\n\nconst logger = getLogger([\"drfed\", \"graphql\", \"auth\"]);\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n// oxlint-disable no-magic-numbers\n\nimport { schema } from \"@drfed/models\";\nimport { generateLoginChallengeCode } from \"@drfed/models/login\";\nimport { type Uuid, uuidV7 } from \"@drfed/models/uuid\";\n\nimport builder, { type UserContext } from \"../builder.ts\";\nimport expandVerifyUrl from \"./expand.ts\";\nimport { sendMail } from \"./mail.ts\";\n\ninterface LoginChallengeShape {\n readonly challengeId: Uuid;\n}\n\nconst LoginChallengeRef = builder\n .objectRef<LoginChallengeShape>(\"LoginChallenge\")\n .implement({\n description: \"An email login challenge.\",\n fields: (t) => ({\n challengeId: t.expose(\"challengeId\", {\n type: \"UUID\",\n description: \"The public identifier of the login challenge.\",\n }),\n }),\n });\n\nbuilder.mutationFields((t) => ({\n loginByEmail: t.field({\n type: LoginChallengeRef,\n description:\n \"Send a magic link without revealing whether the account exists.\",\n args: {\n email: t.arg({\n type: \"Email\",\n required: true,\n description: \"The email address of the `Account`.\",\n }),\n verifyUrl: t.arg({\n type: \"URITemplate\",\n required: true,\n description:\n \"Use {challengeId} and {code} variables. \" +\n \"The URL's origin must be in the server's login allowlist.\",\n }),\n },\n async resolve(_root, { email, verifyUrl }, ctx) {\n const challengeId = uuidV7();\n const code = generateLoginChallengeCode();\n const loginUrl = expandVerifyUrl({\n challengeId,\n code,\n loginOrigins: ctx.loginOrigins,\n template: verifyUrl,\n });\n const account = await findAccount(email, ctx);\n if (account == null) {\n // Return an ID even for an unknown account to prevent account\n // enumeration. Consider mailing in a worker to prevent timing attacks.\n return { challengeId };\n }\n const verifier = {\n challengeId,\n code,\n };\n\n await insertChallenge(account.id, verifier, ctx);\n // Do not check the email was sent. Instructs users to request a resend if\n // the email does not arrive after a few minutes at the web page.\n await sendMail(account.email, loginUrl, ctx);\n\n return { challengeId };\n },\n }),\n}));\n\nconst findAccount = async (email: string, ctx: UserContext) =>\n await ctx.db.query.accounts.findFirst({\n where: { email },\n });\n\nconst insertChallenge = async (\n accountId: Uuid,\n { challengeId, code }: { challengeId: Uuid; code: string },\n ctx: UserContext,\n) =>\n await ctx.db.insert(schema.loginChallenges).values({\n id: challengeId,\n accountId,\n code,\n });\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n// oxlint-disable no-magic-numbers\n\nimport { Buffer } from \"node:buffer\";\nimport { timingSafeEqual } from \"node:crypto\";\n\nimport type { Database } from \"@drfed/models\";\nimport {\n LoginChallengeError,\n consumeLoginChallenge,\n findLoginChallenge,\n} from \"@drfed/models/login\";\nimport { sessions } from \"@drfed/models/schema\";\nimport type { Uuid } from \"@drfed/models/uuid\";\n\nimport builder from \"../builder.ts\";\nimport { generateAccessToken, hashSecret } from \"./hash.ts\";\n\nconst SessionRef = builder.drizzleObject(\"sessions\", {\n name: \"Session\",\n fields: (t) => ({\n id: t.expose(\"id\", { type: \"UUID\" }),\n accessToken: t.string({\n nullable: true,\n resolve(session) {\n const accessToken =\n \"accessToken\" in session ? session.accessToken : null;\n return typeof accessToken === \"string\" ? accessToken : null;\n },\n }),\n // The only `Session` a client can obtain is the one `completeLoginChallenge`\n // just created for it, and `Session` is not a `Node`, so the account behind\n // a session is always the viewer's own. Granting `ownAccount` here lets\n // the login response carry the viewer's private fields even though the\n // request that produced it had no session yet.\n account: t.relation(\"account\", { grantScopes: [\"ownAccount\"] }),\n created: t.expose(\"created\", { type: \"DateTime\" }),\n expires: t.expose(\"expires\", { type: \"DateTime\" }),\n }),\n});\n\nbuilder.mutationFields((t) => ({\n completeLoginChallenge: t.drizzleField({\n type: SessionRef,\n nullable: true,\n description: \"Complete login challenge.\",\n args: {\n challengeId: t.arg({ type: \"UUID\", required: true }),\n code: t.arg({ type: \"String\", required: true }),\n },\n async resolve(query, _root, { challengeId, code }, ctx) {\n try {\n const now = Temporal.Now.instant();\n const row = await findLoginChallenge(ctx.db, challengeId, now);\n const id = crypto.randomUUID();\n const accessToken = generateAccessToken();\n const accessHash = await hashSecret(accessToken);\n\n const providedCode = Buffer.from(code.toLowerCase());\n const expectedCode = Buffer.from(row.code);\n if (\n providedCode.length !== expectedCode.length ||\n !timingSafeEqual(providedCode, expectedCode)\n ) {\n throw new LoginChallengeError(\"The provided code does not match.\");\n }\n await ctx.db.transaction(async (tx) => {\n await consumeLoginChallenge(tx, row.id, now);\n await insertSession(id, row.accountId, accessHash, tx);\n });\n\n const session = await ctx.db.query.sessions.findFirst(\n query({ where: { id } }),\n );\n return session == null ? null : { ...session, accessToken };\n } catch (error) {\n if (error instanceof LoginChallengeError) {\n return null;\n }\n throw error;\n }\n },\n }),\n}));\n\nconst insertSession = async (\n id: Uuid,\n accountId: Uuid,\n tokenHash: string,\n tx: Database,\n) => await tx.insert(sessions).values({ id, accountId, tokenHash });\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n// oxlint-disable no-magic-numbers\n\nimport { sessions } from \"@drfed/models/schema\";\nimport { eq } from \"drizzle-orm/sql/expressions\";\n\nimport builder, { type UserContext } from \"../builder.ts\";\n\nbuilder.mutationFields((t) => ({\n revokeSession: t.field({\n type: LogoutSuccessRef,\n description: \"Revokes a session. Return always `revoke: true`.\",\n authScopes: {\n authenticated: true,\n },\n async resolve(_query, _, ctx) {\n const sessionId = ctx.session?.id;\n if (sessionId) {\n await deleteSession(ctx);\n }\n // Return always true to prevent brute-force attack.\n return { revoke: true };\n },\n }),\n}));\n\ninterface LogoutSuccessShape {\n revoke: boolean;\n}\n\nconst LogoutSuccessRef = builder\n .objectRef<LogoutSuccessShape>(\"LogoutSuccess\")\n .implement({\n description: \"The session revoked.\",\n fields: (t) => ({\n revoke: t.expose(\"revoke\", {\n type: \"Boolean\",\n description: \"Revoking status.\",\n }),\n }),\n });\n\nconst deleteSession = (ctx: UserContext) =>\n ctx.db.delete(sessions).where(eq(sessions.id, ctx.session!.id));\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n// oxlint-disable import/no-unassigned-import\nimport \"./magic-link.ts\";\nimport \"./challenge.ts\";\nimport \"./revoke.ts\";\nimport builder from \"../builder.ts\";\n\nbuilder.queryFields((t) => ({\n viewer: t.drizzleField({\n type: \"accounts\",\n nullable: true,\n description: \"`Account` if authorized, else `null`\",\n resolve: (query, _root, _args, ctx) =>\n ctx.session == null\n ? null\n : ctx.db.query.accounts.findFirst(\n query({ where: { id: ctx.session.accountId } }),\n ),\n }),\n}));\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport {\n type InterpretedNode,\n RELATION_PROPERTIES,\n type RecipientOccurrence,\n type RelationOccurrence,\n interpretDocument,\n} from \"@drfed/federation/document\";\nimport { schema } from \"@drfed/models\";\nimport {\n type Diagnostic,\n type DiagnosticCategory,\n type DiagnosticSeverity,\n type DocumentNodeKind,\n validateDocument,\n} from \"@drfed/models/document\";\nimport type {\n ResourceRevision as ResourceRevisionRow,\n Resource as ResourceRow,\n RevisionEmbedding,\n} from \"@drfed/models/schema\";\nimport type { Uuid } from \"@drfed/models/uuid\";\nimport { and, eq, inArray } from \"drizzle-orm\";\n\nimport builder, { type DrFedObjectRef, type UserContext } from \"./builder.ts\";\nimport { readableResourceNode, readableRevision } from \"./readable.ts\";\nimport { Resource } from \"./resource.ts\";\n\nconst ACTIVITY_STREAMS = \"https://www.w3.org/ns/activitystreams#\";\n\nconst ResourceRevisionKind = builder.enumType(\"ResourceRevisionKind\", {\n description: \"What a revision records.\",\n values: {\n snapshot: { description: \"A saved document.\" },\n unavailable: {\n description:\n \"A legacy typed row that had no retained document; nothing replaces it.\",\n },\n whiteout: {\n description:\n \"A deletion: its time and the types the resource had, but no document.\",\n },\n } satisfies Record<ResourceRevisionRow[\"kind\"], object>,\n});\nconst ResourceRevisionCapture = builder.enumType(\"ResourceRevisionCapture\", {\n description:\n \"How DrFed came to store a revision. Neither proves ownership nor \" +\n \"grants access.\",\n values: {\n local: { description: \"Saved by DrFed for a local actor.\" },\n received: { description: \"Received in an inbound activity.\" },\n embedded: { description: \"Embedded in another received document.\" },\n fetched: {\n description:\n \"Fetched apart from an activity. For legacy data, a conservative \" +\n \"flag that is no proof an HTTP fetch occurred.\",\n },\n } satisfies Record<ResourceRevisionRow[\"capture\"], object>,\n});\nconst DocumentNodeKindEnum = builder.enumType(\"DocumentNodeKind\", {\n description: \"The vocabulary category of a document's type.\",\n values: {\n activity: {},\n actor: {},\n collection: {},\n link: {},\n object: {},\n } satisfies Record<DocumentNodeKind, object>,\n});\nconst RelationProperty = builder.enumType(\"RelationProperty\", {\n description: \"A property that relates a document to another resource.\",\n values: RELATION_PROPERTIES,\n});\nconst AddressingProperty = builder.enumType(\"AddressingProperty\", {\n description: \"A property that addresses a document's recipients.\",\n values: schema.addressingPropertyEnum.enumValues,\n});\nconst RelationRepresentation = builder.enumType(\"RelationRepresentation\", {\n description: \"How a value names what it stands for.\",\n values: {\n reference: { description: \"An IRI.\" },\n embedded: { description: \"An embedded document.\" },\n link: { description: \"An embedded `Link`, which names it by `href`.\" },\n } satisfies Record<RelationOccurrence[\"representation\"], object>,\n});\nconst DiagnosticCategoryEnum = builder.enumType(\"DiagnosticCategory\", {\n values: {\n vocabulary: {\n description: \"The document breaks a vocabulary or JSON-LD rule.\",\n },\n authority: { description: \"The document claims what it may not.\" },\n support: { description: \"DrFed's validator cannot check it.\" },\n compatibility: {\n description: \"Valid, but other implementations may read it otherwise.\",\n },\n } satisfies Record<DiagnosticCategory, object>,\n});\nconst DiagnosticSeverityEnum = builder.enumType(\"DiagnosticSeverity\", {\n values: {\n error: {},\n warning: {},\n } satisfies Record<DiagnosticSeverity, object>,\n});\n\nconst DocumentExtension = builder.objectRef<{\n readonly key: string;\n readonly value: unknown;\n}>(\"DocumentExtension\");\nDocumentExtension.implement({\n description: \"A custom extension property, preserved as opaque JSON.\",\n fields: (t) => ({\n key: t.exposeString(\"key\", {\n description: \"The key in its source spelling.\",\n }),\n value: t.expose(\"value\", { type: \"JSON\", description: \"As saved.\" }),\n }),\n});\n\nconst DocumentDiagnostic = builder.objectRef<Diagnostic>(\"DocumentDiagnostic\");\nDocumentDiagnostic.implement({\n description: \"A finding of the document validator.\",\n fields: (t) => ({\n reason: t.exposeString(\"reason\", {\n description:\n \"A stable classification, such as `unsupported_property`. Use it \" +\n \"for decisions rather than `message`.\",\n }),\n category: t.expose(\"category\", { type: DiagnosticCategoryEnum }),\n severity: t.expose(\"severity\", { type: DiagnosticSeverityEnum }),\n path: t.expose(\"path\", {\n type: \"JSON\",\n description:\n \"The source keys and list indexes leading to the finding; `[]` is \" +\n \"the root.\",\n }),\n message: t.exposeString(\"message\", {\n description: \"For people; it may change.\",\n }),\n }),\n});\n\nconst DocumentSourceRelation = builder.enumType(\"DocumentSourceRelation\", {\n description:\n \"How an embedded document relates to the revision it came from, as \" +\n \"recorded when the document embedding it was saved.\",\n values: {\n snapshot: {\n description:\n \"It keeps the source revision's contents, apart from the context \" +\n \"it inherits from the document embedding it.\",\n },\n derived: {\n description:\n \"It started from the source revision and was changed, as a test \" +\n \"input with other addressing or an altered property.\",\n },\n } satisfies Record<RevisionEmbedding[\"relation\"], object>,\n});\nconst DocumentSourceStatus = builder.enumType(\"DocumentSourceStatus\", {\n description:\n \"Where the source revision stands in its resource's history. It \" +\n \"compares revisions, not contents.\",\n values: {\n current: { description: \"It is the resource's current revision.\" },\n superseded: {\n description:\n \"A later revision is current, which may have the same contents.\",\n },\n deleted: { description: \"The resource's current revision is a whiteout.\" },\n },\n});\n\ntype SourceStatus = \"current\" | \"superseded\" | \"deleted\";\n\n/** A recorded embedding whose source revision the viewer may read. */\ninterface Source {\n readonly relation: RevisionEmbedding[\"relation\"];\n readonly revision: ResourceRevisionRow;\n /** Null when the viewer may not read the resource's current revision. */\n readonly status: SourceStatus | null;\n}\nconst DocumentSource = builder.objectRef<Source>(\"DocumentSource\");\n\nconst DocumentNode = builder.objectRef<InterpretedNode>(\"DocumentNode\");\nconst DocumentRelation =\n builder.objectRef<RelationOccurrence>(\"DocumentRelation\");\nconst DocumentRecipient =\n builder.objectRef<RecipientOccurrence>(\"DocumentRecipient\");\n\nconst resourceLookups = new WeakMap<\n UserContext,\n Map<string, Promise<ResourceRow | null>>\n>();\n\n/**\n * Finds the resource registered under an IRI, as `Activity.object` opens\n * it: only when the viewer may read it or one of its revisions. A deleted\n * one is found too, since its revisions stay readable. Lookups are shared within a request, since\n * a document may name one IRI many times.\n * @returns The resource, or null.\n */\nfunction registeredResource(\n ctx: UserContext,\n iri: string | null,\n): Promise<ResourceRow | null> {\n if (iri == null) return Promise.resolve(null);\n let lookups = resourceLookups.get(ctx);\n if (lookups == null) {\n lookups = new Map();\n resourceLookups.set(ctx, lookups);\n }\n let lookup = lookups.get(iri);\n if (lookup == null) {\n lookup = (async () =>\n (await ctx.db.query.resources.findFirst({\n where: {\n iri,\n RAW: (table) => readableResourceNode(ctx, table.id),\n },\n })) ?? null)();\n lookups.set(iri, lookup);\n }\n return lookup;\n}\n\n// The revision each interpreted node belongs to.\nconst nodeRevisions = new WeakMap<InterpretedNode, Uuid>();\n\nconst sourceLookups = new WeakMap<\n UserContext,\n Map<Uuid, Promise<ReadonlyMap<string, Source>>>\n>();\n\n/**\n * Tells where a source revision stands against its resource's current\n * revision. An `unavailable` current revision, a legacy typed row without a\n * retained document, is a later revision like any other.\n * @param revision The source revision.\n * @param current The current revision of its resource, when the viewer may\n * read it.\n * @returns The status, or null without a readable current revision.\n */\nconst statusOf = (\n revision: ResourceRevisionRow,\n current: Pick<ResourceRevisionRow, \"id\" | \"kind\"> | undefined,\n): SourceStatus | null =>\n current == null\n ? null\n : current.id === revision.id\n ? \"current\"\n : current.kind === \"whiteout\"\n ? \"deleted\"\n : \"superseded\";\n\n/**\n * Loads the recorded sources of a revision's embedded documents that the\n * viewer may read, with where each stands, in two queries per revision\n * whatever the number of documents it embeds. Lookups are shared within a\n * request.\n * @returns The sources, keyed by the JSON of the embedded documents' paths.\n */\nfunction sourcesOf(\n ctx: UserContext,\n revisionId: Uuid,\n): Promise<ReadonlyMap<string, Source>> {\n let lookups = sourceLookups.get(ctx);\n if (lookups == null) {\n lookups = new Map();\n sourceLookups.set(ctx, lookups);\n }\n let lookup = lookups.get(revisionId);\n if (lookup == null) {\n lookup = (async () => {\n const embeddings = await ctx.db\n .select({\n path: schema.revisionEmbeddings.path,\n relation: schema.revisionEmbeddings.relation,\n revision: schema.resourceRevisions,\n })\n .from(schema.revisionEmbeddings)\n .innerJoin(\n schema.resourceRevisions,\n eq(\n schema.resourceRevisions.id,\n schema.revisionEmbeddings.sourceRevisionId,\n ),\n )\n .where(\n and(\n eq(schema.revisionEmbeddings.revisionId, revisionId),\n readableRevision(ctx, schema.resourceRevisions.id),\n ),\n );\n const resourceIds = [\n ...new Set(embeddings.map(({ revision }) => revision.resourceId)),\n ];\n const heads =\n resourceIds.length === 0\n ? []\n : await ctx.db\n .select({\n resourceId: schema.resourceHeads.resourceId,\n id: schema.resourceRevisions.id,\n kind: schema.resourceRevisions.kind,\n })\n .from(schema.resourceHeads)\n .innerJoin(\n schema.resourceRevisions,\n eq(\n schema.resourceRevisions.id,\n schema.resourceHeads.revisionId,\n ),\n )\n .where(\n and(\n inArray(schema.resourceHeads.resourceId, resourceIds),\n readableRevision(ctx, schema.resourceRevisions.id),\n ),\n );\n const current = new Map(\n heads.map((head) => [head.resourceId, head] as const),\n );\n return new Map(\n embeddings.map(({ path, relation, revision }) => [\n JSON.stringify(path),\n {\n relation,\n revision,\n status: statusOf(revision, current.get(revision.resourceId)),\n },\n ]),\n );\n })();\n lookups.set(revisionId, lookup);\n }\n return lookup;\n}\n\n/**\n * Finds the recorded source of an embedded document, when the viewer may\n * read the source revision. Whatever it finds, the document itself reads\n * as the revision embedding it does.\n * @returns The source, or null for the root, for a document whose source is\n * unknown, and for a source the viewer may not read, which are not\n * told apart.\n */\nasync function sourceOf(\n ctx: UserContext,\n node: InterpretedNode,\n): Promise<Source | null> {\n const revisionId = nodeRevisions.get(node);\n if (revisionId == null || node.path.length === 0) return null;\n return (\n (await sourcesOf(ctx, revisionId)).get(JSON.stringify(node.path)) ?? null\n );\n}\n\nconst occurrenceFields = {\n representation: {\n description:\n \"Whether the value is an IRI, an embedded document or a `Link`.\",\n },\n iri:\n \"A reference's IRI, an embedded document's `id`, or a `Link`'s `href`, \" +\n \"with a compact IRI expanded; null for an anonymous embedded value.\",\n node:\n \"The embedded document or `Link` as the saved document embeds it, \" +\n \"which may differ from the resource's current revision; null for a \" +\n \"reference.\",\n resource:\n \"The resource currently registered under `iri`, or null when there is \" +\n \"none, or when the viewer may read neither it nor any of its \" +\n \"revisions. A deleted resource is returned too, since its revisions \" +\n \"stay readable. It is never fetched.\",\n} as const;\n\nDocumentRelation.implement({\n description:\n \"One value of a relation property, in source order including duplicates.\",\n fields: (t) => ({\n property: t.expose(\"property\", { type: RelationProperty }),\n path: t.expose(\"path\", {\n type: \"JSON\",\n description:\n \"The source path of the value from the root of the saved document, \" +\n 'such as `[\"object\", 0]`.',\n }),\n representation: t.expose(\"representation\", {\n type: RelationRepresentation,\n ...occurrenceFields.representation,\n }),\n iri: t.expose(\"iri\", {\n type: \"URL\",\n nullable: true,\n description: occurrenceFields.iri,\n }),\n node: t.expose(\"node\", {\n type: DocumentNode,\n nullable: true,\n description: occurrenceFields.node,\n }),\n resource: t.field({\n type: Resource,\n nullable: true,\n description: occurrenceFields.resource,\n resolve: (occurrence, _, ctx) => registeredResource(ctx, occurrence.iri),\n }),\n }),\n});\n\nDocumentRecipient.implement({\n description:\n \"One value of an addressing property, in source order including \" +\n \"duplicates and anonymous embedded recipients.\",\n fields: (t) => ({\n property: t.expose(\"property\", { type: AddressingProperty }),\n position: t.exposeInt(\"position\", {\n description:\n \"The index of the value in its property's list, or 0 for a value \" +\n \"written alone.\",\n }),\n path: t.expose(\"path\", {\n type: \"JSON\",\n description:\n \"The source path of the value from the root of the saved document.\",\n }),\n representation: t.expose(\"representation\", {\n type: RelationRepresentation,\n ...occurrenceFields.representation,\n }),\n iri: t.expose(\"iri\", {\n type: \"URL\",\n nullable: true,\n description: occurrenceFields.iri,\n }),\n node: t.expose(\"node\", {\n type: DocumentNode,\n nullable: true,\n description: occurrenceFields.node,\n }),\n resource: t.field({\n type: Resource,\n nullable: true,\n description: occurrenceFields.resource,\n resolve: (occurrence, _, ctx) => registeredResource(ctx, occurrence.iri),\n }),\n }),\n});\n\nDocumentNode.implement({\n description:\n \"A vocabulary document of a saved revision, the root or one embedded in \" +\n \"it at any depth, read by meaning, whatever keys spell its properties. \" +\n \"It may be anonymous.\",\n fields: (t) => ({\n path: t.expose(\"path\", {\n type: \"JSON\",\n description:\n 'The source path from the root, such as `[\"object\", 0]`; `[]` is ' +\n \"the root.\",\n }),\n property: t.exposeString(\"property\", {\n nullable: true,\n description:\n \"The standard name of the property that embeds it, whatever its \" +\n \"source spelling; null for the root.\",\n }),\n type: t.expose(\"type\", {\n type: \"URL\",\n description: \"The type IRI, such as `…/activitystreams#Note`.\",\n }),\n kind: t.expose(\"kind\", { type: DocumentNodeKindEnum }),\n iri: t.expose(\"iri\", {\n type: \"URL\",\n nullable: true,\n description:\n \"Its `id`, or the `href` of a `Link`, with a compact IRI expanded; \" +\n \"null when it has none.\",\n }),\n document: t.expose(\"value\", {\n type: \"JSON\",\n description: \"Its JSON as saved, with everything it embeds.\",\n }),\n relations: t.field({\n type: [DocumentRelation],\n args: { property: t.arg({ type: RelationProperty }) },\n description:\n \"Its own `actor`, `object`, `target`, `origin`, `result`, \" +\n \"`instrument` and `attributedTo` values, or those of one property, \" +\n \"in that order, then in source order including duplicates. Empty \" +\n \"for a property it does not have.\",\n resolve: (node, { property }) =>\n property == null\n ? node.relations\n : node.relations.filter((entry) => entry.property === property),\n }),\n addressing: t.field({\n type: [DocumentRecipient],\n args: { property: t.arg({ type: AddressingProperty }) },\n description:\n \"Its own `to`, `cc`, `bto`, `bcc` and `audience` values, or those \" +\n \"of one property, in that order, then in source order including \" +\n \"duplicates.\",\n resolve: (node, { property }) =>\n property == null\n ? node.addressing\n : node.addressing.filter((entry) => entry.property === property),\n }),\n extensions: t.expose(\"extensions\", {\n type: [DocumentExtension],\n description:\n \"Its own custom extension properties, by their source keys, sorted.\",\n }),\n source: t.field({\n type: DocumentSource,\n nullable: true,\n description:\n \"The revision this embedded document came from, as recorded when \" +\n \"the document embedding it was saved. Null for the root, for an \" +\n \"embedded document whose source is unknown, such as one saved \" +\n \"before sources were recorded or pasted without one, and when the \" +\n \"viewer may not read the source revision, which are not told \" +\n \"apart. It hides nothing else: the document reads as the revision \" +\n \"embedding it does, whatever its source.\",\n resolve: (node, _, ctx) => sourceOf(ctx, node),\n }),\n }),\n});\n\nDocumentSource.implement({\n description:\n \"The revision an embedded document came from, which the viewer may \" +\n \"read.\",\n fields: (t) => ({\n relation: t.expose(\"relation\", { type: DocumentSourceRelation }),\n revision: t.field({\n type: ResourceRevisionRef,\n description: \"The source revision, of the resource the document names.\",\n resolve: (source) => source.revision,\n }),\n status: t.field({\n type: DocumentSourceStatus,\n nullable: true,\n description:\n \"Whether the source revision is still current, or a later revision \" +\n \"or a deletion followed it; null when the viewer may not read the \" +\n \"resource's current revision.\",\n resolve: (source) => source.status,\n }),\n }),\n});\n\ntype Content = Pick<ResourceRevisionRow, \"id\" | \"kind\" | \"document\">;\n\nconst interpretations = new WeakMap<Content, InterpretedNode | null>();\nconst validations = new WeakMap<Content, readonly Diagnostic[]>();\n\n/**\n * Interprets a revision's document once per loaded row.\n * @returns The root, or null unless the revision is a snapshot whose\n * document the validator reads without errors.\n */\nfunction rootOf(revision: Content): InterpretedNode | null {\n if (!interpretations.has(revision)) {\n const nodes =\n revision.kind === \"snapshot\"\n ? interpretDocument(revision.document)\n : null;\n for (const node of nodes ?? []) nodeRevisions.set(node, revision.id);\n interpretations.set(revision, nodes?.[0] ?? null);\n }\n return interpretations.get(revision)!;\n}\n\nfunction diagnosticsOf(revision: Content): readonly Diagnostic[] {\n let diagnostics = validations.get(revision);\n if (diagnostics == null) {\n diagnostics =\n revision.kind === \"snapshot\"\n ? validateDocument(revision.document).diagnostics\n : [];\n validations.set(revision, diagnostics);\n }\n return diagnostics;\n}\n\nconst content = { columns: { id: true, kind: true, document: true } } as const;\n\nconst ResourceRevisionRef = builder.drizzleNode(\"resourceRevisions\", {\n name: \"ResourceRevision\",\n description:\n \"An immutable revision of a resource. Each revision, past ones \" +\n \"included, is readable by evidence of its own, not by the current \" +\n \"state of its resource: one saved by DrFed for a local actor by anyone, \" +\n \"blind recipients and unpublished activities included; one addressed \" +\n \"to the public by anyone; one a receipt links to a delivery to a local \" +\n \"instance the viewer is a member of by its members; and the current \" +\n \"revision of a resource with a legacy typed row as `Activity` and \" +\n \"`Object` tell. Where its embedded documents came from never hides \" +\n \"it. Administrators read every revision. A later \" +\n \"restriction or deletion of the resource hides no earlier revision. A \" +\n \"revision the viewer may not read is left out as if it did not exist.\",\n // A node lookup checks the revision by its own ID.\n select: { columns: { id: true, resourceId: true } },\n id: { column: (revision) => revision.id },\n fields: (t) => ({\n resource: t.relation(\"resource\"),\n sequence: t.exposeInt(\"sequence\", {\n description: \"Increases with each revision of the resource.\",\n }),\n kind: t.expose(\"kind\", { type: ResourceRevisionKind }),\n capture: t.expose(\"capture\", { type: ResourceRevisionCapture }),\n backfilled: t.exposeBoolean(\"backfilled\", {\n description: \"Whether the migration from legacy typed rows created it.\",\n }),\n created: t.expose(\"created\", {\n type: \"DateTime\",\n description: \"When DrFed stored the revision.\",\n }),\n document: t.expose(\"document\", {\n type: \"JSON\",\n nullable: true,\n description:\n \"The saved JSON as is, `bto` and `bcc` included for local \" +\n \"resources. Read `root` instead of parsing it by keys, which \" +\n \"aliases and contexts may spell otherwise. Null unless `kind` is \" +\n \"`snapshot`, or for a snapshot of JSON null.\",\n }),\n interpreted: t.boolean({\n description:\n \"Whether `root` could be derived from `document`. When false, \" +\n \"`root` is null and, for a snapshot, `diagnostics` explain why.\",\n select: content,\n resolve: (revision) => rootOf(revision) != null,\n }),\n root: t.field({\n type: DocumentNode,\n nullable: true,\n description:\n \"The root document read by meaning; null unless `interpreted`.\",\n select: content,\n resolve: (revision) => rootOf(revision),\n }),\n diagnostics: t.field({\n type: [DocumentDiagnostic],\n description:\n \"What the current validator finds in the saved document, which may \" +\n \"differ from what it found when the revision was stored. Empty \" +\n \"unless `kind` is `snapshot`.\",\n select: content,\n resolve: (revision) => diagnosticsOf(revision),\n }),\n deleted: t.expose(\"deleted\", {\n type: \"DateTime\",\n nullable: true,\n description: \"The deletion time of a whiteout; null otherwise.\",\n }),\n formerTypes: t.field({\n type: [\"URL\"],\n nullable: true,\n description:\n \"The type IRIs the resource had, for a whiteout; null otherwise. \" +\n 'Stored ActivityStreams names, such as `\"Note\"`, are expanded with ' +\n \"`https://www.w3.org/ns/activitystreams#`.\",\n select: { columns: { formerTypes: true } },\n resolve: (revision) =>\n revision.formerTypes?.map((type) =>\n type.includes(\":\") ? type : `${ACTIVITY_STREAMS}${type}`,\n ) ?? null,\n }),\n }),\n});\nexport const ResourceRevision: DrFedObjectRef = ResourceRevisionRef;\n\nbuilder.drizzleObjectField(\"resources\", \"currentRevision\", (t) =>\n t.field({\n type: ResourceRevisionRef,\n nullable: true,\n description:\n \"The current revision; null for a resource without revisions, or when \" +\n \"the viewer may not read the current revision.\",\n select: { columns: { id: true } },\n resolve: async (resource, _, ctx) =>\n (await ctx.db.query.resourceRevisions.findFirst({\n where: {\n RAW: (table) =>\n and(\n inArray(\n table.id,\n ctx.db\n .select({ id: schema.resourceHeads.revisionId })\n .from(schema.resourceHeads)\n .where(eq(schema.resourceHeads.resourceId, resource.id)),\n ),\n readableRevision(ctx, table.id),\n )!,\n },\n })) ?? null,\n }),\n);\n\nbuilder.drizzleObjectField(\"resources\", \"revision\", (t) =>\n t.field({\n type: ResourceRevisionRef,\n nullable: true,\n args: { sequence: t.arg.int({ required: true }) },\n description:\n \"The revision with the given sequence; null when there is none, or \" +\n \"when the viewer may not read it, which are not told apart.\",\n select: { columns: { id: true } },\n resolve: async (resource, { sequence }, ctx) =>\n (await ctx.db.query.resourceRevisions.findFirst({\n where: {\n resourceId: resource.id,\n sequence,\n RAW: (table) => readableRevision(ctx, table.id),\n },\n })) ?? null,\n }),\n);\n\nbuilder.drizzleObjectField(\"resources\", \"revisions\", (t) =>\n t.relatedConnection(\n \"revisions\",\n {\n description:\n \"The revisions the viewer may read, newest first. Others are left \" +\n \"out, so sequences may skip.\",\n query: (_, ctx) => ({\n where: { RAW: (table) => readableRevision(ctx, table.id) },\n orderBy: { sequence: \"desc\" },\n }),\n },\n { name: \"ResourceRevisionConnection\" },\n { name: \"ResourceRevisionEdge\" },\n ),\n);\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport builder, { type DrFedObjectRef } from \"./builder.ts\";\n\nconst KeyRef = builder.drizzleNode(\"keys\", {\n name: \"Key\",\n description:\n \"A remote public key, identified by its IRI. Readable by any \" +\n \"authenticated viewer, since it holds public material only.\",\n authScopes: { authenticated: true },\n runScopesOnType: true,\n id: { column: (key) => key.id },\n fields: (t) => ({\n uuid: t.expose(\"id\", { type: \"UUID\" }),\n iri: t.expose(\"iri\", { type: \"URL\" }),\n created: t.expose(\"created\", { type: \"DateTime\" }),\n versions: t.relatedConnection(\"versions\", {\n description: \"The observed versions of the key, oldest first.\",\n query: { orderBy: { firstSeen: \"asc\", id: \"asc\" } },\n }),\n }),\n});\nexport const Key: DrFedObjectRef = KeyRef;\nconst observationDescription =\n \"DrFed observation time, not the remote key rotation time; \" +\n \"does not imply continuous use between observations.\";\nconst KeyVersionRef = builder.drizzleNode(\"keyVersions\", {\n name: \"KeyVersion\",\n description:\n \"Immutable public key material observed under a `Key`. Readable by \" +\n \"any authenticated viewer.\",\n authScopes: { authenticated: true },\n runScopesOnType: true,\n id: { column: (version) => version.id },\n fields: (t) => ({\n uuid: t.expose(\"id\", { type: \"UUID\" }),\n key: t.relation(\"key\"),\n publicKey: t.expose(\"publicKey\", { type: \"JSON\" }),\n fingerprint: t.exposeString(\"fingerprint\"),\n firstSeen: t.expose(\"firstSeen\", {\n type: \"DateTime\",\n description: `First ${observationDescription}`,\n }),\n lastSeen: t.expose(\"lastSeen\", {\n type: \"DateTime\",\n description: `Last ${observationDescription}`,\n }),\n }),\n});\nexport const KeyVersion: DrFedObjectRef = KeyVersionRef;\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n// oxlint-disable import/no-unassigned-import\nimport \"./account.ts\";\nimport \"./instance.ts\";\nimport \"./auth/entry.ts\";\nimport \"./actor.ts\";\nimport \"./object.ts\";\nimport \"./revision.ts\";\nimport \"./activity-delivery/entry.ts\";\nimport \"./key.ts\";\nimport builder from \"./builder.ts\";\n\nbuilder.queryType({});\nbuilder.mutationType({});\n\nexport const schema = builder.toSchema();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAa,aAAa,OAAO,QAC/B,IAAI,WACF,MAAM,OAAO,OAAO,OAAO,WAAW,YAAY,OAAO,GAAG,CAAC,CAC/D,CAAC,CAAC,MAAM;AAEV,MAAM,cAAc,IAAI,YAAY;AAEpC,MAAM,qBAAqB;AAE3B,MAAa,4BACX,OAAO,gBAAgB,IAAI,WAAW,kBAAkB,CAAC,CAAC,CAAC,SAAS;CAClE,UAAU;CACV,aAAa;AACf,CAAC;;;ACJH,SAAwB,gBAAgB,EACtC,UACA,aACA,MACA,gBACgC;CAChC,eAAe,UAAU,aAAa;CACtC,eAAe,UAAU,MAAM;CAE/B,IAAI;C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jD,aAAa,EAAE,aAAa,aAAa;EACzC,WAAW,EAAE,OAAO,aAAa;GAC/B,MAAM;GACN,aAAa,SAAS;EACxB,CAAC;EACD,UAAU,EAAE,OAAO,YAAY;GAC7B,MAAM;GACN,aAAa,QAAQ;EACvB,CAAC;CACH;AACF,CAAC;;;ACpCD,QAAQ,UAAU,CAAC,CAAC;AACpB,QAAQ,aAAa,CAAC,CAAC;AAEvB,MAAaE,WAAS,QAAQ,SAAS"}
|
package/dist/schema.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.mts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"schema.d.mts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;;;cA6Ba,0BAAM"}
|
package/dist/schema.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as schema } from "./schema-
|
|
1
|
+
export { t as schema } from "./schema-eJO_-DWq.mjs";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drfed/graphql",
|
|
3
|
-
"version": "0.2.0-dev.
|
|
3
|
+
"version": "0.2.0-dev.716",
|
|
4
4
|
"description": "A GraphQL server for DrFed.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ActivityPub",
|
|
@@ -74,6 +74,10 @@
|
|
|
74
74
|
"types": "./dist/object.d.mts",
|
|
75
75
|
"default": "./dist/object.mjs"
|
|
76
76
|
},
|
|
77
|
+
"./readable": {
|
|
78
|
+
"types": "./dist/readable.d.mts",
|
|
79
|
+
"default": "./dist/readable.mjs"
|
|
80
|
+
},
|
|
77
81
|
"./activity-delivery": {
|
|
78
82
|
"types": "./dist/activity-delivery/entry.d.mts",
|
|
79
83
|
"default": "./dist/activity-delivery/entry.mjs"
|
|
@@ -93,6 +97,7 @@
|
|
|
93
97
|
"src/instance.ts",
|
|
94
98
|
"src/schema.ts",
|
|
95
99
|
"src/object.ts",
|
|
100
|
+
"src/readable.ts",
|
|
96
101
|
"src/activity-delivery/entry.ts"
|
|
97
102
|
],
|
|
98
103
|
"dts": {
|
|
@@ -109,8 +114,8 @@
|
|
|
109
114
|
"typescript": "^7.0.2"
|
|
110
115
|
},
|
|
111
116
|
"dependencies": {
|
|
112
|
-
"@drfed/federation": "0.2.0-dev.
|
|
113
|
-
"@drfed/models": "0.2.0-dev.
|
|
117
|
+
"@drfed/federation": "0.2.0-dev.716",
|
|
118
|
+
"@drfed/models": "0.2.0-dev.716",
|
|
114
119
|
"@faker-js/faker": "^10.5.0",
|
|
115
120
|
"@fedify/uri-template": "^2.3.1",
|
|
116
121
|
"@fedify/fedify": "2.4.3",
|
|
@@ -140,13 +145,13 @@
|
|
|
140
145
|
},
|
|
141
146
|
"drfedBuild": {
|
|
142
147
|
"enabled": true,
|
|
143
|
-
"version": "0.2.0-dev.
|
|
144
|
-
"fullVersion": "0.2.0-dev.
|
|
148
|
+
"version": "0.2.0-dev.716",
|
|
149
|
+
"fullVersion": "0.2.0-dev.716+c33e1199",
|
|
145
150
|
"baseVersion": "0.2.0",
|
|
146
151
|
"channel": "dev",
|
|
147
|
-
"sha": "
|
|
148
|
-
"runNumber": "
|
|
149
|
-
"runId": "
|
|
152
|
+
"sha": "c33e11999ed51c7b2c86e33f66440196c7863f50",
|
|
153
|
+
"runNumber": "716",
|
|
154
|
+
"runId": "45125661114",
|
|
150
155
|
"ref": "refs/heads/main",
|
|
151
156
|
"workflow": ".github/workflows/main.yaml"
|
|
152
157
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"actor-B1FAD_C_.mjs","names":["and","eq","uuid"],"sources":["../src/resource.ts","../src/actor.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { activitySelection, objectSelection } from \"@drfed/federation/object\";\nimport { schema } from \"@drfed/models\";\nimport type { Resource as ResourceRow } from \"@drfed/models/schema\";\nimport { type Uuid, validateUuid } from \"@drfed/models/uuid\";\nimport { PothosValidationError } from \"@pothos/core\";\nimport { resolveCursorConnection } from \"@pothos/plugin-relay\";\nimport { type SQL, type SQLWrapper, and, eq, sql } from \"drizzle-orm\";\n\nimport builder, { type DrFedObjectRef } from \"./builder.ts\";\nimport {\n classificationAuthor,\n classificationInput,\n classifyMastodon,\n classifyMisskey,\n} from \"./classification.ts\";\nimport {\n type Viewer,\n isReadableResource,\n readableResource,\n} from \"./readable.ts\";\n\nexport const ResourceKind = builder.enumType(\"ResourceKind\", {\n values: schema.resourceKindEnum.enumValues,\n});\nexport const ResourceDetail = builder.unionType(\"ResourceDetail\", {\n types: () => [Activity, Collection],\n resolveType: async (value, ctx) => {\n const { id } = value as { id: Uuid };\n const row = await ctx.db.query.resources.findFirst({ where: { id } });\n if (row == null || row.kind === \"unknown\") {\n throw new Error(\"Missing typed resource.\");\n }\n return (\n {\n actor: \"Actor\",\n object: \"Object\",\n activity: \"Activity\",\n collection: \"Collection\",\n } as const\n )[row.kind];\n },\n});\nconst ResourceRef = builder.drizzleNode(\"resources\", {\n name: \"Resource\",\n id: { column: (row) => row.id },\n fields: (t) => ({\n iri: t.expose(\"iri\", { type: \"URL\" }),\n kind: t.expose(\"kind\", { type: ResourceKind }),\n detail: t.field({\n type: ResourceDetail,\n nullable: true,\n description:\n \"Typed details, or null while unknown, when the typed row or its author/owner is deleted, or when the viewer may not read it.\",\n select: { columns: { id: true, iri: true, kind: true } },\n resolve: (row, _, ctx) => resolveResource(ctx, row),\n }),\n }),\n});\nexport const Resource: DrFedObjectRef = ResourceRef;\n\n/**\n * Loads the typed record so union fragments see the complete entity.\n * @returns The typed entity, or null when it or its author is deleted, or when\n * the viewer may not read it.\n */\nexport async function resolveResource(\n viewer: Viewer,\n row: ResourceRow,\n): Promise<{ id: Uuid } | null> {\n const { db } = viewer;\n const visible = await db.query.resources.findFirst({\n where: {\n id: row.id,\n RAW: (table) =>\n and(visibleResource(table.id), readableResource(viewer, table.id))!,\n },\n columns: { id: true },\n });\n if (visible == null) return null;\n if (row.kind === \"unknown\") return null;\n const where = { id: row.id };\n const result =\n row.kind === \"actor\"\n ? await db.query.actors.findFirst({ where })\n : row.kind === \"object\"\n ? await db.query.objects.findFirst({ where })\n : row.kind === \"activity\"\n ? await db.query.activities.findFirst({ where })\n : await db.query.collections.findFirst({ where });\n // Generic revision-backed resources have no legacy typed details yet.\n return result ?? null;\n}\n\nexport function registerAddressingFields(\n table: \"objects\" | \"activities\",\n): void {\n for (const property of schema.addressingPropertyEnum.enumValues) {\n builder.drizzleObjectField(table, property, (t) =>\n t.field({\n type: [Resource],\n description: `Stored ${property} occurrences, in original order including duplicates.`,\n select: { columns: { id: true } },\n resolve: async (row, _, ctx) =>\n (\n await ctx.db.query.addressing.findMany({\n where: { sourceId: row.id, property },\n orderBy: { position: \"asc\" },\n with: { targetResource: true },\n })\n ).map((entry) => entry.targetResource),\n }),\n );\n }\n}\n\nconst CollectionType = builder.enumType(\"CollectionType\", {\n values: schema.collectionTypeEnum.enumValues,\n});\nconst CollectionRef = builder.drizzleNode(\"collections\", {\n name: \"Collection\",\n select: {\n columns: { id: true },\n with: { ownerActor: { columns: { deleted: true } } },\n },\n id: { column: (row) => row.id },\n fields: (t) => ({\n resource: t.relation(\"resource\"),\n iri: t.field({\n type: \"URL\",\n select: { with: { resource: true } },\n resolve: (row) => row.resource.iri,\n }),\n type: t.expose(\"type\", { type: CollectionType }),\n owner: t.relation(\"ownerActor\", {\n nullable: true,\n query: { where: { deleted: { isNull: true } } },\n }),\n declaredTotalItems: t.exposeInt(\"totalItems\", {\n nullable: true,\n description:\n \"The `totalItems` reported by the collection document. It can differ from the locally observed count and is null for local collections. Unlike `totalCount` and `items`, this value is not recalculated when deleted actors, deleted objects, or resources authored by deleted actors are excluded.\",\n }),\n totalCount: t.int({\n description:\n \"The number of locally stored, visible members. It can differ from `declaredTotalItems`. Deleted actors, deleted objects, resources authored by deleted actors, and resources the viewer may not read are excluded from this count and `items`.\",\n select: { columns: { id: true } },\n resolve: (row, _, ctx) =>\n ctx.db.$count(\n schema.collectionItems,\n and(\n eq(schema.collectionItems.collectionId, row.id),\n visibleResource(schema.collectionItems.itemId),\n readableResource(ctx, schema.collectionItems.itemId),\n ),\n ),\n }),\n items: t.connection({\n type: Resource,\n description:\n \"The locally stored, visible members. Deleted actors, deleted objects, resources authored by deleted actors, and resources the viewer may not read are excluded from this connection and `totalCount`.\",\n select: { columns: { id: true } },\n resolve: (row, args, ctx) => {\n const positions = new Map<Uuid, number | null>();\n return resolveCursorConnection<Promise<ResourceRow[]>>(\n {\n args,\n toCursor: (item: ResourceRow) => {\n if (!positions.has(item.id)) {\n throw new Error(\"Missing collection item position.\");\n }\n return encodeCollectionCursor({\n position: positions.get(item.id)!,\n itemId: item.id,\n });\n },\n },\n async ({ before, after, limit, inverted }) => {\n const parsedBefore =\n before == null ? undefined : parseCollectionCursor(before);\n const parsedAfter =\n after == null ? undefined : parseCollectionCursor(after);\n const items = await ctx.db.query.collectionItems.findMany({\n where: {\n collectionId: row.id,\n RAW: (table) =>\n and(\n visibleResource(table.itemId),\n readableResource(ctx, table.itemId),\n collectionCursorPredicate(\n table.position,\n table.itemId,\n parsedBefore,\n parsedAfter,\n ),\n )!,\n },\n orderBy: collectionItemsOrder(inverted),\n limit,\n with: { item: true },\n });\n for (const item of items) {\n positions.set(item.itemId, item.position);\n }\n return items.map((item) => item.item);\n },\n );\n },\n }),\n }),\n});\nexport const Collection: DrFedObjectRef = CollectionRef;\n\ninterface CollectionCursor {\n position: number | null;\n itemId: Uuid;\n}\n\nconst BASE64_PATTERN =\n /^(?:[A-Za-z\\d+/]{4})*(?:[A-Za-z\\d+/]{2}==|[A-Za-z\\d+/]{3}=)?$/u;\n\nfunction encodeCollectionCursor(cursor: CollectionCursor): string {\n return Buffer.from(JSON.stringify([cursor.position, cursor.itemId])).toString(\n \"base64\",\n );\n}\n\nfunction parseCollectionCursor(cursor: string): CollectionCursor {\n if (cursor === \"\" || !BASE64_PATTERN.test(cursor)) {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n const decoded = Buffer.from(cursor, \"base64\");\n if (decoded.toString(\"base64\") !== cursor) {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n let value: unknown;\n try {\n value = JSON.parse(decoded.toString(\"utf8\"));\n } catch {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n if (!Array.isArray(value) || value.length !== 2) {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n const [position, itemId] = value;\n if (\n (position !== null &&\n (!Number.isInteger(position) ||\n position < -2_147_483_648 ||\n position > 2_147_483_647)) ||\n !validateUuid(itemId)\n ) {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n return { position, itemId };\n}\n\nfunction collectionCursorPredicate(\n positionColumn: SQLWrapper,\n itemIdColumn: SQLWrapper,\n before?: CollectionCursor,\n after?: CollectionCursor,\n): SQL | undefined {\n return and(\n after == null\n ? undefined\n : after.position == null\n ? sql`${positionColumn} is null and ${itemIdColumn} > ${after.itemId}`\n : sql`(\n ${positionColumn} > ${after.position}\n or (${positionColumn} = ${after.position} and ${itemIdColumn} > ${after.itemId})\n or ${positionColumn} is null\n )`,\n before == null\n ? undefined\n : before.position == null\n ? sql`(\n ${positionColumn} is not null\n or (${positionColumn} is null and ${itemIdColumn} < ${before.itemId})\n )`\n : sql`(\n ${positionColumn} < ${before.position}\n or (${positionColumn} = ${before.position} and ${itemIdColumn} < ${before.itemId})\n )`,\n );\n}\n\nfunction collectionItemsOrder(inverted: boolean): {\n position: \"asc\" | \"desc\";\n itemId: \"asc\" | \"desc\";\n} {\n // The keyset predicates rely on PostgreSQL's default ASC NULLS LAST and\n // DESC NULLS FIRST ordering.\n const direction = inverted ? \"desc\" : \"asc\";\n return { position: direction, itemId: direction };\n}\n\nconst Implementation = builder.enumType(\"Implementation\", {\n values: [\"MASTODON\", \"MISSKEY\"] as const,\n});\nconst ExpectedClassification = builder.objectRef<\n ReturnType<typeof classifyMastodon>\n>(\"ExpectedClassification\");\nExpectedClassification.implement({\n description:\n \"Expected classification; actual access depends on receiver state and policy.\",\n fields: (t) => ({\n implementation: t.expose(\"implementation\", { type: Implementation }),\n version: t.exposeString(\"version\"),\n classification: t.exposeString(\"classification\"),\n reason: t.exposeString(\"reason\"),\n }),\n});\nexport const ActivityType = builder.enumType(\"ActivityType\", {\n values: schema.activityTypeEnum.enumValues,\n});\nconst ActivityRef = builder.drizzleNode(\"activities\", {\n name: \"Activity\",\n description:\n \"Represents an ActivityPub activity. An activity of a local actor is \" +\n \"readable whatever its addressing. One of a remote actor is readable \" +\n \"only when it is addressed to the public, by members of the local \" +\n \"instances that received it, and by administrators; otherwise it is \" +\n \"left out as if it did not exist.\",\n select: {\n columns: { id: true },\n with: { actor: { columns: { deleted: true } } },\n },\n id: { column: (row) => row.id },\n fields: (t) => ({\n resource: t.relation(\"resource\"),\n iri: t.field({\n type: \"URL\",\n select: { with: { resource: true } },\n resolve: (row) => row.resource.iri,\n }),\n type: t.expose(\"type\", { type: ActivityType }),\n actor: t.relation(\"actor\"),\n object: t.field({\n type: Resource,\n nullable: true,\n description:\n \"The resource the activity acts on, or null when there is none or \" +\n \"the viewer may not read it.\",\n select: { with: { object: true } },\n resolve: async (row, _, ctx) =>\n row.object != null && (await isReadableResource(ctx, row.object.id))\n ? row.object\n : null,\n }),\n expectedClassifications: t.field({\n type: [ExpectedClassification],\n description:\n \"Expected classifications for this activity and its Object. Empty if the object is absent, hidden, or not an Object.\",\n select: { columns: { id: true } },\n resolve: async (activity, _, ctx) => {\n const row = await ctx.db.query.activities.findFirst({\n where: { id: activity.id },\n with: activitySelection,\n });\n // As hidden from this viewer as `object` is, its addressing included.\n if (\n row?.objectId == null ||\n !(await isReadableResource(ctx, row.objectId))\n ) {\n return [];\n }\n const object = await ctx.db.query.objects.findFirst({\n where: {\n id: row.objectId,\n deleted: { isNull: true },\n actor: { deleted: { isNull: true } },\n },\n with: {\n ...objectSelection,\n actor: {\n with: {\n resource: true,\n collectionReferences: {\n with: { collection: { with: { resource: true } } },\n },\n },\n },\n },\n });\n if (object == null) return [];\n const addressing = classificationInput(object);\n const input = classificationInput(row);\n const author = classificationAuthor(object.actor);\n return [\n classifyMastodon(addressing, input, author),\n classifyMisskey(addressing, input, author),\n ];\n },\n }),\n published: t.expose(\"published\", { type: \"DateTime\" }),\n document: t.expose(\"document\", { type: \"JSON\", nullable: true }),\n }),\n});\nexport const Activity: DrFedObjectRef = ActivityRef;\nregisterAddressingFields(\"activities\");\n\n/**\n * Excludes deleted actors and objects, including resources authored or\n * owned by deleted actors.\n * @returns A predicate for a resource ID in an outer query.\n */\nfunction visibleResource(id: SQLWrapper): SQL {\n return sql`not exists (\n select 1 from ${schema.actors}\n where ${schema.actors.id} = ${id} and ${schema.actors.deleted} is not null\n ) and not exists (\n select 1 from ${schema.objects}\n join ${schema.actors} on ${schema.actors.id} = ${schema.objects.actorId}\n where ${schema.objects.id} = ${id}\n and (${schema.objects.deleted} is not null or ${schema.actors.deleted} is not null)\n ) and not exists (\n select 1 from ${schema.activities}\n join ${schema.actors} on ${schema.actors.id} = ${schema.activities.actorId}\n where ${schema.activities.id} = ${id} and ${schema.actors.deleted} is not null\n ) and not exists (\n select 1 from ${schema.collections}\n join ${schema.actors} on ${schema.actors.id} = ${schema.collections.ownerActorId}\n where ${schema.collections.id} = ${id} and ${schema.actors.deleted} is not null\n )`;\n}\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n// oxlint-disable max-lines-per-function eslint/max-lines\n\n// Keep dependent database writes and observations sequential.\n// oxlint-disable no-await-in-loop\n\nimport { enqueueActorKeyGeneration } from \"@drfed/federation\";\nimport { type Database, promoteResource, schema } from \"@drfed/models\";\nimport { type CollectionRole, actorTypeEnum } from \"@drfed/models/schema\";\nimport { type Uuid, uuidV7 as uuid } from \"@drfed/models/uuid\";\nimport { faker } from \"@faker-js/faker\";\nimport type { Context } from \"@fedify/fedify\";\nimport { drizzleConnectionHelpers } from \"@pothos/plugin-drizzle\";\nimport type { PgInsertValue } from \"drizzle-orm/pg-core\";\nimport { and, eq, gt, isNotNull, isNull } from \"drizzle-orm/sql/expressions\";\n\nimport builder, { type DrFedObjectRef } from \"./builder.ts\";\nimport { Instance } from \"./instance.ts\";\nimport { Collection, ResourceDetail } from \"./resource.ts\";\n\nconst ActorType = builder.enumType(\"ActorType\", {\n values: actorTypeEnum.enumValues,\n});\n\nconst ACTOR_TYPES_DOC = actorTypeEnum.enumValues\n .map((t) => `\\`${t}\\``)\n .join(\" | \");\n\nasync function resolveActorCollection(\n db: Database,\n actorId: Uuid,\n role: CollectionRole,\n) {\n const reference = await db.query.actorCollectionReferences.findFirst({\n where: { actorId, role },\n with: {\n collection: {\n with: { ownerActor: { columns: { deleted: true } } },\n },\n },\n });\n const collection = reference?.collection;\n return collection?.ownerActor?.deleted == null ? (collection ?? null) : null;\n}\n\nconst USERNAME_DOC =\n \"The username of the `Actor`. A remote actor's is its \" +\n \"`preferredUsername` as received, which is null when it has none and \" +\n \"need not be unique.\";\n\nconst ActorRef = builder.drizzleNode(\"actors\", {\n name: \"Actor\",\n description: \"Represents an `Actor` in the DrFed platform.\",\n id: {\n column: ({ id }) => id,\n description: \"The unique identifier of the `Actor`.\",\n },\n fields: (t) => ({\n resource: t.relation(\"resource\"),\n iri: t.field({\n type: \"URL\",\n select: { with: { resource: true } },\n resolve: (row) => row.resource.iri,\n }),\n uuid: t.expose(\"id\", {\n type: \"UUID\",\n description: \"The UUID of the `Actor`.\",\n }),\n handle: t.field({\n type: \"String\",\n nullable: true,\n description:\n \"The handle of the `Actor`, its `username` and its `Instance`'s \" +\n \"host. For a remote actor, this is not a verified WebFinger \" +\n \"address. Null when `username` is.\",\n select: {\n columns: { username: true },\n with: { instance: { columns: { host: true } } },\n },\n resolve: ({ instance, username }) =>\n username == null ? null : `@${username}@${instance.host}`,\n }),\n type: t.expose(\"type\", {\n type: ActorType,\n description: `The type of the \\`Actor\\`: ${ACTOR_TYPES_DOC}`,\n }),\n username: t.exposeString(\"username\", {\n nullable: true,\n description: USERNAME_DOC,\n }),\n instance: t.relation(\"instance\", {\n description: \"The `Instance` that the `Actor` belongs to.\",\n }),\n local: t.relation(\"localActor\", {\n nullable: true,\n description: \"The local details of the `Actor`, or null if it is remote.\",\n }),\n inboxUrl: t.expose(\"inboxUrl\", {\n type: \"URL\",\n description: \"The inbox URL of the `Actor`.\",\n }),\n outbox: t.field({\n type: Collection,\n nullable: true,\n description:\n \"The stored outbox collection. For local actors, it contains every stored `Create` activity regardless of addressing and retains activities whose objects are deleted so their recorded history remains inspectable. The ActivityPub outbox serves only activities with Public addressing whose objects are not deleted.\",\n select: { columns: { id: true } },\n resolve: (actor, _, ctx) =>\n resolveActorCollection(ctx.db, actor.id, \"outbox\"),\n }),\n avatarUrl: t.expose(\"avatarUrl\", {\n type: \"URL\",\n description: \"The avatar URL of the `Actor`.\",\n nullable: true,\n }),\n followers: t.field({\n type: Collection,\n nullable: true,\n select: { columns: { id: true } },\n resolve: (actor, _, ctx) =>\n resolveActorCollection(ctx.db, actor.id, \"followers\"),\n }),\n following: t.field({\n type: Collection,\n nullable: true,\n select: { columns: { id: true } },\n resolve: (actor, _, ctx) =>\n resolveActorCollection(ctx.db, actor.id, \"following\"),\n }),\n headerUrl: t.expose(\"headerUrl\", {\n type: \"URL\",\n description: \"The header URL of the `Actor`.\",\n nullable: true,\n }),\n profileUrl: t.expose(\"profileUrl\", {\n type: \"URL\",\n description: \"The profile URL of the `Actor`.\",\n nullable: true,\n }),\n featured: t.field({\n type: Collection,\n nullable: true,\n select: { columns: { id: true } },\n resolve: (actor, _, ctx) =>\n resolveActorCollection(ctx.db, actor.id, \"featured\"),\n }),\n created: t.expose(\"created\", {\n type: \"DateTime\",\n description: \"The creation date/time of the `Actor`.\",\n }),\n }),\n});\n\nexport const Actor: DrFedObjectRef = ActorRef;\nResourceDetail.addTypes([Actor]);\n\nconst LocalActorRef = builder.drizzleNode(\"localActors\", {\n name: \"LocalActor\",\n select: {\n columns: { id: true },\n with: { actor: { columns: { deleted: true } } },\n },\n description: \"Represents the local details of an `Actor`.\",\n id: {\n column: ({ id }) => id,\n description: \"The unique identifier of the local actor details.\",\n },\n fields: (t) => ({\n uuid: t.expose(\"id\", {\n type: \"UUID\",\n description: \"The UUID of the local actor details.\",\n }),\n avatar: t.exposeString(\"avatar\", {\n nullable: true,\n description: \"The profile image of the actor.\",\n }),\n header: t.exposeString(\"header\", {\n nullable: true,\n description: \"The profile banner image of the actor.\",\n }),\n }),\n});\n\nexport const LocalActor: DrFedObjectRef = LocalActorRef;\n\ninterface CreateActorsSuccess {\n readonly actors: readonly (typeof ActorRef.$inferType)[];\n}\n\nconst CreateActorsSuccessRef = builder.objectRef<CreateActorsSuccess>(\n \"CreateActorsSuccess\",\n);\n\nCreateActorsSuccessRef.implement({\n fields: (t) => ({\n actors: t.field({\n type: [ActorRef],\n resolve: ({ actors }) => actors,\n }),\n }),\n});\n\nconst INVALID_SIZE = \"InvalidSize\" as const;\nconst INSTANCE_NOT_FOUND = \"InstanceNotFound\" as const;\nconst INVALID_INSTANCE_HOST = \"InvalidInstanceHost\" as const;\nconst TOO_MANY_ACTORS = \"TooManyActors\" as const;\nconst CreateActorsErrors = [\n INVALID_SIZE,\n INSTANCE_NOT_FOUND,\n INVALID_INSTANCE_HOST,\n TOO_MANY_ACTORS,\n] as const;\n\nconst CreateActorsErrorType = builder.enumType(\"CreateActorsErrorType\", {\n values: CreateActorsErrors,\n});\n\ninterface CreateActorsError {\n readonly type: typeof CreateActorsErrorType.$inferType;\n readonly message: string;\n}\n\nconst CreateActorsErrorRef =\n builder.objectRef<CreateActorsError>(\"CreateActorsError\");\n\nCreateActorsErrorRef.implement({\n description: \"Represents an error that occurred while creating an `Actor`.\",\n fields: (t) => ({\n type: t.expose(\"type\", {\n type: CreateActorsErrorType,\n description:\n \"The type of the error. Use this for programmatic error handling.\",\n }),\n message: t.exposeString(\"message\", {\n description:\n \"A human-readable message describing the error. \" +\n \"Don't use this for programmatic error handling, \" +\n \"use the `type` field instead.\",\n }),\n }),\n});\n\nconst CreateActorsResult = builder.unionType(\"CreateActorsResult\", {\n types: [CreateActorsSuccessRef, CreateActorsErrorRef],\n resolveType(value) {\n if (\"message\" in value) return CreateActorsErrorRef;\n return CreateActorsSuccessRef;\n },\n});\n\nbuilder.mutationFields((t) => ({\n generateActors: t.field({\n type: CreateActorsResult,\n description: \"Create actors.\",\n authScopes: { authenticated: true },\n args: {\n instance: t.arg.globalID({\n for: Instance,\n required: true,\n description: \"The ID of the target instance\",\n }),\n size: t.arg({\n type: \"Int\",\n required: true,\n description: \"How many actors to generate\",\n }),\n },\n async resolve(_query, { instance: { id: instanceId }, size }, ctx) {\n if (size < 1) {\n return {\n type: INVALID_SIZE,\n message: `${size} is too small. At least 1 or more.`,\n };\n }\n if (ctx.account == null) {\n // Note that the following error is not expected to be thrown,\n // because the `authScopes` option above should prevent this resolver\n throw new Error(\"You must be authenticated to create actors.\");\n }\n const { account } = ctx;\n // Relay decodes global IDs as strings; Instance uses UUID identifiers.\n const targetInstanceId = instanceId as Uuid;\n\n let createdOrigin: URL | undefined;\n const result = await ctx.db.transaction(async (tx) => {\n // Find the instance that the account is included\n const [instance] = await tx\n .select({\n host: schema.instances.host,\n maxActors: schema.localInstances.maxActors,\n })\n .from(schema.instanceMembers)\n .for(\"update\", { of: schema.localInstances })\n .innerJoin(\n schema.instances,\n eq(schema.instanceMembers.instanceId, schema.instances.id),\n )\n .innerJoin(\n schema.localInstances,\n eq(schema.instances.localId, schema.localInstances.id),\n )\n .where(\n and(\n eq(schema.instanceMembers.accountId, account.id),\n gt(schema.localInstances.expires, Temporal.Now.instant()),\n eq(schema.instances.id, targetInstanceId),\n isNotNull(schema.instanceMembers.accepted),\n ),\n )\n .limit(1);\n if (instance == null) {\n return {\n type: INSTANCE_NOT_FOUND,\n message: \"Can't find the instance.\",\n };\n }\n // Read the stored authority rather than recomposing it from the\n // slug, so that actor URIs cannot drift from the instance the rest of\n // the fediverse already knows.\n const { host, maxActors } = instance;\n const instanceUrl = `${ctx.rootOrigin.protocol}//${host}`;\n // Stored authorities can outlive the runtime that accepted them.\n if (!URL.canParse(instanceUrl)) {\n return {\n type: INVALID_INSTANCE_HOST,\n message:\n `The instance host ${JSON.stringify(host)} cannot be parsed by ` +\n \"this server. Contact the server administrator.\",\n };\n }\n const currActors = await tx.$count(\n schema.actors,\n eq(schema.actors.instanceId, targetInstanceId),\n );\n\n if (size + currActors > maxActors) {\n return {\n type: TOO_MANY_ACTORS,\n message: `${size} is too big. The maximum number of actors of ${\n host\n } is ${maxActors} and the current number of actors is ${\n currActors\n }.`,\n };\n }\n // Create actors\n createdOrigin = new URL(instanceUrl);\n const fedCtx = ctx.federation.createContext(\n new URL(instanceUrl),\n undefined,\n );\n const ids = Array.from({ length: size }, () => ({ id: uuid() }));\n await tx.insert(schema.localActors).values(ids);\n const createdActors = [];\n for (const { id } of ids) {\n const actor = await promoteResource(\n tx,\n fedCtx.getActorUri(id).href,\n \"actor\",\n async (inner, resource) => {\n for (let attempt = 0; attempt < 10; attempt += 1) {\n const [createdActor] = await inner\n .insert(schema.actors)\n .values(generateActor(resource.id, targetInstanceId, fedCtx))\n .onConflictDoNothing({\n target: [schema.actors.username, schema.actors.instanceId],\n // Only the partial index of local actors' usernames.\n where: isNotNull(schema.actors.localId),\n })\n .returning();\n if (createdActor != null) {\n return createdActor;\n }\n }\n throw new Error(\"Actor insertion returned no row.\");\n },\n id,\n );\n for (const [role, iri] of [\n [\"followers\", fedCtx.getFollowersUri(id).href],\n [\"following\", fedCtx.getFollowingUri(id).href],\n [\"featured\", fedCtx.getFeaturedUri(id).href],\n [\"outbox\", fedCtx.getOutboxUri(id).href],\n ] as const) {\n await promoteResource(\n tx,\n iri,\n \"collection\",\n async (inner, resource) => {\n await inner.insert(schema.collections).values({\n id: resource.id,\n type: \"OrderedCollection\",\n ownerActorId: actor.id,\n });\n await inner.insert(schema.actorCollectionReferences).values({\n actorId: actor.id,\n role,\n collectionId: resource.id,\n });\n },\n );\n }\n createdActors.push(actor);\n }\n return { actors: createdActors };\n });\n if (\"actors\" in result && createdOrigin != null) {\n await enqueueActorKeyGeneration(\n ctx.federation.createContext(createdOrigin, undefined),\n result.actors.map((actor) => actor.id),\n );\n }\n return result;\n },\n }),\n}));\n\nfunction generateActor(\n id: Uuid,\n instanceId: Uuid,\n fedCtx: Context<unknown>,\n): PgInsertValue<typeof schema.actors> {\n const username = faker.internet\n .username()\n .toLowerCase()\n .replace(/[^a-z0-9_]/gu, \"_\");\n\n return {\n id,\n localId: id,\n username,\n instanceId,\n type: \"Person\",\n inboxUrl: fedCtx.getInboxUri(id).href,\n profileUrl: new URL(`/@${username}`, fedCtx.origin).href,\n };\n}\n\nconst actorsConnection = drizzleConnectionHelpers(builder, \"actors\", {\n query: { orderBy: { created: \"desc\", id: \"desc\" } },\n});\n\nbuilder.drizzleObjectField(\"instances\", \"actors\", (t) =>\n t.connection(\n {\n type: Actor,\n description: \"The `Actor`s that belong to the `Instance`.\",\n select(args, ctx, nestedSelection) {\n return {\n with: {\n actors: actorsConnection.getQuery(args, ctx, nestedSelection),\n },\n };\n },\n resolve(instance, args, ctx) {\n return {\n ...actorsConnection.resolve(instance.actors, args, ctx, instance),\n totalCount() {\n return ctx.db.$count(\n schema.actors,\n and(\n eq(schema.actors.instanceId, instance.id),\n isNull(schema.actors.deleted),\n ),\n );\n },\n };\n },\n },\n {\n fields(fb) {\n return {\n totalCount: fb.int({\n description:\n \"The total number of `Actor`s that belong to the `Instance`.\",\n resolve(connection) {\n return connection.totalCount();\n },\n }),\n };\n },\n },\n {\n fields(fb) {\n return {\n created: fb.expose(\"created\", {\n type: \"DateTime\",\n description:\n \"The date/time when the `Actor` was added to the `Instance`.\",\n }),\n type: fb.expose(\"type\", {\n type: ActorType,\n description: `The type of the \\`Actor\\`: ${ACTOR_TYPES_DOC}`,\n }),\n username: fb.exposeString(\"username\", {\n nullable: true,\n description: USERNAME_DOC,\n }),\n };\n },\n },\n ),\n);\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,MAAa,eAAe,QAAQ,SAAS,gBAAgB,EAC3D,QAAQ,OAAO,iBAAiB,WAClC,CAAC;AACD,MAAa,iBAAiB,QAAQ,UAAU,kBAAkB;CAChE,aAAa,CAAC,UAAU,UAAU;CAClC,aAAa,OAAO,OAAO,QAAQ;EACjC,MAAM,EAAE,OAAO;EACf,MAAM,MAAM,MAAM,IAAI,GAAG,MAAM,UAAU,UAAU,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;EACpE,IAAI,OAAO,QAAQ,IAAI,SAAS,WAC9B,MAAM,IAAI,MAAM,yBAAyB;EAE3C,OACE;GACE,OAAO;GACP,QAAQ;GACR,UAAU;GACV,YAAY;EACd,EACA,IAAI;CACR;AACF,CAAC;AAiBD,MAAa,WAhBO,QAAQ,YAAY,aAAa;CACnD,MAAM;CACN,IAAI,EAAE,SAAS,QAAQ,IAAI,GAAG;CAC9B,SAAS,OAAO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A,MAAM,mBAAmB,yBAAyB,SAAS,UAAU,EACnE,OAAO,EAAE,SAAS;CAAE,SAAS;CAAQ,IAAI;AAAO,EAAE,EACpD,CAAC;AAED,QAAQ,mBAAmB,aAAa,WAAW,MACjD,EAAE,WACA;CACE,MAAM;CACN,aAAa;CACb,OAAO,MAAM,KAAK,iBAAiB;EACjC,OAAO,EACL,MAAM,EACJ,QAAQ,iBAAiB,SAAS,MAAM,KAAK,eAAe,EAC9D,EACF;CACF;CACA,QAAQ,UAAU,MAAM,KAAK;EAC3B,OAAO;GACL,GAAG,iBAAiB,QAAQ,SAAS,QAAQ,MAAM,KAAK,QAAQ;GAChE,aAAa;IACX,OAAO,IAAI,GAAG,OACZ,OAAO,QACP,IACE,GAAG,OAAO,OAAO,YAAY,SAAS,EAAE,GACxC,OAAO,OAAO,OAAO,OAAO,CAC9B,CACF;GACF;EACF;CACF;AACF,GACA,EACE,OAAO,IAAI;CACT,OAAO,EACL,YAAY,GAAG,IAAI;EACjB,aACE;EACF,QAAQ,YAAY;GAClB,OAAO,WAAW,WAAW;EAC/B;CACF,CAAC,EACH;AACF,EACF,GACA,EACE,OAAO,IAAI;CACT,OAAO;EACL,SAAS,GAAG,OAAO,WAAW;GAC5B,MAAM;GACN,aACE;EACJ,CAAC;EACD,MAAM,GAAG,OAAO,QAAQ;GACtB,MAAM;GACN,aAAa,8BAA8B;EAC7C,CAAC;EACD,UAAU,GAAG,aAAa,YAAY;GACpC,UAAU;GACV,aAAa;EACf,CAAC;CACH;AACF,EACF,CACF,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"builder-BLioFAdv.mjs","names":["OperationsPlugin"],"sources":["../src/operations.ts","../src/builder.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport SchemaBuilder, { BasePlugin, type SchemaTypes } from \"@pothos/core\";\nimport type {\n GraphQLFieldResolver,\n GraphQLIsTypeOfFn,\n GraphQLTypeResolver,\n} from \"graphql\";\n\n/** Track the lifetime of work that may outlive a cancelled HTTP request. */\nexport type OperationTracker = <T>(\n operation: () => T | Promise<T>,\n) => Promise<T>;\n\nclass OperationsPlugin<Types extends SchemaTypes> extends BasePlugin<Types> {\n // Pothos requires an instance hook even when the wrapper has no plugin state.\n // oxlint-disable-next-line class-methods-use-this\n override wrapResolve(\n resolve: GraphQLFieldResolver<unknown, Types[\"Context\"], object>,\n ): GraphQLFieldResolver<unknown, Types[\"Context\"], object> {\n return (parent, args, context, info) => {\n const { trackOperation } = context as {\n trackOperation?: OperationTracker;\n };\n return trackOperation == null\n ? resolve(parent, args, context, info)\n : trackOperation(() => resolve(parent, args, context, info));\n };\n }\n // Pothos dispatches abstract type resolution separately from field resolution.\n // oxlint-disable-next-line class-methods-use-this\n override wrapResolveType(\n resolveType: GraphQLTypeResolver<unknown, Types[\"Context\"]>,\n ): GraphQLTypeResolver<unknown, Types[\"Context\"]> {\n return (parent, context, info, type) => {\n const { trackOperation } = context as {\n trackOperation?: OperationTracker;\n };\n return trackOperation == null\n ? resolveType(parent, context, info, type)\n : trackOperation(() => resolveType(parent, context, info, type));\n };\n }\n\n // ScopeAuth performs type-level authorization through this separate hook.\n // oxlint-disable-next-line class-methods-use-this\n override wrapIsTypeOf(\n isTypeOf: GraphQLIsTypeOfFn<unknown, Types[\"Context\"]> | undefined,\n ): GraphQLIsTypeOfFn<unknown, Types[\"Context\"]> | undefined {\n if (isTypeOf == null) return isTypeOf;\n return (parent, context, info) => {\n const { trackOperation } = context as {\n trackOperation?: OperationTracker;\n };\n return trackOperation == null\n ? isTypeOf(parent, context, info)\n : trackOperation(() => isTypeOf(parent, context, info));\n };\n }\n}\n\ndeclare global {\n // Pothos registers plugin types through this namespace.\n // oxlint-disable-next-line typescript/no-namespace\n namespace PothosSchemaTypes {\n interface Plugins<Types extends SchemaTypes> {\n drfedOperations: OperationsPlugin<Types>;\n }\n }\n}\n\nSchemaBuilder.registerPlugin(\"drfedOperations\", OperationsPlugin);\n\nexport default \"drfedOperations\" as const;\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { type Database, normalizeEmail, relations } from \"@drfed/models\";\nimport { type Account, type Session, instances } from \"@drfed/models/schema\";\nimport type { Uuid } from \"@drfed/models/uuid\";\nimport type { Federation } from \"@fedify/fedify\";\nimport { Template } from \"@fedify/uri-template\";\nimport SchemaBuilder, { type ObjectRef } from \"@pothos/core\";\nimport DrizzlePlugin from \"@pothos/plugin-drizzle\";\nimport ErrorsPlugin from \"@pothos/plugin-errors\";\nimport RelayPlugin from \"@pothos/plugin-relay\";\nimport ScopeAuthPlugin from \"@pothos/plugin-scope-auth\";\nimport type { Transport } from \"@upyo/core\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\nimport { eq } from \"drizzle-orm/sql/expressions\";\nimport { GraphQLScalarType, Kind } from \"graphql\";\nimport { JSONResolver, URLResolver, UUIDResolver } from \"graphql-scalars\";\n\nimport OperationsPlugin, { type OperationTracker } from \"./operations.ts\";\nimport { hideUnreadableNodes, memberInstances } from \"./readable.ts\";\n\n/**\n * The context data for the GraphQL server, which includes the incoming request\n * object and any additional information needed for processing GraphQL queries\n * and mutations.\n */\nexport interface ServerContext {\n /** Combined request and runtime shutdown cancellation for active work. */\n readonly operationSignal?: AbortSignal | undefined;\n\n /** Optional runtime owner for work that survives HTTP cancellation. */\n readonly trackOperation?: OperationTracker | undefined;\n\n /**\n * The incoming HTTP request.\n */\n readonly request: Request;\n\n /**\n * The database instance.\n */\n readonly db: Database;\n\n /**\n * Email sending services.\n */\n readonly mailer: Transport;\n\n /**\n * The address login mail is sent from.\n */\n readonly emailFrom: string;\n\n /**\n * Origins for login.\n */\n readonly loginOrigins: ReadonlySet<string>;\n\n /**\n * The root origin of this deployment, which every instance's subdomain is\n * derived from. It is always equal to its own origin, i.e. it carries no\n * path, query or credentials.\n */\n readonly rootOrigin: URL;\n\n /**\n * The federation instance.\n */\n readonly federation: Federation<unknown>;\n}\n\n/**\n * The user-related context data for the GraphQL server, which include every\n * field from the {@link ServerContext}.\n */\nexport interface UserContext extends ServerContext {\n /**\n * Session information.\n */\n readonly session?: Session;\n\n /**\n * Current viewer.\n */\n readonly account?: Account;\n}\n\nexport interface SchemaTypes {\n Context: UserContext;\n Scalars: {\n JSON: { Input: unknown; Output: unknown };\n DateTime: {\n Input: Temporal.Instant;\n Output: Temporal.Instant;\n };\n Email: {\n Input: string;\n Output: string;\n };\n UUID: {\n Input: Uuid;\n Output: Uuid;\n };\n URITemplate: {\n Input: Template;\n Output: Template;\n };\n URL: {\n Input: string;\n Output: string;\n };\n };\n DefaultFieldNullability: false;\n DrizzleRelations: typeof relations;\n AuthScopes: {\n authenticated: boolean;\n admin: boolean;\n /**\n * Whether the viewer is an accepted member of the `Instance` backed by\n * the `LocalInstance` with the given UUID.\n */\n localInstanceMember: Uuid;\n /**\n * Whether the viewer is the `Account` with the given UUID.\n */\n accountSelf: Uuid;\n };\n}\n\nexport type DrFedSchemaTypes =\n PothosSchemaTypes.ExtendDefaultTypes<SchemaTypes>;\n\nexport type DrFedObjectRef<Shape = unknown, Parent = Shape> = ObjectRef<\n DrFedSchemaTypes,\n Shape,\n Parent\n>;\n\n/**\n * The GraphQL schema builder.\n */\nexport const builder = new SchemaBuilder<SchemaTypes>({\n defaultFieldNullability: false,\n drizzle: {\n client(ctx) {\n return ctx.db;\n },\n getTableConfig,\n relations,\n },\n plugins: [\n OperationsPlugin,\n DrizzlePlugin,\n RelayPlugin,\n ErrorsPlugin,\n ScopeAuthPlugin,\n ],\n errors: { defaultTypes: [] },\n relay: {\n nodeQueryOptions: {\n resolve: async (_, { id }, ctx, __, resolveNode) => {\n const [node] = await hideUnreadableNodes(ctx, [\n filterDeleted(await resolveNode(id)),\n ]);\n return node;\n },\n },\n nodesQueryOptions: {\n resolve: async (_, { ids }, ctx, __, resolveNodes) =>\n await hideUnreadableNodes(\n ctx,\n (await resolveNodes(ids)).map(filterDeleted),\n ),\n },\n },\n scopeAuth: {\n authorizeOnSubscribe: true,\n authScopes(context) {\n return {\n authenticated: Boolean(context.session),\n admin: Boolean(context.account?.admin),\n localInstanceMember(localInstanceId) {\n return isLocalInstanceMember(context, localInstanceId);\n },\n accountSelf(accountId) {\n return context.account?.id === accountId;\n },\n };\n },\n },\n});\n\nconst isDeleted = (node: unknown): boolean =>\n node != null &&\n typeof node === \"object\" &&\n \"deleted\" in node &&\n node.deleted != null;\n\n// Relations whose deletion hides the node: an object's or activity's\n// author, or a collection's owner.\nconst OWNER_RELATIONS = [\"actor\", \"ownerActor\"] as const;\n\nconst filterDeleted = (node: unknown): unknown =>\n isDeleted(node) ||\n (node != null &&\n typeof node === \"object\" &&\n OWNER_RELATIONS.some((key) =>\n isDeleted((node as Record<string, unknown>)[key]),\n ))\n ? null\n : node;\n\n/**\n * Determines whether the viewer is an accepted member of the `Instance` that\n * the given `LocalInstance` backs. Pending members, i.e. those who have been\n * invited but have not accepted yet, do not count.\n *\n * Pothos caches scope results per request by scope name and parameter, so this\n * runs at most once per `LocalInstance` per request.\n *\n * @param context The request context, whose `account` is the viewer.\n * @param localInstanceId The UUID of the `LocalInstance` to check.\n * @returns Whether the viewer is an accepted member.\n */\nasync function isLocalInstanceMember(\n context: UserContext,\n localInstanceId: Uuid,\n): Promise<boolean> {\n const { account } = context;\n if (account == null) return false;\n const rows = await memberInstances(\n context.db,\n account.id,\n eq(instances.localId, localInstanceId),\n ).limit(1);\n return rows.length > 0;\n}\n\nbuilder.scalarType(\"DateTime\", {\n description: \"An ISO 8601 instant preserving sub-millisecond precision.\",\n serialize(value) {\n if (!(value instanceof Temporal.Instant)) {\n throw new TypeError(\"Expected a Temporal.Instant.\");\n }\n return value.toString();\n },\n parseValue(value) {\n if (typeof value !== \"string\") {\n throw new TypeError(\"Expected an instant string.\");\n }\n return Temporal.Instant.from(value);\n },\n parseLiteral(node) {\n if (node.kind !== Kind.STRING) {\n throw new TypeError(\"Expected an instant string.\");\n }\n return Temporal.Instant.from(node.value);\n },\n});\nbuilder.addScalarType(\n \"URL\",\n new GraphQLScalarType({\n ...URLResolver.toConfig(),\n serialize(value) {\n URLResolver.serialize(value);\n return String(value);\n },\n // Validate URLs while preserving the caller's exact spelling.\n parseValue(value) {\n URLResolver.parseValue(value);\n return String(value);\n },\n parseLiteral(node, variables) {\n URLResolver.parseLiteral(node, variables);\n if (node.kind !== Kind.STRING) {\n throw new TypeError(\"Expected a URL string.\");\n }\n return node.value;\n },\n }),\n);\nbuilder.addScalarType(\"JSON\", JSONResolver);\n\nbuilder.scalarType(\"Email\", {\n parseValue: (v) => normalizeEmail(String(v)),\n serialize: (v) => normalizeEmail(v),\n});\n\nbuilder.addScalarType(\"UUID\", UUIDResolver);\n\nbuilder.scalarType(\"URITemplate\", {\n parseValue(v) {\n if (v instanceof Template) {\n return v;\n }\n return Template.parse(String(v));\n },\n serialize(v) {\n return v.toString();\n },\n});\n\nexport const Node = builder.nodeInterfaceRef();\n\nexport default builder;\n"],"mappings":";;;;;;;;;;;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,UAAU,OAAO;EACf,YAAY,UAAU,KAAK;EAC3B,OAAO,OAAO,KAAK;CACrB;CAEA,WAAW,OAAO;EAChB,YAAY,WAAW,KAAK;EAC5B,OAAO,OAAO,KAAK;CACrB;CACA,aAAa,MAAM,WAAW;EAC5B,YAAY,aAAa,MAAM,SAAS;EACxC,IAAI,KAAK,SAAS,KAAK,QACrB,MAAM,IAAI,UAAU,wBAAwB;EAE9C,OAAO,KAAK;CACd;AACF,CAAC,CACH;AACA,QAAQ,cAAc,QAAQ,YAAY;AAE1C,QAAQ,WAAW,SAAS;CAC1B,aAAa,MAAM,eAAe,OAAO,CAAC,CAAC;CAC3C,YAAY,MAAM,eAAe,CAAC;AACpC,CAAC;AAED,QAAQ,cAAc,QAAQ,YAAY;AAE1C,QAAQ,WAAW,eAAe;CAChC,WAAW,GAAG;EACZ,IAAI,aAAa,UACf,OAAO;EAET,OAAO,SAAS,MAAM,OAAO,CAAC,CAAC;CACjC;CACA,UAAU,GAAG;EACX,OAAO,EAAE,SAAS;CACpB;AACF,CAAC;AAED,MAAa,OAAO,QAAQ,iBAAiB"}
|
|
@@ -1,140 +0,0 @@
|
|
|
1
|
-
import { activities, activityDeliveries, actors, addressing, instanceMembers, instances, objects, resources } from "@drfed/models/schema";
|
|
2
|
-
import { alias } from "drizzle-orm/pg-core";
|
|
3
|
-
import { PUBLIC_IRI } from "@drfed/models/resource";
|
|
4
|
-
import { validateUuid } from "@drfed/models/uuid";
|
|
5
|
-
import { and, eq, inArray, isNotNull, not, sql } from "drizzle-orm";
|
|
6
|
-
//#region src/readable.ts
|
|
7
|
-
/**
|
|
8
|
-
* The IRIs that address an activity or object to the public: the full one and
|
|
9
|
-
* the compacted forms a JSON-LD document may carry.
|
|
10
|
-
*/
|
|
11
|
-
const PUBLIC_IRIS = [
|
|
12
|
-
PUBLIC_IRI,
|
|
13
|
-
"as:Public",
|
|
14
|
-
"Public"
|
|
15
|
-
];
|
|
16
|
-
/**
|
|
17
|
-
* The local instances an account is an accepted member of; pending members,
|
|
18
|
-
* who have been invited but have not accepted yet, do not count.
|
|
19
|
-
* @returns A query of their IDs.
|
|
20
|
-
*/
|
|
21
|
-
const memberInstances = (db, accountId, ...conditions) => db.select({ instanceId: instanceMembers.instanceId }).from(instanceMembers).innerJoin(instances, eq(instanceMembers.instanceId, instances.id)).where(and(eq(instanceMembers.accountId, accountId), isNotNull(instanceMembers.accepted), isNotNull(instances.localId), ...conditions));
|
|
22
|
-
/**
|
|
23
|
-
* Restricts rows to those of the local instances whose private records the
|
|
24
|
-
* viewer may read: every local instance for an administrator, and those the
|
|
25
|
-
* viewer is an accepted member of otherwise, as the `admin` and
|
|
26
|
-
* `localInstanceMember` scopes decide for one instance. Filtering rows by it
|
|
27
|
-
* before paging keeps a connection from telling of rows the viewer may not
|
|
28
|
-
* read.
|
|
29
|
-
* @param viewer The viewer and the database.
|
|
30
|
-
* @param instanceId The column of the instance a row belongs to.
|
|
31
|
-
* @returns The condition on the column.
|
|
32
|
-
*/
|
|
33
|
-
function viewableInstance(viewer, instanceId) {
|
|
34
|
-
const { account } = viewer;
|
|
35
|
-
if (account == null) return sql`false`;
|
|
36
|
-
return account.admin ? inArray(instanceId, viewer.db.select({ id: instances.id }).from(instances).where(isNotNull(instances.localId))) : inArray(instanceId, memberInstances(viewer.db, account.id));
|
|
37
|
-
}
|
|
38
|
-
const authors = alias(actors, "readable_authors");
|
|
39
|
-
const remoteActivities = alias(activities, "readable_remote_activities");
|
|
40
|
-
const remoteObjects = alias(objects, "readable_remote_objects");
|
|
41
|
-
const carriers = alias(activities, "readable_carriers");
|
|
42
|
-
const entries = alias(addressing, "readable_addressing");
|
|
43
|
-
const targets = alias(resources, "readable_targets");
|
|
44
|
-
const deliveries = alias(activityDeliveries, "readable_deliveries");
|
|
45
|
-
const remoteActivity = (id) => sql`exists (
|
|
46
|
-
select 1 from ${activities} ${remoteActivities}
|
|
47
|
-
join ${actors} ${authors} on ${authors.id} = ${remoteActivities.actorId}
|
|
48
|
-
where ${remoteActivities.id} = ${id} and ${authors.localId} is null
|
|
49
|
-
)`;
|
|
50
|
-
const remoteObject = (id) => sql`exists (
|
|
51
|
-
select 1 from ${objects} ${remoteObjects}
|
|
52
|
-
join ${actors} ${authors} on ${authors.id} = ${remoteObjects.actorId}
|
|
53
|
-
where ${remoteObjects.id} = ${id} and ${authors.localId} is null
|
|
54
|
-
)`;
|
|
55
|
-
const addressedPublicly = (id) => sql`exists (
|
|
56
|
-
select 1 from ${addressing} ${entries}
|
|
57
|
-
join ${resources} ${targets} on ${targets.id} = ${entries.targetId}
|
|
58
|
-
where ${entries.sourceId} = ${id} and ${inArray(targets.iri, PUBLIC_IRIS)}
|
|
59
|
-
)`;
|
|
60
|
-
const received = (viewer, id, mark) => sql`exists (
|
|
61
|
-
select 1 from ${activityDeliveries} ${deliveries}
|
|
62
|
-
where ${deliveries.activityId} = ${id}
|
|
63
|
-
and ${deliveries.direction} = 'inbound'
|
|
64
|
-
and ${mark}
|
|
65
|
-
and ${viewableInstance(viewer, deliveries.instanceId)}
|
|
66
|
-
)`;
|
|
67
|
-
const readableActivity = (viewer, id) => sql`(not ${remoteActivity(id)} or ${addressedPublicly(id)} or ${received(viewer, id, deliveries.carriedSnapshot)})`;
|
|
68
|
-
const readableObject = (viewer, id) => sql`(not ${remoteObject(id)} or ${addressedPublicly(id)} or exists (
|
|
69
|
-
select 1 from ${objects} ${remoteObjects}
|
|
70
|
-
join ${activities} ${carriers} on ${carriers.id} = ${remoteObjects.activityId}
|
|
71
|
-
where ${remoteObjects.id} = ${id}
|
|
72
|
-
and (
|
|
73
|
-
(not ${remoteObjects.fetched} and ${addressedPublicly(carriers.id)})
|
|
74
|
-
or ${received(viewer, carriers.id, deliveries.carriedObjectSnapshot)}
|
|
75
|
-
)
|
|
76
|
-
))`;
|
|
77
|
-
/**
|
|
78
|
-
* Restricts resources to those the viewer may read. Received content is an
|
|
79
|
-
* inbox's, which ActivityPub filters by the requester's permission (5.2) and
|
|
80
|
-
* opens without authentication only when addressed to the public (5.6):
|
|
81
|
-
*
|
|
82
|
-
* - An administrator reads everything.
|
|
83
|
-
* - An activity of a remote actor is readable when it is addressed to the
|
|
84
|
-
* public, or when one of the local instances the viewer is a member of
|
|
85
|
-
* received it, i.e. an inbound delivery to it is linked to the activity
|
|
86
|
-
* and carried it as stored. A delivery of the same IRI with other
|
|
87
|
-
* contents stays linked but opens nothing.
|
|
88
|
-
* - An object of a remote actor is readable when it is addressed to the
|
|
89
|
-
* public, when the activity that carried it embedded in it is, or when
|
|
90
|
-
* one of the local instances the viewer is a member of received that
|
|
91
|
-
* activity and the object as stored with it. An object fetched apart
|
|
92
|
-
* from the activity is opened neither by the activity being public nor
|
|
93
|
-
* by a delivery but one that fetched it as stored.
|
|
94
|
-
* - Everything else, including the activities and objects of local actors
|
|
95
|
-
* whatever their addressing, is readable.
|
|
96
|
-
*
|
|
97
|
-
* Filtering rows by it before paging keeps a connection from telling of rows
|
|
98
|
-
* the viewer may not read.
|
|
99
|
-
* @param viewer The viewer and the database.
|
|
100
|
-
* @param id The resource ID in an outer query.
|
|
101
|
-
* @returns The condition on the ID.
|
|
102
|
-
*/
|
|
103
|
-
function readableResource(viewer, id) {
|
|
104
|
-
if (viewer.account?.admin === true) return sql`true`;
|
|
105
|
-
return sql`(${readableActivity(viewer, id)} and ${readableObject(viewer, id)})`;
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Finds the resources among the given IDs that the viewer may not read, as
|
|
109
|
-
* {@link readableResource} decides. IDs of anything but a resource are never
|
|
110
|
-
* among them.
|
|
111
|
-
* @returns The IDs the viewer may not read.
|
|
112
|
-
*/
|
|
113
|
-
async function unreadableResources(viewer, ids) {
|
|
114
|
-
if (ids.length === 0 || viewer.account?.admin === true) return /* @__PURE__ */ new Set();
|
|
115
|
-
const rows = await viewer.db.select({ id: resources.id }).from(resources).where(and(inArray(resources.id, [...ids]), not(readableResource(viewer, resources.id))));
|
|
116
|
-
return new Set(rows.map(({ id }) => id));
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Determines whether the viewer may read the resource.
|
|
120
|
-
* @returns Whether {@link readableResource} holds for it.
|
|
121
|
-
*/
|
|
122
|
-
const isReadableResource = async (viewer, id) => !(await unreadableResources(viewer, [id])).has(id);
|
|
123
|
-
const nodeIdOf = (node) => node != null && typeof node === "object" && "id" in node && validateUuid(node.id) ? node.id : null;
|
|
124
|
-
/**
|
|
125
|
-
* Replaces the Relay nodes the viewer may not read by null, as if they did
|
|
126
|
-
* not exist. Activities, objects, and resources share their IDs, so a node's
|
|
127
|
-
* ID alone tells whether it is one the viewer may not read.
|
|
128
|
-
* @returns The nodes, in the same order.
|
|
129
|
-
*/
|
|
130
|
-
async function hideUnreadableNodes(viewer, nodes) {
|
|
131
|
-
const hidden = await unreadableResources(viewer, nodes.map(nodeIdOf).filter((id) => id != null));
|
|
132
|
-
return nodes.map((node) => {
|
|
133
|
-
const id = nodeIdOf(node);
|
|
134
|
-
return id != null && hidden.has(id) ? null : node;
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
//#endregion
|
|
138
|
-
export { readableResource as a, memberInstances as i, hideUnreadableNodes as n, viewableInstance as o, isReadableResource as r, PUBLIC_IRIS as t };
|
|
139
|
-
|
|
140
|
-
//# sourceMappingURL=readable-CSN0MPlO.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"readable-CSN0MPlO.mjs","names":[],"sources":["../src/readable.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport type { Database } from \"@drfed/models\";\nimport { PUBLIC_IRI } from \"@drfed/models/resource\";\nimport {\n type Account,\n activities,\n activityDeliveries,\n actors,\n addressing,\n instanceMembers,\n instances,\n objects,\n resources,\n} from \"@drfed/models/schema\";\nimport { type Uuid, validateUuid } from \"@drfed/models/uuid\";\nimport {\n type SQL,\n type SQLWrapper,\n and,\n eq,\n inArray,\n isNotNull,\n not,\n sql,\n} from \"drizzle-orm\";\nimport { type PgColumn, alias } from \"drizzle-orm/pg-core\";\n\n/**\n * The IRIs that address an activity or object to the public: the full one and\n * the compacted forms a JSON-LD document may carry.\n */\nexport const PUBLIC_IRIS: readonly string[] = [\n PUBLIC_IRI,\n \"as:Public\",\n \"Public\",\n];\n\n/**\n * Who reads, and the database to decide what they may read in.\n */\nexport interface Viewer {\n readonly db: Database;\n readonly account?: Account;\n}\n\n/**\n * The local instances an account is an accepted member of; pending members,\n * who have been invited but have not accepted yet, do not count.\n * @returns A query of their IDs.\n */\nexport const memberInstances = (\n db: Database,\n accountId: Uuid,\n ...conditions: SQL[]\n) =>\n db\n .select({ instanceId: instanceMembers.instanceId })\n .from(instanceMembers)\n .innerJoin(instances, eq(instanceMembers.instanceId, instances.id))\n .where(\n and(\n eq(instanceMembers.accountId, accountId),\n isNotNull(instanceMembers.accepted),\n isNotNull(instances.localId),\n ...conditions,\n ),\n );\n\n/**\n * Restricts rows to those of the local instances whose private records the\n * viewer may read: every local instance for an administrator, and those the\n * viewer is an accepted member of otherwise, as the `admin` and\n * `localInstanceMember` scopes decide for one instance. Filtering rows by it\n * before paging keeps a connection from telling of rows the viewer may not\n * read.\n * @param viewer The viewer and the database.\n * @param instanceId The column of the instance a row belongs to.\n * @returns The condition on the column.\n */\nexport function viewableInstance(viewer: Viewer, instanceId: PgColumn): SQL {\n const { account } = viewer;\n if (account == null) return sql`false`;\n return account.admin\n ? inArray(\n instanceId,\n viewer.db\n .select({ id: instances.id })\n .from(instances)\n .where(isNotNull(instances.localId)),\n )\n : inArray(instanceId, memberInstances(viewer.db, account.id));\n}\n\n// The predicates below are nested into queries on the same tables, so each\n// subquery reads an alias of its own to never capture the outer row. An\n// alias renders as its name alone, so a FROM clause names its table as well.\nconst authors = alias(actors, \"readable_authors\");\nconst remoteActivities = alias(activities, \"readable_remote_activities\");\nconst remoteObjects = alias(objects, \"readable_remote_objects\");\nconst carriers = alias(activities, \"readable_carriers\");\nconst entries = alias(addressing, \"readable_addressing\");\nconst targets = alias(resources, \"readable_targets\");\nconst deliveries = alias(activityDeliveries, \"readable_deliveries\");\n\nconst remoteActivity = (id: SQLWrapper): SQL => sql`exists (\n select 1 from ${activities} ${remoteActivities}\n join ${actors} ${authors} on ${authors.id} = ${remoteActivities.actorId}\n where ${remoteActivities.id} = ${id} and ${authors.localId} is null\n)`;\n\nconst remoteObject = (id: SQLWrapper): SQL => sql`exists (\n select 1 from ${objects} ${remoteObjects}\n join ${actors} ${authors} on ${authors.id} = ${remoteObjects.actorId}\n where ${remoteObjects.id} = ${id} and ${authors.localId} is null\n)`;\n\nconst addressedPublicly = (id: SQLWrapper): SQL => sql`exists (\n select 1 from ${addressing} ${entries}\n join ${resources} ${targets} on ${targets.id} = ${entries.targetId}\n where ${entries.sourceId} = ${id} and ${inArray(targets.iri, PUBLIC_IRIS)}\n)`;\n\n// Whether an instance the viewer may read received the activity, by one of\n// its deliveries the mark says carried what is opened.\nconst received = (viewer: Viewer, id: SQLWrapper, mark: PgColumn): SQL =>\n sql`exists (\n select 1 from ${activityDeliveries} ${deliveries}\n where ${deliveries.activityId} = ${id}\n and ${deliveries.direction} = 'inbound'\n and ${mark}\n and ${viewableInstance(viewer, deliveries.instanceId)}\n )`;\n\n// True for anything but an activity of a remote actor.\nconst readableActivity = (viewer: Viewer, id: SQLWrapper): SQL =>\n sql`(not ${remoteActivity(id)} or ${addressedPublicly(id)} or ${received(viewer, id, deliveries.carriedSnapshot)})`;\n\n// True for anything but an object of a remote actor. Only the activity that\n// carried the stored version opens it, since a later one may carry another;\n// one whose activity row is gone stays closed, since a missing row proves\n// nothing of who may read it. That activity being public opens only an\n// object embedded in it, since of one fetched apart it made public no more\n// than the IRI. Receiving that activity opens it only by a delivery that\n// carried the object as stored too, since one fetched apart from the activity\n// may differ from fetch to fetch.\nconst readableObject = (viewer: Viewer, id: SQLWrapper): SQL =>\n sql`(not ${remoteObject(id)} or ${addressedPublicly(id)} or exists (\n select 1 from ${objects} ${remoteObjects}\n join ${activities} ${carriers} on ${carriers.id} = ${remoteObjects.activityId}\n where ${remoteObjects.id} = ${id}\n and (\n (not ${remoteObjects.fetched} and ${addressedPublicly(carriers.id)})\n or ${received(viewer, carriers.id, deliveries.carriedObjectSnapshot)}\n )\n ))`;\n\n/**\n * Restricts resources to those the viewer may read. Received content is an\n * inbox's, which ActivityPub filters by the requester's permission (5.2) and\n * opens without authentication only when addressed to the public (5.6):\n *\n * - An administrator reads everything.\n * - An activity of a remote actor is readable when it is addressed to the\n * public, or when one of the local instances the viewer is a member of\n * received it, i.e. an inbound delivery to it is linked to the activity\n * and carried it as stored. A delivery of the same IRI with other\n * contents stays linked but opens nothing.\n * - An object of a remote actor is readable when it is addressed to the\n * public, when the activity that carried it embedded in it is, or when\n * one of the local instances the viewer is a member of received that\n * activity and the object as stored with it. An object fetched apart\n * from the activity is opened neither by the activity being public nor\n * by a delivery but one that fetched it as stored.\n * - Everything else, including the activities and objects of local actors\n * whatever their addressing, is readable.\n *\n * Filtering rows by it before paging keeps a connection from telling of rows\n * the viewer may not read.\n * @param viewer The viewer and the database.\n * @param id The resource ID in an outer query.\n * @returns The condition on the ID.\n */\nexport function readableResource(viewer: Viewer, id: SQLWrapper): SQL {\n if (viewer.account?.admin === true) return sql`true`;\n return sql`(${readableActivity(viewer, id)} and ${readableObject(viewer, id)})`;\n}\n\n/**\n * Finds the resources among the given IDs that the viewer may not read, as\n * {@link readableResource} decides. IDs of anything but a resource are never\n * among them.\n * @returns The IDs the viewer may not read.\n */\nexport async function unreadableResources(\n viewer: Viewer,\n ids: readonly Uuid[],\n): Promise<ReadonlySet<Uuid>> {\n if (ids.length === 0 || viewer.account?.admin === true) return new Set();\n const rows = await viewer.db\n .select({ id: resources.id })\n .from(resources)\n .where(\n and(\n inArray(resources.id, [...ids]),\n not(readableResource(viewer, resources.id)),\n ),\n );\n return new Set(rows.map(({ id }) => id));\n}\n\n/**\n * Determines whether the viewer may read the resource.\n * @returns Whether {@link readableResource} holds for it.\n */\nexport const isReadableResource = async (\n viewer: Viewer,\n id: Uuid,\n): Promise<boolean> => !(await unreadableResources(viewer, [id])).has(id);\n\nconst nodeIdOf = (node: unknown): Uuid | null =>\n node != null &&\n typeof node === \"object\" &&\n \"id\" in node &&\n validateUuid(node.id)\n ? node.id\n : null;\n\n/**\n * Replaces the Relay nodes the viewer may not read by null, as if they did\n * not exist. Activities, objects, and resources share their IDs, so a node's\n * ID alone tells whether it is one the viewer may not read.\n * @returns The nodes, in the same order.\n */\nexport async function hideUnreadableNodes(\n viewer: Viewer,\n nodes: readonly unknown[],\n): Promise<unknown[]> {\n const hidden = await unreadableResources(\n viewer,\n nodes.map(nodeIdOf).filter((id) => id != null),\n );\n return nodes.map((node) => {\n const id = nodeIdOf(node);\n return id != null && hidden.has(id) ? null : node;\n });\n}\n"],"mappings":";;;;;;;;;;AA8CA,MAAa,cAAiC;CAC5C;CACA;CACA;AACF;;;;;;AAeA,MAAa,mBACX,IACA,WACA,GAAG,eAEH,GACG,OAAO,EAAE,YAAY,gBAAgB,WAAW,CAAC,CAAC,CAClD,KAAK,eAAe,CAAC,CACrB,UAAU,WAAW,GAAG,gBAAgB,YAAY,UAAU,EAAE,CAAC,CAAC,CAClE,MACC,IACE,GAAG,gBAAgB,WAAW,SAAS,GACvC,UAAU,gBAAgB,QAAQ,GAClC,UAAU,UAAU,OAAO,GAC3B,GAAG,UACL,CACF;;;;;;;;;;;;AAaJ,SAAgB,iBAAiB,QAAgB,YAA2B;CAC1E,MAAM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