From b946c4b83d01cc54de73dfe17dbc7903db1aa212 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 13:23:01 +0600 Subject: [PATCH 1/6] sdk/badge: add badge definitions, awards and responses Add createBadgeDefinition, awardBadge and respondToBadgeAward at @hypercerts-org/sdk/badge. - awardBadge creates a new definition and the award in one applyWrites commit, or reuses an existing definition, and checks the signed-in account against that definition version's allowedIssuers. - respondToBadgeAward only creates a response for the award's recipient: the account it is for, or the account whose repository holds the record. - The icon is a raw blob field; its type and size are checked against the lexicon before upload. TECH-760 --- .agents/skills/hypercerts-org-sdk/SKILL.md | 11 +- .../hypercerts-org-sdk/references/badge.md | 105 +++++ .changeset/badges.md | 7 + packages/sdk/package.json | 4 + packages/sdk/src/badge/award-badge.test.ts | 396 ++++++++++++++++++ packages/sdk/src/badge/award-badge.ts | 221 ++++++++++ packages/sdk/src/badge/award-targets.ts | 112 +++++ packages/sdk/src/badge/build-definition.ts | 157 +++++++ .../src/badge/create-badge-definition.test.ts | 138 ++++++ packages/sdk/src/badge/index.ts | 15 + .../sdk/src/badge/respond-to-award.test.ts | 252 +++++++++++ packages/sdk/src/badge/respond-to-award.ts | 177 ++++++++ 12 files changed, 1591 insertions(+), 4 deletions(-) create mode 100644 .agents/skills/hypercerts-org-sdk/references/badge.md create mode 100644 .changeset/badges.md create mode 100644 packages/sdk/src/badge/award-badge.test.ts create mode 100644 packages/sdk/src/badge/award-badge.ts create mode 100644 packages/sdk/src/badge/award-targets.ts create mode 100644 packages/sdk/src/badge/build-definition.ts create mode 100644 packages/sdk/src/badge/create-badge-definition.test.ts create mode 100644 packages/sdk/src/badge/index.ts create mode 100644 packages/sdk/src/badge/respond-to-award.test.ts create mode 100644 packages/sdk/src/badge/respond-to-award.ts diff --git a/.agents/skills/hypercerts-org-sdk/SKILL.md b/.agents/skills/hypercerts-org-sdk/SKILL.md index 63c41a0..06bf912 100644 --- a/.agents/skills/hypercerts-org-sdk/SKILL.md +++ b/.agents/skills/hypercerts-org-sdk/SKILL.md @@ -3,7 +3,7 @@ name: hypercerts-org-sdk description: "Write Hypercerts and Certified records (org.hypercerts.*, app.certified.*) to a PDS from an app with @hypercerts-org/sdk: setting up the SDK context from an authenticated @atproto/lex Client, choosing the right operation and subpath, uploading blobs, and handling write errors without duplicates. Use when app code imports @hypercerts-org/sdk, or the user wants to create, link or write hypercert-related records from an app. Not for changing the SDK's own source." metadata: author: hypercerts-org - version: "5" + version: "6" --- # @hypercerts-org/sdk @@ -63,6 +63,7 @@ export const context = createSDKContext({ | `@hypercerts-org/sdk/feature` | `createFeature`, `RecordAlreadyExistsError`, the same `Write*` errors, `FeatureInput`, `CreateFeatureResult`, `LeafletDocument` | | `@hypercerts-org/sdk/organization` | `createOrganization`, `OrganizationAlreadyExistsError`, `RecordAlreadyExistsError`, the same `Write*` errors, `OrganizationInput`, `CreateOrganizationInput`, `CreateOrganizationResult`, `LeafletDocument` | | `@hypercerts-org/sdk/social` | `followAccount`, `followEntity`, `like`, `repost`, `unfollowAccount`, `unfollowEntity`, `unlike`, `unrepost`, the `Write*` errors and input types | +| `@hypercerts-org/sdk/badge` | `createBadgeDefinition`, `awardBadge`, `respondToBadgeAward`, the same `Write*` errors, input/result types | | `@hypercerts-org/sdk/blob` | `uploadBlob` | | `@hypercerts-org/sdk/collection` | `createCollection`, `createActivityInCollection`, `RecordAlreadyExistsError`, `WriteError`, `WriteRejectedError`, `WriteOutcomeUnknownError`, `WriteResultMismatchError`, input/result types | @@ -82,6 +83,7 @@ Operations are grouped by domain, each under its own subpath. Read the domain's | Collection (create a Collection with items; add a new Activity to an existing Collection) | `@hypercerts-org/sdk/collection` | [references/collection.md](references/collection.md) | | Organization (`app.certified.actor.organization`, with its profile and locations) | `@hypercerts-org/sdk/organization` | [references/organization.md](references/organization.md) | | Social (follow accounts and records, like, repost, and undo them) | `@hypercerts-org/sdk/social` | [references/social.md](references/social.md) | +| Badge (`app.certified.badge.*`: definitions, awards to an account or record, responses) | `@hypercerts-org/sdk/badge` | [references/badge.md](references/badge.md) | Things to know before opening a reference: @@ -89,6 +91,7 @@ Things to know before opening a reference: - `location: { uri }` inside a location is a link to external data; a whole location given as `{ uri }` in `createActivity` reuses an existing record. - `createOrganization` takes the name, avatar, banner and website in `profileIfMissing`, not in `organization`, and an existing location as `{ uri }`, never a bare string. - Social create functions take the **target**: `{ targetDid }` for an account, `{ targetUri }` (a full record URI) for a record. Undo functions (`unlike`, `unrepost`, `unfollowAccount`, `unfollowEntity`) take the **URI of your own like, repost or follow record** (`likeUri`, `repostUri`, `followUri`), not the target's, and return `void`. Keep the `uri` the create function returned. +- `awardBadge` takes `{ did }` or `{ uri }` as the subject and `{ uri }` or new fields as the definition; never build strong references or DID objects. `respondToBadgeAward` works only as the award's recipient. ## 5. Images and files @@ -121,7 +124,7 @@ Uploads happen before the write and are not rolled back, so a call that throws c Order of work: validate input → read `{ uri }` records → upload blobs → validate against lexicons → one write. The SDK never retries. -The three write errors are exported from `@hypercerts-org/sdk/activity`, `/actor`, `/location`, `/tag`, `/feature`, `/collection`, `/organization` and `/social` and extend `WriteError`. Every `WriteError` has `attempted`: the URI and CID of every record in the request, in request order (an undo function called without `cid` has an empty `attempted`; its message names the URI): for `createActivity` the Activity is last; for `createActivityInCollection` the Collection is last and the Activity is just before it; for `createCollection` the Collection is last, after the records it points at; for `createOrganization` the organization is last. `instanceof WriteError` catches all three. +The three write errors are exported from `@hypercerts-org/sdk/activity`, `/actor`, `/badge`, `/location`, `/tag`, `/feature`, `/collection`, `/organization` and `/social` and extend `WriteError`. Every `WriteError` has `attempted`: the URI and CID of every record in the request, in request order (an undo function called without `cid` has an empty `attempted`; its message names the URI): for `createActivity` the Activity is last; for `createActivityInCollection` the Collection is last and the Activity is just before it; for `createCollection` the Collection is last, after the records it points at; for `awardBadge` the award is last, after a new definition; for `createOrganization` the organization is last. `instanceof WriteError` catches all three. | Error | Meaning | What to do | | -------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------- | @@ -194,7 +197,7 @@ try { - `createSDKContext({ client: session })` or passing an `@atproto/api` `Agent` throws. Wrap it: `new Client(session)`. - `didResolver: oauthClient` throws. Pass `oauthClient.identityResolver`. - Passing an `uploadBlob` result as `image` throws. Pass the `Blob`/`File`. -- Retrying blindly after `WriteOutcomeUnknownError` duplicates every record under new keys. The exception is a call whose records all have a fixed key and are only created if absent: `createProfile` and `createVocabularyTag`. `createOrganization` is also safe to repeat: the organization exists at most once, so a second call creates it or throws `OrganizationAlreadyExistsError`. Undo functions are safe to repeat too. `createFeature`, `createCollection`, `createWorkScopeTag`, `followAccount`, `followEntity`, `like` and `repost` are not safe to repeat. +- Retrying blindly after `WriteOutcomeUnknownError` duplicates every record under new keys. The exception is a call whose records all have a fixed key and are only created if absent: `createProfile` and `createVocabularyTag`. `createOrganization` is also safe to repeat: the organization exists at most once, so a second call creates it or throws `OrganizationAlreadyExistsError`. Undo functions are safe to repeat too. `createFeature`, `createCollection`, `createWorkScopeTag`, `createBadgeDefinition`, `awardBadge`, `respondToBadgeAward`, `followAccount`, `followEntity`, `like` and `repost` are not safe to repeat. - An item of `createCollection` is `{ activity }`, `{ feature }`, `{ collection }` or `{ uri }`, never a bare Activity input; `{ uri }` must be an Activity, Feature or Collection. - A vocabulary tag's key is `.` exactly as you pass it. A dot in either part throws a `TypeError`; the SDK does not normalise the parts. - A work-scope tag URI is not a vocabulary tag URI: each field accepts one collection, and a `{ uri }` of another throws a `TypeError`. @@ -204,6 +207,6 @@ try { ## Verify -1. Imports come only from `@hypercerts-org/sdk`, `.../activity`, `.../actor`, `.../collection`, `.../feature`, `.../location`, `.../organization`, `.../social`, `.../tag` or `.../blob`. +1. Imports come only from `@hypercerts-org/sdk`, `.../activity`, `.../actor`, `.../badge`, `.../collection`, `.../feature`, `.../location`, `.../organization`, `.../social`, `.../tag` or `.../blob`. 2. `tsc --noEmit` passes. The input types catch wrong field names and shapes. 3. `com.atproto.repo.getRecord` on each returned `uri` returns the record, and any references it holds match the URIs and CIDs the SDK returned. diff --git a/.agents/skills/hypercerts-org-sdk/references/badge.md b/.agents/skills/hypercerts-org-sdk/references/badge.md new file mode 100644 index 0000000..924f3cd --- /dev/null +++ b/.agents/skills/hypercerts-org-sdk/references/badge.md @@ -0,0 +1,105 @@ +# Badge domain (`@hypercerts-org/sdk/badge`) + +Read [../SKILL.md](../SKILL.md) first for setup, blob uploads and error handling. Every example assumes `context` from `createSDKContext`. + +Three operations that only create records: `createBadgeDefinition` (`app.certified.badge.definition`), `awardBadge` (`app.certified.badge.award`) and `respondToBadgeAward` (`app.certified.badge.response`). There is no operation that deletes, revokes or edits a definition, award or response. + +## createBadgeDefinition + +`createBadgeDefinition(context, input)` creates one definition in your repo and returns `{ uri, cid }`. + +```ts +import { createBadgeDefinition } from "@hypercerts-org/sdk/badge"; + +const definition = await createBadgeDefinition(context, { + title: "Verified steward", + badgeType: "verification", // free text; values outside the lexicon's known set are fine + description: "Confirmed to manage the land they report on.", + icon: iconFile, // a PNG, JPEG, WebP or SVG File/Blob of at most 1 MiB, from your app, uploaded for you + allowedIssuers: ["did:plc:abc123"], // plain DIDs; the SDK stores them as DID objects +}); +``` + +- `allowedIssuers`: omitted means **anyone** may award the badge; `[]` means **no one** may. You do not have to be on the list to create the definition, only to award it. +- `icon` is a `Blob`/`File`, not a URL and not an `uploadBlob` result. A type or size the lexicon refuses throws `TypeError` before anything is uploaded. +- Nothing is deduplicated: two calls create two definitions. + +## awardBadge + +`awardBadge(context, { definition, subject, note?, url?, validFrom?, validUntil?, createdAt? })` creates an award in your repo and returns `{ award, definition }`. + +`definition` is either the fields of a **new** definition (created in the same commit) or `{ uri }` of an **existing** one (read, never rewritten): + +```ts +import { awardBadge } from "@hypercerts-org/sdk/badge"; + +// An existing badge, awarded to an account. +const { award, definition } = await awardBadge(context, { + definition: { uri: "at://did:plc:abc123/app.certified.badge.definition/3k2a4b5c6d7e8" }, + subject: { did: "did:plc:xyz789" }, + note: "Completed the stewardship course.", + validUntil: "2027-06-01T00:00:00.000Z", +}); +definition.created; // false + +// A new badge awarded to a record (any type, any account's repository), one atomic commit. +await awardBadge(context, { + definition: { title: "Field verified", badgeType: "verification" }, + subject: { uri: "at://did:plc:xyz789/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }, +}); +``` + +- `subject` is `{ did }` (an account) or `{ uri }` (a record, identified by a DID, not a handle). You never build a strong reference or DID object: the SDK reads the record and pins its current CID. +- The award pins the definition by the CID it read. The signed-in account must be in **that version's** `allowedIssuers` (omitted: anyone, `[]`: no one), otherwise `Error` and nothing is written or uploaded. +- `validFrom` defaults to `createdAt` (which defaults to the time of the call). A `validUntil` earlier than `validFrom`, or than `createdAt` when `validFrom` is omitted, throws `TypeError`. Timestamps are stored as given. `validUntil` marks the award expired; it is not revocation. +- Awarding does not accept the badge for the recipient; they use `respondToBadgeAward`. +- The new definition and the award are one `applyWrites` commit: both exist afterwards, or neither does. +- `WriteOutcomeUnknownError.attempted` lists the new definition (if any) first, then the award. Do not call again blindly: it would create a second award. Check the URIs with `com.atproto.repo.getRecord` first. +- Nothing is deduplicated: awarding the same badge to the same subject twice creates two awards. + +## respondToBadgeAward + +`respondToBadgeAward(context, { awardUri, response, weight?, createdAt? })` creates a response in **your** repo and returns `{ uri, cid }`. You must be the award's recipient. + +```ts +import { respondToBadgeAward } from "@hypercerts-org/sdk/badge"; + +await respondToBadgeAward(context, { + awardUri: "at://did:plc:issuer/app.certified.badge.award/3k2a4b5c6d7e8", + response: "accepted", + weight: "2", +}); +// `awardUri` is the URI of the award, from the issuer or your app. +await respondToBadgeAward(context, { awardUri, response: "rejected" }); // no weight here +``` + +- The recipient of an award to an account is that account. For an award to a record it is the account whose repository holds the record (the SDK's rule; the lexicon does not say). Any other signed-in account, the issuer included, gets an `Error` and nothing is written. +- `weight` only goes with `"accepted"`; with `"rejected"` it throws `TypeError`. It must be a positive decimal number written as a string and is stored exactly as written (`"007.50"` stays `"007.50"`). +- Nothing is deduplicated or overwritten: every call creates a response under a new key. Responding twice leaves two responses. Do not repeat after `WriteOutcomeUnknownError` without checking `attempted`. + +## Uploads are outside the commit + +A new definition's `icon` is uploaded before the write. Invalid input, a refused issuer and an unreadable subject or definition fail before any upload; a rule of the award's or the new definition's lexicon (for example a `note` over 500 characters) is only found after it. If the write or such a rule fails, the blob stays unreferenced (a PDS usually deletes it later, not guaranteed). + +## Input fields + +`BadgeDefinitionInput` (also `definition` of `awardBadge` when new): + +| Field | Type | Notes | +| ---------------- | -------------------- | ---------------------------------------------------------------------- | +| `title` | `string` | Required. At most 256 characters. | +| `badgeType` | `string` | Required. At most 100 characters. Any value is accepted. | +| `description` | `string` | At most 500 graphemes. | +| `icon` | `Blob` / `File` | PNG, JPEG, WebP or SVG, at most 1 MiB. Uploaded by the SDK. | +| `allowedIssuers` | `string[]` (DIDs) | At most 100. Omitted: anyone. `[]`: no one. | +| `createdAt` | ISO 8601 `string` | Defaults to the time of the call. | + +`AwardBadgeInput`: `definition` (`BadgeDefinitionInput` or `{ uri }`), `subject` (`{ did }` or `{ uri }`), `note` (at most 500 characters), `url`, `validFrom`, `validUntil`, `createdAt`. + +`RespondToBadgeAwardInput`: `awardUri`, `response` (`"accepted"` or `"rejected"`), `weight` (accepted only, at most 50 characters), `createdAt`. + +## Pitfalls + +- `definition: { uri, title }` (a mix of an existing URI and new fields) throws `TypeError`. Pass one or the other. +- A definition `{ uri }` must be an `app.certified.badge.definition`; another type of record throws `TypeError`. +- An empty `allowedIssuers` is not "no restriction": it makes the badge impossible to award. diff --git a/.changeset/badges.md b/.changeset/badges.md new file mode 100644 index 0000000..a2e57f1 --- /dev/null +++ b/.changeset/badges.md @@ -0,0 +1,7 @@ +--- +"@hypercerts-org/sdk": minor +--- + +- Add `createBadgeDefinition`, `awardBadge` and `respondToBadgeAward` at `@hypercerts-org/sdk/badge`. +- `awardBadge` creates a new definition and the award in one `applyWrites` commit, or reuses an existing definition, and checks the signed-in account against its `allowedIssuers`. +- `respondToBadgeAward` only creates a response for the award's recipient: the account it is for, or the account whose repository holds the record it is for. diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 332374b..8b85bb1 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -23,6 +23,10 @@ "types": "./dist/actor/index.d.ts", "default": "./dist/actor/index.js" }, + "./badge": { + "types": "./dist/badge/index.d.ts", + "default": "./dist/badge/index.js" + }, "./blob": { "types": "./dist/blob/index.d.ts", "default": "./dist/blob/index.js" diff --git a/packages/sdk/src/badge/award-badge.test.ts b/packages/sdk/src/badge/award-badge.test.ts new file mode 100644 index 0000000..61640b3 --- /dev/null +++ b/packages/sdk/src/badge/award-badge.test.ts @@ -0,0 +1,396 @@ +import { type LexMap, lexParse } from "@atproto/lex"; +import { cidForLex } from "@atproto/lex-cbor"; +import { describe, expect, it } from "vitest"; +import { CID, DID, json } from "../test-utils/fake-pds.js"; +import { fakeRepo, methods, refTo, writeOf } from "../test-utils/fake-repo.js"; +import { type AwardBadgeInput, awardBadge, WriteOutcomeUnknownError } from "./index.js"; + +const DEFINITION = "app.certified.badge.definition"; +const AWARD = "app.certified.badge.award"; +const ACTIVITY = "org.hypercerts.claim.activity"; +const OTHER = "did:plc:other222"; + +const definitionUri = `at://${DID}/${DEFINITION}/3k2a4b5c6d7e8`; +const subjectRecordUri = `at://${DID}/${ACTIVITY}/3k2a4b5c6d7e8`; +const newDefinition = { title: "Field verified", badgeType: "verification" }; +const stored = (extra: LexMap = {}): LexMap => ({ + $type: DEFINITION, + title: "Verified steward", + badgeType: "verification", + createdAt: "2024-01-01T00:00:00.000Z", + ...extra, +}); +// The CID the fake PDS reports for a stored record, as a PDS computes it from the stored value. +const cidOf = async (value: LexMap) => + (await cidForLex(lexParse(JSON.stringify(value)))).toString(); +const png = () => new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" }); + +const award = (input: Partial = {}): AwardBadgeInput => ({ + definition: { uri: definitionUri }, + subject: { did: OTHER }, + ...input, +}); + +describe("awardBadge", () => { + it("creates a new definition and the award in one request, the award pinning the definition's CID", async () => { + const { context, requests, creates, updates } = fakeRepo(); + + const result = await awardBadge( + context, + award({ definition: { ...newDefinition, icon: png() }, note: "Visited the site." }), + ); + + expect(methods(requests)).toEqual([ + "com.atproto.repo.uploadBlob", + "com.atproto.repo.applyWrites", + ]); + // One commit, the definition first. + expect(creates).toHaveLength(1); + expect((creates[0] ?? []).map((write) => write.collection)).toEqual([DEFINITION, AWARD]); + expect(updates[0]).toEqual([]); + const created = writeOf(creates[0] ?? [], DEFINITION); + const awarded = writeOf(creates[0] ?? [], AWARD); + expect(created.value).toMatchObject({ ...newDefinition, icon: { mimeType: "image/png" } }); + expect(awarded.value).toMatchObject({ + badge: refTo(created), + subject: { $type: "app.certified.defs#did", did: OTHER }, + note: "Visited the site.", + }); + expect(awarded.value).not.toHaveProperty("validFrom"); + expect(awarded.value).not.toHaveProperty("validUntil"); + expect(result).toEqual({ + award: refTo(awarded), + definition: { ...refTo(created), created: true }, + }); + }); + + it("reuses an existing definition as it is, pinning the version that was read", async () => { + const definition = stored({ allowedIssuers: [{ did: DID }] }); + const { context, requests, creates, updates } = fakeRepo({ + records: { [definitionUri]: definition }, + }); + + const result = await awardBadge(context, award()); + + expect(methods(requests)).toEqual([ + "com.atproto.repo.getRecord", + "com.atproto.repo.applyWrites", + ]); + // Only the award is written; the definition is neither created nor rewritten. + expect((creates[0] ?? []).map((write) => write.collection)).toEqual([AWARD]); + expect(updates[0]).toEqual([]); + const cid = await cidOf(definition); + expect(writeOf(creates[0] ?? [], AWARD).value.badge).toEqual({ uri: definitionUri, cid }); + expect(result.definition).toEqual({ uri: definitionUri, cid, created: false }); + }); + + it("awards a record of any type with a strong reference to the version that was read", async () => { + const { context, creates } = fakeRepo({ + existing: { [subjectRecordUri]: CID }, + records: { [definitionUri]: stored() }, + }); + + await awardBadge(context, award({ subject: { uri: subjectRecordUri } })); + + expect(writeOf(creates[0] ?? [], AWARD).value.subject).toEqual({ + $type: "com.atproto.repo.strongRef", + uri: subjectRecordUri, + cid: CID, + }); + }); + + it("keeps the validity timestamps as written", async () => { + const { context, creates } = fakeRepo({ records: { [definitionUri]: stored() } }); + + await awardBadge( + context, + award({ + validFrom: "2019-06-01T00:00:00.000Z", + validUntil: "2030-01-01T00:00:00.000Z", + createdAt: "2024-05-05T12:00:00.000Z", + url: "https://example.org/certificate", + }), + ); + + expect(writeOf(creates[0] ?? [], AWARD).value).toMatchObject({ + validFrom: "2019-06-01T00:00:00.000Z", + validUntil: "2030-01-01T00:00:00.000Z", + createdAt: "2024-05-05T12:00:00.000Z", + url: "https://example.org/certificate", + }); + }); +}); + +describe("awardBadge validity", () => { + it.each([ + [ + "ends at the start", + { validFrom: "2024-01-01T00:00:00.000Z", validUntil: "2024-01-01T00:00:00.000Z" }, + ], + [ + "ends before createdAt but after an earlier validFrom", + { + validFrom: "2019-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + validUntil: "2020-01-01T00:00:00.000Z", + }, + ], + ])("accepts an award that %s", async (_, validity) => { + const { context, creates } = fakeRepo({ records: { [definitionUri]: stored() } }); + + await awardBadge(context, award(validity)); + + expect(creates).toHaveLength(1); + }); + + it.each([ + [ + "validUntil before validFrom", + { validFrom: "2025-01-01T00:00:00.000Z", validUntil: "2024-01-01T00:00:00.000Z" }, + /validUntil \(2024-01-01T00:00:00.000Z\) is earlier than validFrom \(2025-01-01T00:00:00.000Z\)/, + ], + [ + "validUntil before createdAt, without validFrom", + { createdAt: "2024-05-01T00:00:00.000Z", validUntil: "2024-04-01T00:00:00.000Z" }, + /earlier than createdAt \(2024-05-01T00:00:00.000Z\), which is when the badge starts/, + ], + [ + "validUntil between createdAt and a later validFrom", + { + createdAt: "2024-01-01T00:00:00.000Z", + validFrom: "2030-01-01T00:00:00.000Z", + validUntil: "2026-01-01T00:00:00.000Z", + }, + /earlier than validFrom/, + ], + [ + "validUntil in the past, with createdAt defaulting to now", + { validUntil: "2000-01-01T00:00:00.000Z" }, + /createdAt defaults to the time of the call/, + ], + ])("sends nothing for %s", async (_, validity, message) => { + const { context, requests } = fakeRepo({ records: { [definitionUri]: stored() } }); + + const error = await awardBadge(context, award(validity)).catch((e) => e); + + expect(error).toBeInstanceOf(TypeError); + expect(error.message).toMatch(message); + expect(requests).toHaveLength(0); + }); +}); + +describe("awardBadge issuers", () => { + const listing = (allowedIssuers?: string[]) => + stored( + allowedIssuers === undefined + ? {} + : { allowedIssuers: allowedIssuers.map((did) => ({ did })) }, + ); + + it.each([ + ["no list", undefined], + ["a list with the signed-in account", [DID]], + ["a list with the signed-in account among others", [OTHER, DID]], + ])("lets the signed-in account award an existing definition with %s", async (_, issuers) => { + const { context, creates } = fakeRepo({ records: { [definitionUri]: listing(issuers) } }); + + await awardBadge(context, award()); + + expect(creates).toHaveLength(1); + }); + + it.each([ + ["a list without the signed-in account", [OTHER], /lets only did:plc:other222 award it/], + ["an empty list", [], /lists no allowed issuers, so no one can award it/], + ])("refuses an existing definition with %s, writing nothing", async (_, issuers, message) => { + const { context, requests } = fakeRepo({ records: { [definitionUri]: listing(issuers) } }); + + const error = await awardBadge(context, award()).catch((e) => e); + + expect(error.message).toMatch(message); + expect(error.message).toMatch(/signed in as did:plc:testowner123.*No record was written/); + expect(methods(requests)).not.toContain("com.atproto.repo.applyWrites"); + }); + + it.each([ + [ + "a list without the signed-in account", + { allowedIssuers: [OTHER] }, + /lets only did:plc:other222/, + ], + ["an empty list", { allowedIssuers: [] }, /lists no allowed issuers/], + ])( + "refuses a new definition with %s before reading or uploading anything", + async (_, extra, message) => { + const { context, requests } = fakeRepo(); + + const error = await awardBadge( + context, + award({ definition: { ...newDefinition, ...extra, icon: png() } }), + ).catch((e) => e); + + expect(error.message).toMatch(/the new badge definition/); + expect(error.message).toMatch(message); + expect(requests).toHaveLength(0); + }, + ); + + it("lets the signed-in account award a new definition that lists them", async () => { + const { context, creates } = fakeRepo(); + + await awardBadge(context, award({ definition: { ...newDefinition, allowedIssuers: [DID] } })); + + expect(writeOf(creates[0] ?? [], DEFINITION).value.allowedIssuers).toEqual([ + { $type: "app.certified.defs#did", did: DID }, + ]); + }); +}); + +describe("awardBadge input and references", () => { + it.each<[string, Partial | Record, RegExp]>([ + [ + "a subject that is neither", + { subject: { name: "Alice" } }, + /subject must be \{ did \} for an account or \{ uri \} for a record/, + ], + [ + "a subject with both", + { subject: { did: OTHER, uri: subjectRecordUri } }, + /subject.*has a field the SDK does not know/, + ], + ["a subject DID that is not one", { subject: { did: "alice.test" } }, /invalid subject: .*did/], + [ + "a subject that is a handle URI", + { subject: { uri: `at://alice.test/${ACTIVITY}/3k2a4b5c6d7e8` } }, + /not a record URI/, + ], + [ + "a subject URI without a record key", + { subject: { uri: `at://${DID}/${ACTIVITY}` } }, + /not a record URI/, + ], + [ + "a definition that mixes { uri } with fields", + { definition: { uri: definitionUri, title: "Other" } as never }, + /definition combines `uri` with other fields/, + ], + [ + "a definition URI of another type of record", + { definition: { uri: subjectRecordUri } }, + /definition points at a record of type org.hypercerts.claim.activity, but this field holds app.certified.badge.definition/, + ], + [ + "a definition URI with a handle", + { definition: { uri: `at://alice.test/${DEFINITION}/3k2a4b5c6d7e8` } }, + /not a record URI/, + ], + [ + "a new definition without a title", + { definition: { badgeType: "verification" } as never }, + /invalid definition: .*title/, + ], + ["an unknown field", { colour: "red" }, /has a field the SDK does not know/], + [ + "a note over 500 characters", + { note: "x".repeat(501) }, + /the award is not a valid app.certified.badge.award/, + ], + ])("sends nothing for %s", async (_, bad, message) => { + const { context, requests } = fakeRepo({ records: { [definitionUri]: stored() } }); + + const error = await awardBadge(context, { ...award(), ...bad } as AwardBadgeInput).catch( + (e) => e, + ); + + expect(error).toBeInstanceOf(TypeError); + expect(error.message).toMatch(message); + expect(methods(requests)).not.toContain("com.atproto.repo.applyWrites"); + expect(methods(requests)).not.toContain("com.atproto.repo.uploadBlob"); + }); + + it.each<[string, Parameters[0], Partial, RegExp]>([ + [ + "an existing definition that does not exist", + {}, + {}, + /cannot resolve .*the record was not found/, + ], + [ + "an existing definition that is not valid", + { records: { [definitionUri]: { $type: DEFINITION, title: "No type" } } }, + {}, + /is not a valid app.certified.badge.definition record.*cannot be awarded/, + ], + [ + "a subject record that does not exist", + { records: { [definitionUri]: stored() } }, + { subject: { uri: subjectRecordUri } }, + /cannot resolve .*the record was not found/, + ], + ])("does not write for %s", async (_, options, input, message) => { + const { context, requests } = fakeRepo(options); + + await expect(awardBadge(context, award(input))).rejects.toThrow(message); + + expect(methods(requests)).not.toContain("com.atproto.repo.applyWrites"); + }); + + it("does not upload a new definition's icon when the subject cannot be read", async () => { + const { context, requests } = fakeRepo(); + + await expect( + awardBadge( + context, + award({ + definition: { ...newDefinition, icon: png() }, + subject: { uri: subjectRecordUri }, + }), + ), + ).rejects.toThrow(/cannot resolve/); + + expect(methods(requests)).not.toContain("com.atproto.repo.uploadBlob"); + }); + + it("does not write when the new definition's icon is refused or its upload fails", async () => { + const refused = fakeRepo(); + const failing = fakeRepo({ uploadBlob: () => json(500, { error: "InternalServerError" }) }); + + await expect( + awardBadge( + refused.context, + award({ definition: { ...newDefinition, icon: new Blob(["x"], { type: "image/gif" }) } }), + ), + ).rejects.toThrow(/definition\.icon cannot be used as a badge icon/); + await expect( + awardBadge(failing.context, award({ definition: { ...newDefinition, icon: png() } })), + ).rejects.toThrow(/could not upload definition\.icon/); + + expect(methods(refused.requests)).not.toContain("com.atproto.repo.uploadBlob"); + expect(methods(failing.requests)).not.toContain("com.atproto.repo.applyWrites"); + }); +}); + +describe("awardBadge when the write fails", () => { + it("lists the new definition and the award when the outcome is unknown, and does not retry", async () => { + const { context, requests } = fakeRepo({ applyWrites: () => json(500, {}) }); + + const error = await awardBadge(context, award({ definition: newDefinition })).catch((e) => e); + + expect(error).toBeInstanceOf(WriteOutcomeUnknownError); + const [definition, awarded] = error.attempted.map((ref: { uri: string }) => ref.uri); + expect(definition).toMatch(new RegExp(`/${DEFINITION}/`)); + expect(awarded).toMatch(new RegExp(`/${AWARD}/`)); + for (const uri of [definition, awarded]) expect(error.message).toContain(uri); + expect(methods(requests).filter((method) => method.endsWith("applyWrites"))).toHaveLength(1); + }); + + it("creates a second award when called again with the same input", async () => { + const { context, creates } = fakeRepo({ records: { [definitionUri]: stored() } }); + + const first = await awardBadge(context, award()); + const second = await awardBadge(context, award()); + + expect(first.award.uri).not.toBe(second.award.uri); + expect(creates).toHaveLength(2); + }); +}); diff --git a/packages/sdk/src/badge/award-badge.ts b/packages/sdk/src/badge/award-badge.ts new file mode 100644 index 0000000..f76f5cf --- /dev/null +++ b/packages/sdk/src/badge/award-badge.ts @@ -0,0 +1,221 @@ +import { type DatetimeString, l, type UriString } from "@atproto/lex"; +import * as award from "@hypercerts-org/lexicon/app/certified/badge/award"; +import type { SDKContext } from "../context.js"; +import { + type BuildContext, + createBuildContext, + parseInput, + prepareChecked, +} from "../internal/build-context.js"; +import { compact, endsBeforeStart, optionalText, strictObject } from "../internal/input.js"; +import type { StrongRef } from "../internal/resolve-record-ref.js"; +import type { ExistingRecord, SupportingRecordRef } from "../internal/slots.js"; +import { submitWrites } from "../internal/submit-writes.js"; +import { + parseSubject, + planDefinition, + resolveDefinition, + resolveSubject, +} from "./award-targets.js"; +import type { BadgeDefinitionInput } from "./build-definition.js"; + +const OPERATION = "awardBadge"; + +/** What a badge is awarded to: an account, or any record. */ +export type AwardSubject = + | { + /** The DID of the account. */ + did: string; + } + | { + /** + * The record, as `at:////`, identified by a DID, not a handle. It may + * be of any type and in any account's repository if it is public. + */ + uri: string; + }; + +/** The input of {@link awardBadge}. */ +export interface AwardBadgeInput { + /** + * The badge to award: the data of a new definition, which is created in the same commit, or + * `{ uri }` of an existing `app.certified.badge.definition`, which is read and reused as it is. + * See {@link BadgeDefinitionInput}. + */ + definition: BadgeDefinitionInput | ExistingRecord; + /** What the badge is awarded to: `{ did }` for an account, `{ uri }` for a record. */ + subject: AwardSubject; + /** Why the badge is awarded. At most 500 characters. */ + note?: string | undefined; + /** A URL the award links to. */ + url?: string | undefined; + /** + * An ISO 8601 date-time: when the badge starts to apply, which may differ from when the award is + * written. Left out: it applies from `createdAt`. + */ + validFrom?: string | undefined; + /** + * An ISO 8601 date-time, not before `validFrom` (or `createdAt` when `validFrom` is left out): + * when the badge stops applying. Left out: no end. After it the award is expired, not revoked. + */ + validUntil?: string | undefined; + /** An ISO 8601 date-time. Defaults to the time of the call. */ + createdAt?: string | undefined; +} + +/** The result of {@link awardBadge}. */ +export interface AwardBadgeResult { + /** The new award's URI and CID. */ + award: StrongRef; + /** + * The badge definition the award references, with the CID of the version that was checked. + * `created` is `true` when this call created it, `false` when it reused an existing one. + */ + definition: SupportingRecordRef; +} + +const awardInput = strictObject({ + definition: l.unknown(), + subject: l.unknown(), + note: optionalText, + url: optionalText, + validFrom: optionalText, + validUntil: optionalText, + createdAt: optionalText, +}); + +// The effective start is the one the lexicon documents: `validFrom`, else `createdAt` (which, left +// out, is the time of the call). A date that does not parse is not judged here: the lexicon +// rejects it when the award is validated. +function assertValidityRange( + build: BuildContext, + { validFrom, validUntil, createdAt }: l.InferOutput, +): void { + const start = validFrom ?? createdAt ?? build.createdAt; + if (!endsBeforeStart({ startDate: start, endDate: validUntil })) return; + const startsAt = + validFrom === undefined + ? `createdAt (${start}), which is when the badge starts to apply because validFrom is left out${createdAt === undefined ? " and createdAt defaults to the time of the call" : ""}` + : `validFrom (${start})`; + throw new TypeError( + `${build.operation}: validUntil (${validUntil}) is earlier than ${startsAt}, so the badge would end before it starts. Nothing was written.`, + ); +} + +/** + * Awards a badge (`app.certified.badge.award`) to an account or a record, creating the badge's + * definition in the same commit when it is new. + * + * @remarks + * `definition` is either the data of a new definition (see {@link createBadgeDefinition}) or + * `{ uri }` of an existing one. A new definition and the award go into a single + * `com.atproto.repo.applyWrites` request, which the PDS commits as a whole: both exist afterwards, + * or neither does. An existing definition is read and reused as it is; the award pins the version + * that was read by its CID. + * + * `subject` is `{ did }` for an account, stored as the lexicon's DID object, or `{ uri }` for any + * record, of any type and in any account's repository, stored as a strong reference to the record + * as it is now. The record is read, never changed. + * + * Who may award: the signed-in account's DID must be in the definition's `allowedIssuers`. Left out, + * anyone may award the badge; an empty array means no one may. The check is made against the + * definition version the award references, so a later change of the list does not affect an award + * that was already made. It is made by the SDK from what it read, not by the PDS. A refused award + * writes nothing and uploads nothing. + * + * `createdAt` defaults to the time of the call and `validFrom` to `createdAt`. A `validUntil` earlier + * than `validFrom` (or, without `validFrom`, than `createdAt`) is refused. `validUntil` marks the + * award as expired from then on; it does not revoke anything, and the SDK has no operation that + * revokes or changes an award. The recipient accepts or rejects the award with + * {@link respondToBadgeAward}; awarding does not do it for them. + * + * Nothing is deduplicated: awarding the same badge to the same subject twice creates two awards. + * The order is: validate the input, read the subject record, read an existing definition or upload + * a new definition's icon, validate the records against their lexicons, write. Invalid input, a + * refused issuer and an unreadable subject or definition stop before any upload. A rule of the + * award's or the new definition's lexicon (for example a `note` over 500 characters) is only found + * after the icon is uploaded. If the PDS rejects the write, or a lexicon rule does, the uploaded icon + * stays unreferenced; see {@link createBadgeDefinition}. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated; the award, and a new definition, are created in that account's repo. + * @param input - The badge, the subject and the optional note, link and validity. See + * {@link AwardBadgeInput}. + * @returns The award's URI and CID, and the definition's, with whether this call created it. See + * {@link AwardBadgeResult}. + * @throws {@link TypeError} If `input` has an unknown field; `subject` is neither `{ did }` nor + * `{ uri }` of a record; `definition` mixes `{ uri }` with other fields, points at another type of + * record, or is invalid as a new definition; `validUntil` is before its start; or a value is not + * allowed by the lexicons. Nothing was written. An icon may already have been uploaded when a + * lexicon rule rejects the award or the new definition. + * @throws {@link Error} If the client is not authenticated; the signed-in account is not allowed to + * award the badge; the subject or the existing definition cannot be read, or the definition is not a + * valid `app.certified.badge.definition`; or the icon upload fails. Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the award + * and a new definition may or may not exist. It lists their URIs, the definition first. The SDK does + * not retry, because a retry would create a second award if the first attempt had succeeded. Check + * the URIs, then decide. + * @throws {@link WriteResultMismatchError} If the PDS reported different URIs or CIDs than the SDK + * computed, so the award's reference to the definition may not match what is stored. + * + * @example Awarding an existing badge to an account + * ```ts + * import { awardBadge } from "@hypercerts-org/sdk/badge"; + * + * // `context` comes from createSDKContext. + * const { award, definition } = await awardBadge(context, { + * definition: { uri: "at://did:plc:abc123/app.certified.badge.definition/3k2a4b5c6d7e8" }, + * subject: { did: "did:plc:xyz789" }, + * note: "Completed the stewardship course.", + * validUntil: "2027-06-01T00:00:00.000Z", + * }); + * console.log(award.uri, definition.created); // definition.created is false + * ``` + * + * @example Defining a new badge and awarding it to a record in one commit + * ```ts + * import { awardBadge } from "@hypercerts-org/sdk/badge"; + * + * const { award, definition } = await awardBadge(context, { + * definition: { title: "Field verified", badgeType: "verification" }, // created too + * subject: { uri: "at://did:plc:xyz789/org.hypercerts.claim.activity/3k2a4b5c6d7e8" }, + * }); + * console.log(definition.created, award.uri); // true + * ``` + */ +export async function awardBadge( + context: SDKContext, + input: AwardBadgeInput, +): Promise { + const build = createBuildContext(context, OPERATION); + const parsed = parseInput(build, "input", awardInput, input); + assertValidityRange(build, parsed); + const subject = parseSubject(build, parsed.subject); + const plan = planDefinition(build, parsed.definition); + + // The subject is read before the definition's icon is uploaded, so an unreadable subject fails first. + const subjectValue = await resolveSubject(build, subject); + const badge = await resolveDefinition(build, plan); + const record = await prepareChecked( + build, + "the award", + award.main, + compact({ + badge: badge.ref, + subject: subjectValue, + note: parsed.note, + url: parsed.url as UriString | undefined, + validFrom: parsed.validFrom as DatetimeString | undefined, + validUntil: parsed.validUntil as DatetimeString | undefined, + createdAt: (parsed.createdAt ?? build.createdAt) as DatetimeString, + }), + ); + + const writes = badge.created === undefined ? [record] : [badge.created, record]; + await submitWrites(context, build.did, writes, OPERATION); + return { + award: record.ref, + definition: { ...badge.ref, created: badge.created !== undefined }, + }; +} diff --git a/packages/sdk/src/badge/award-targets.ts b/packages/sdk/src/badge/award-targets.ts new file mode 100644 index 0000000..27cef48 --- /dev/null +++ b/packages/sdk/src/badge/award-targets.ts @@ -0,0 +1,112 @@ +import { type DidString, l } from "@atproto/lex"; +import * as definition from "@hypercerts-org/lexicon/app/certified/badge/definition"; +import * as certifiedDefs from "@hypercerts-org/lexicon/app/certified/defs"; +import * as strongRef from "@hypercerts-org/lexicon/com/atproto/repo/strongRef"; +import { type BuildContext, parseInput } from "../internal/build-context.js"; +import { describeError, describeValue } from "../internal/describe.js"; +import { strictObject } from "../internal/input.js"; +import type { PreparedRecord } from "../internal/prepare-record.js"; +import { buildRecord } from "../internal/record-kind.js"; +import { parseRecordUri, readRecord, type StrongRef } from "../internal/resolve-record-ref.js"; +import { isInputObject, toSlot } from "../internal/slots.js"; +import { type BadgeDefinitionInput, badgeDefinitionKind } from "./build-definition.js"; + +// What an award points at: the subject it is for and the badge definition it uses. + +export type DefinitionPlan = + | { kind: "existing"; uri: string } + | { kind: "new"; input: BadgeDefinitionInput }; + +// Reads the caller's choice and, for a new definition, checks the signed-in account against its +// issuers, so a denied award fails before anything is read or uploaded. +export function planDefinition(build: BuildContext, value: unknown): DefinitionPlan { + // `toSlot` reads the choice as every other operation does: `{ uri }` reuses an existing record, a + // record's fields create one. It rejects a mix of both and a URI of another type of record. + const { choice } = toSlot(build, "definition", value, badgeDefinitionKind, false); + if (choice.kind === "existing") { + parseRecordUri(choice.uri, build.operation); + return { kind: "existing", uri: choice.uri }; + } + const input = parseInput(build, "definition", badgeDefinitionKind.input, value); + assertIssuerAllowed(build, "the new badge definition", input.allowedIssuers); + return { kind: "new", input }; +} + +// An omitted list lets anyone issue the badge; an empty one lets no one. +function assertIssuerAllowed( + build: BuildContext, + which: string, + allowedIssuers: readonly string[] | undefined, +): void { + if (allowedIssuers === undefined || allowedIssuers.includes(build.did)) return; + const reason = + allowedIssuers.length === 0 + ? "lists no allowed issuers, so no one can award it" + : `lets only ${allowedIssuers.join(", ")} award it`; + throw new Error( + `${build.operation}: ${which} ${reason}, but the client is signed in as ${build.did}. No record was written. Award a badge whose definition allows this account, or leave allowedIssuers out of the definition to let anyone award it.`, + ); +} + +export interface ResolvedDefinition { + readonly ref: StrongRef; + /** The record to write with the award, when the definition is new. */ + readonly created: PreparedRecord | undefined; +} + +// An existing definition is read and checked as it is now, and the award pins that version. A new +// one is built by the same kind `createBadgeDefinition` uses, with its icon uploaded, but not written. +export async function resolveDefinition( + build: BuildContext, + plan: DefinitionPlan, +): Promise { + if (plan.kind === "new") { + const created = await buildRecord(badgeDefinitionKind, build, plan.input, "definition"); + return { ref: created.ref, created }; + } + const stored = await readRecord(build.context, plan.uri, build.operation); + const checked = definition.main.safeValidate(stored.value); + if (!checked.success) { + throw new Error( + `${build.operation}: the badge definition ${plan.uri} is not a valid ${definition.main.$type} record (${describeError(checked.reason)}), so it cannot be awarded. No record was written.`, + { cause: checked.reason }, + ); + } + assertIssuerAllowed( + build, + `the badge definition ${plan.uri}`, + checked.value.allowedIssuers?.map(({ did }) => did), + ); + return { ref: stored.ref, created: undefined }; +} + +const accountSubject = strictObject({ did: l.string({ format: "did" }) }); +const recordSubject = strictObject({ uri: l.string() }); + +export function parseSubject( + build: BuildContext, + value: unknown, +): { did: DidString } | { uri: string } { + if (isInputObject(value) && "did" in value) { + return parseInput(build, "subject", accountSubject, value); + } + if (isInputObject(value) && "uri" in value) { + const subject = parseInput(build, "subject", recordSubject, value); + parseRecordUri(subject.uri, build.operation); + return subject; + } + throw new TypeError( + `${build.operation}: subject must be { did } for an account or { uri } for a record, but received ${describeValue(value)}.`, + ); +} + +// An account is stored as the lexicon's DID object, a record as a strong reference to the version +// that was read, which pins what the award was made for. +export async function resolveSubject( + build: BuildContext, + subject: { did: DidString } | { uri: string }, +) { + if ("did" in subject) return certifiedDefs.did.build({ did: subject.did }); + const { ref } = await readRecord(build.context, subject.uri, build.operation); + return strongRef.main.build(ref); +} diff --git a/packages/sdk/src/badge/build-definition.ts b/packages/sdk/src/badge/build-definition.ts new file mode 100644 index 0000000..b1fba57 --- /dev/null +++ b/packages/sdk/src/badge/build-definition.ts @@ -0,0 +1,157 @@ +import { type DidString, l, parseCid } from "@atproto/lex"; +import * as definition from "@hypercerts-org/lexicon/app/certified/badge/definition"; +import * as certifiedDefs from "@hypercerts-org/lexicon/app/certified/defs"; +import { uploadBlob } from "../blob/upload-blob.js"; +import type { BuildContext } from "../internal/build-context.js"; +import { createStandalone, type StandaloneCreator } from "../internal/create-record.js"; +import { describeError } from "../internal/describe.js"; +import { blob, optionalText } from "../internal/input.js"; +import { type RecordKind, recordKind } from "../internal/record-kind.js"; + +/** The data of a new `app.certified.badge.definition` record. */ +export interface BadgeDefinitionInput { + /** The badge's display title. At most 256 characters. */ + title: string; + /** + * The category of the badge, for example `endorsement`, `verification`, `participation`, + * `certification`, `affiliation` or `recognition`. Any other value is accepted. At most 100 + * characters. + */ + badgeType: string; + /** A short statement of what the badge represents. At most 500 graphemes. */ + description?: string | undefined; + /** + * The badge's icon: a PNG, JPEG, WebP or SVG `Blob` or `File` of at most 1 MiB that the SDK + * uploads. A URL is not accepted: the lexicon stores only an uploaded file. + */ + icon?: Blob | undefined; + /** + * The accounts allowed to award the badge, as DIDs, at most 100. Left out: anyone may award it. + * An empty array: no one may. {@link awardBadge} checks the signed-in account against this list. + */ + allowedIssuers?: readonly string[] | undefined; + /** An ISO 8601 date-time. Defaults to the time of the call. */ + createdAt?: string | undefined; +} + +// The lexicon decides which types and sizes an icon may have, so the check runs its own schema on a +// definition that holds a blob reference built from the file's type and size, with a well-formed CID +// standing in for the one the upload will return. A Blob with no type is left to `uploadBlob`, which +// explains how to supply one. +function assertIconAllowed(build: BuildContext, field: string, file: Blob): void { + if (file.type === "") return; + const placeholder = parseCid("bafkreibm6jg3ux5qumhcn2b3flc3tyu6dmlb4xa7u5bf44yegnrjhc4yeq", { + flavor: "raw", + }); + const result = definition.main.safeValidate({ + $type: definition.main.$type, + title: "icon check", + badgeType: "icon check", + createdAt: build.createdAt, + icon: { $type: "blob", ref: placeholder, mimeType: file.type, size: file.size }, + }); + if (!result.success) { + throw new TypeError( + `${build.operation}: ${field} cannot be used as a badge icon (${file.type}, ${file.size} bytes): ${result.message}. Nothing was uploaded.`, + { cause: result }, + ); + } +} + +// `icon` is a blob field of the definition itself, not a wrapper object like the images of the +// other records, so the shared media helper does not apply and the reference is stored as it is. +async function uploadIcon(build: BuildContext, field: string, file: Blob) { + assertIconAllowed(build, field, file); + try { + return await uploadBlob(build.context, file); + } catch (error) { + throw new Error(`${build.operation}: could not upload ${field}: ${describeError(error)}`, { + cause: error, + }); + } +} + +export const badgeDefinitionKind: RecordKind = recordKind( + definition.main, + { + title: l.string(), + badgeType: l.string(), + description: optionalText, + icon: l.optional(blob), + allowedIssuers: l.optional(l.array(l.string({ format: "did" }))), + }, + { + icon: uploadIcon, + allowedIssuers: (_build, _field, dids: DidString[]) => + Promise.resolve(dids.map((did) => certifiedDefs.did.build({ did }))), + }, +); + +/** + * Creates a badge definition (`app.certified.badge.definition`) in the authenticated account's repo. + * + * @remarks + * A definition says what a badge is and who may award it; {@link awardBadge} then awards it to an + * account or a record. The record key is a new TID chosen by the SDK, and `createdAt` defaults to + * the time of the call. Nothing is deduplicated: calling this twice creates two definitions. + * + * `allowedIssuers` takes plain DIDs. The SDK stores them as the lexicon's DID objects and does not + * check that the accounts exist. Left out, anyone may award the badge; an empty array means no one + * may. The signed-in account does not have to be on the list to create the definition, only to + * award it. + * + * `badgeType` is free text; values outside the lexicon's known set (`endorsement`, `verification`, + * `participation`, `certification`, `affiliation`, `recognition`) are accepted. + * + * `icon` is uploaded before the record is written. The SDK checks its type and size against the + * lexicon (PNG, JPEG, WebP or SVG, at most 1 MiB) first, so a file the record would reject is not + * uploaded. The upload is not part of the write: if the write fails, the uploaded blob is left + * unreferenced. A PDS usually deletes unreferenced blobs after a while, but this is not guaranteed, + * and a blob with the same content that another record already uses stays. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated. + * @param input - The definition's data. See {@link BadgeDefinitionInput}. + * @returns The new record's URI and CID. + * @throws {@link TypeError} If `input` has an unknown field, an `allowedIssuers` entry that is not + * a DID, an `icon` that is not a PNG, JPEG, WebP or SVG of at most 1 MiB, or a value the lexicon + * does not allow (for example a `title` over 256 characters). Nothing was written. Blobs may + * already have been uploaded when a lexicon rule other than the icon's rejects the record. + * @throws {@link Error} If the client is not authenticated, or the icon upload fails. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the + * definition may or may not exist. It carries the URI to check. The SDK does not retry, because + * calling again would create a second definition if the first attempt had succeeded. + * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK + * computed. + * + * @example + * ```ts + * import { createBadgeDefinition } from "@hypercerts-org/sdk/badge"; + * + * // `context` comes from createSDKContext; `iconFile` is a File, for example from an + * // . + * const definition = await createBadgeDefinition(context, { + * title: "Verified steward", + * badgeType: "verification", + * description: "Confirmed to manage the land they report on.", + * icon: iconFile, + * allowedIssuers: ["did:plc:abc123"], + * }); + * console.log(definition.uri, definition.cid); + * ``` + * + * @example Who may award the badge + * ```ts + * import { createBadgeDefinition } from "@hypercerts-org/sdk/badge"; + * + * await createBadgeDefinition(context, { title: "Supporter", badgeType: "recognition" }); // anyone + * await createBadgeDefinition(context, { + * title: "Retired", + * badgeType: "recognition", + * allowedIssuers: [], // no one: the badge can be defined but never awarded + * }); + * ``` + */ +export const createBadgeDefinition: StandaloneCreator = (context, input) => + createStandalone(context, "createBadgeDefinition", badgeDefinitionKind, input); diff --git a/packages/sdk/src/badge/create-badge-definition.test.ts b/packages/sdk/src/badge/create-badge-definition.test.ts new file mode 100644 index 0000000..8ce4f5d --- /dev/null +++ b/packages/sdk/src/badge/create-badge-definition.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from "vitest"; +import { DID, json } from "../test-utils/fake-pds.js"; +import { fakeRepo, methods, refTo, writeOf } from "../test-utils/fake-repo.js"; +import { createBadgeDefinition, WriteOutcomeUnknownError, WriteRejectedError } from "./index.js"; + +const DEFINITION = "app.certified.badge.definition"; +const MiB = 1024 * 1024; +const ISSUER = "did:plc:issuer111"; +const OTHER = "did:plc:other222"; +const input = { title: "Verified steward", badgeType: "verification" }; +const icon = (type: string, size = 3) => new Blob([new Uint8Array(size)], { type }); + +describe("createBadgeDefinition", () => { + it("creates the definition with its issuers as DID objects and an uploaded icon, in one request", async () => { + const { context, requests, creates } = fakeRepo(); + + const ref = await createBadgeDefinition(context, { + ...input, + description: "Confirmed to manage the land they report on.", + icon: icon("image/png"), + allowedIssuers: [ISSUER, OTHER], + createdAt: "2024-05-05T12:00:00.000Z", + }); + + expect(methods(requests)).toEqual([ + "com.atproto.repo.uploadBlob", + "com.atproto.repo.applyWrites", + ]); + const write = writeOf(creates[0] ?? [], DEFINITION); + expect(write.value).toMatchObject({ + $type: DEFINITION, + title: "Verified steward", + badgeType: "verification", + description: "Confirmed to manage the land they report on.", + // A raw blob field, not a wrapper object around it. + icon: { $type: "blob", mimeType: "image/png", size: 3 }, + allowedIssuers: [ + { $type: "app.certified.defs#did", did: ISSUER }, + { $type: "app.certified.defs#did", did: OTHER }, + ], + createdAt: "2024-05-05T12:00:00.000Z", + }); + expect(ref).toEqual(refTo(write)); + }); + + it("keeps a badge type outside the lexicon's known values", async () => { + const { context, creates } = fakeRepo(); + + await createBadgeDefinition(context, { ...input, badgeType: "stewardship-circle" }); + + expect(writeOf(creates[0] ?? [], DEFINITION).value.badgeType).toBe("stewardship-circle"); + }); + + it("tells an omitted issuer list (anyone) from an empty one (no one)", async () => { + const { context, creates } = fakeRepo(); + + await createBadgeDefinition(context, input); + await createBadgeDefinition(context, { ...input, allowedIssuers: [] }); + + const [anyone, nobody] = creates.map((writes) => writeOf(writes, DEFINITION).value); + expect(anyone).not.toHaveProperty("allowedIssuers"); + expect(nobody?.allowedIssuers).toEqual([]); + }); + + it.each([ + ["image/svg+xml", 1], + ["image/png", MiB], + ])("uploads a %s icon of %d bytes", async (type, size) => { + const { context, requests } = fakeRepo(); + + await createBadgeDefinition(context, { ...input, icon: icon(type, size) }); + + expect(methods(requests)).toContain("com.atproto.repo.uploadBlob"); + }); + + it.each([ + ["a type the lexicon does not accept", icon("image/gif"), /image\/gif/], + ["a PDF", icon("application/pdf"), /application\/pdf/], + ["a file over 1 MiB", icon("image/png", MiB + 1), /blob too big \(maximum 1048576/], + ])("sends nothing for an icon that is %s", async (_, file, message) => { + const { context, requests } = fakeRepo(); + + const error = await createBadgeDefinition(context, { ...input, icon: file }).catch((e) => e); + + expect(error).toBeInstanceOf(TypeError); + expect(error.message).toMatch(/icon cannot be used as a badge icon/); + expect(error.message).toMatch(message); + expect(error.message).toMatch(/Nothing was uploaded/); + expect(requests).toHaveLength(0); + }); + + it.each([ + ["an unknown field", { ...input, colour: "red" }, /has a field the SDK does not know/], + ["a missing badge type", { title: "Verified steward" }, /badgeType/], + ["an issuer that is not a DID", { ...input, allowedIssuers: ["alice.test"] }, /allowedIssuers/], + ["an icon that is a URL", { ...input, icon: "https://example.org/i.png" }, /Blob or File/], + ["a title the lexicon rejects", { ...input, title: "x".repeat(257) }, /title/], + ])("sends nothing for %s", async (_, bad, message) => { + const { context, requests } = fakeRepo(); + + const error = await createBadgeDefinition(context, bad as never).catch((e) => e); + + expect(error).toBeInstanceOf(TypeError); + expect(error.message).toMatch(/^createBadgeDefinition: /); + expect(error.message).toMatch(message); + expect(requests).toHaveLength(0); + }); + + it("does not write when the icon upload fails", async () => { + const { context, requests } = fakeRepo({ + uploadBlob: () => json(500, { error: "InternalServerError" }), + }); + + await expect( + createBadgeDefinition(context, { ...input, icon: icon("image/png") }), + ).rejects.toThrow(/could not upload input.icon/); + + expect(methods(requests)).toEqual(["com.atproto.repo.uploadBlob"]); + }); + + it("reports a rejected write as definite and a write without an answer as unknown", async () => { + const rejecting = fakeRepo({ + applyWrites: () => json(400, { error: "InvalidRequest", message: "no" }), + }); + const silent = fakeRepo({ applyWrites: () => json(500, {}) }); + + const rejected = await createBadgeDefinition(rejecting.context, input).catch((e) => e); + const unknown = await createBadgeDefinition(silent.context, input).catch((e) => e); + + expect(rejected).toBeInstanceOf(WriteRejectedError); + expect(rejected).toMatchObject({ status: 400, code: "InvalidRequest" }); + expect(unknown).toBeInstanceOf(WriteOutcomeUnknownError); + expect(unknown.attempted).toHaveLength(1); + expect(unknown.attempted[0].uri).toMatch(new RegExp(`^at://${DID}/${DEFINITION}/`)); + // The SDK does not retry: one request each. + expect(methods(silent.requests)).toEqual(["com.atproto.repo.applyWrites"]); + }); +}); diff --git a/packages/sdk/src/badge/index.ts b/packages/sdk/src/badge/index.ts new file mode 100644 index 0000000..688fb0f --- /dev/null +++ b/packages/sdk/src/badge/index.ts @@ -0,0 +1,15 @@ +// Entry point for @hypercerts-org/sdk/badge. +export type { StrongRef } from "../internal/resolve-record-ref.js"; +export type { ExistingRecord, SupportingRecordRef } from "../internal/slots.js"; +export { + WriteError, + WriteOutcomeUnknownError, + WriteRejectedError, + WriteResultMismatchError, +} from "../internal/submit-writes.js"; +export type { AwardBadgeInput, AwardBadgeResult, AwardSubject } from "./award-badge.js"; +export { awardBadge } from "./award-badge.js"; +export type { BadgeDefinitionInput } from "./build-definition.js"; +export { createBadgeDefinition } from "./build-definition.js"; +export type { RespondToBadgeAwardInput } from "./respond-to-award.js"; +export { respondToBadgeAward } from "./respond-to-award.js"; diff --git a/packages/sdk/src/badge/respond-to-award.test.ts b/packages/sdk/src/badge/respond-to-award.test.ts new file mode 100644 index 0000000..723a874 --- /dev/null +++ b/packages/sdk/src/badge/respond-to-award.test.ts @@ -0,0 +1,252 @@ +import { type LexMap, lexParse } from "@atproto/lex"; +import { cidForLex } from "@atproto/lex-cbor"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { CID, DID, json } from "../test-utils/fake-pds.js"; +import { fakeRepo, methods, refTo, writeOf } from "../test-utils/fake-repo.js"; +import { + type RespondToBadgeAwardInput, + respondToBadgeAward, + WriteOutcomeUnknownError, + WriteRejectedError, +} from "./index.js"; + +const AWARD = "app.certified.badge.award"; +const RESPONSE = "app.certified.badge.response"; +const ACTIVITY = "org.hypercerts.claim.activity"; +// The issuer's repository is another account's, so the award is read from the PDS in its DID +// document, as it is outside tests. +const ISSUER = "did:plc:ewvi7nxzyoun6zhxrhs64oiz"; +const OTHER = "did:plc:other222"; +const awardUri = `at://${ISSUER}/${AWARD}/3k2a4b5c6d7e8`; +const ownRecordUri = `at://${DID}/${ACTIVITY}/3k2a4b5c6d7e8`; + +const forDid = (did: string) => ({ $type: "app.certified.defs#did", did }); +const forRecord = (uri: string) => ({ $type: "com.atproto.repo.strongRef", uri, cid: CID }); +const storedAward = (subject: LexMap): LexMap => ({ + $type: AWARD, + badge: { uri: `at://${ISSUER}/app.certified.badge.definition/3k2a4b5c6d7e8`, cid: CID }, + subject, + createdAt: "2024-01-01T00:00:00.000Z", +}); +const cidOf = async (value: LexMap) => + (await cidForLex(lexParse(JSON.stringify(value)))).toString(); + +// Serves the issuer's DID document and the records of its repository, and counts the reads. +function stubIssuerPds(records: Record) { + const reads: string[] = []; + vi.stubGlobal("fetch", async (input: Request | string | URL) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (url.origin === "https://plc.directory") { + return json(200, { + id: ISSUER, + service: [ + { + id: "#atproto_pds", + type: "AtprotoPersonalDataServer", + serviceEndpoint: "https://issuer-pds.test", + }, + ], + }); + } + const uri = `at://${url.searchParams.get("repo")}/${url.searchParams.get("collection")}/${url.searchParams.get("rkey")}`; + reads.push(uri); + const value = records[uri]; + return value === undefined + ? json(400, { error: "RecordNotFound", message: "not found" }) + : json(200, { uri, cid: await cidOf(value), value }); + }); + return reads; +} + +const respond = (input: Partial = {}): RespondToBadgeAwardInput => ({ + awardUri, + response: "accepted", + ...input, +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("respondToBadgeAward", () => { + it.each([ + ["an account", forDid(DID)], + ["a record in the signed-in account's repository", forRecord(ownRecordUri)], + ])( + "creates the response when the award is for %s, keeping the weight as written", + async (_, subject) => { + const award = storedAward(subject); + stubIssuerPds({ [awardUri]: award }); + const { context, requests, creates, swapCommits } = fakeRepo(); + + const ref = await respondToBadgeAward( + context, + respond({ weight: "007.50", createdAt: "2024-05-05T12:00:00.000Z" }), + ); + + // The award is read from the issuer's PDS; the signed-in account's PDS only gets the write. + expect(methods(requests)).toEqual(["com.atproto.repo.applyWrites"]); + const write = writeOf(creates[0] ?? [], RESPONSE); + expect(creates[0]).toHaveLength(1); + expect(write.value).toEqual({ + $type: RESPONSE, + badgeAward: { uri: awardUri, cid: await cidOf(award) }, + response: "accepted", + weight: "007.50", + createdAt: "2024-05-05T12:00:00.000Z", + }); + expect(swapCommits).toEqual([undefined]); + expect(ref).toEqual(refTo(write)); + }, + ); + + it("records a rejection without a weight, and a second call creates a second response", async () => { + stubIssuerPds({ [awardUri]: storedAward(forDid(DID)) }); + const { context, creates } = fakeRepo(); + + const first = await respondToBadgeAward(context, respond({ response: "rejected" })); + const second = await respondToBadgeAward(context, respond({ response: "rejected" })); + + const value = writeOf(creates[0] ?? [], RESPONSE).value; + expect(value).toMatchObject({ response: "rejected" }); + expect(value).not.toHaveProperty("weight"); + // Nothing is deduplicated or overwritten: a new record under a new key each time. + expect(first.uri).not.toBe(second.uri); + expect(creates).toHaveLength(2); + }); + + it.each([ + [ + "an account", + forDid(OTHER), + /is for did:plc:other222 and the client is signed in as did:plc:testowner123/, + ], + [ + "a record in another account's repository", + forRecord(`at://${OTHER}/${ACTIVITY}/3k2a4b5c6d7e8`), + /is for did:plc:other222 and the client is signed in as/, + ], + ])( + "refuses to respond to an award for %s that is not the signed-in account's", + async (_, subject, message) => { + stubIssuerPds({ [awardUri]: storedAward(subject) }); + const { context, requests } = fakeRepo(); + + const error = await respondToBadgeAward(context, respond()).catch((e) => e); + + expect(error.message).toMatch(/only the recipient can respond/); + expect(error.message).toMatch(message); + expect(requests).toHaveLength(0); + }, + ); + + it("does not let the issuer respond to an award they made for someone else", async () => { + const own = `at://${DID}/${AWARD}/3k2a4b5c6d7e8`; + const { context, requests } = fakeRepo({ records: { [own]: storedAward(forDid(OTHER)) } }); + + await expect(respondToBadgeAward(context, respond({ awardUri: own }))).rejects.toThrow( + /only the recipient can respond/, + ); + + expect(methods(requests)).toEqual(["com.atproto.repo.getRecord"]); + }); + + it.each<[string, Partial | Record, RegExp]>([ + [ + "a weight on a rejected award", + { response: "rejected", weight: "1" }, + /has a weight on a rejected award.* at \$\.weight/, + ], + [ + "a weight that is not a positive decimal", + { weight: "heavy" }, + /positive decimal number.* at \$\.weight/, + ], + [ + "a response other than accepted or rejected", + { response: "maybe" }, + /Expected one of "accepted" or "rejected"/, + ], + ["an unknown field", { note: "hi" }, /has a field the SDK does not know/], + [ + "an award URI of another type of record", + { awardUri: ownRecordUri }, + /must be of type app.certified.badge.award/, + ], + [ + "an award URI with a handle", + { awardUri: `at://alice.test/${AWARD}/3k2a4b5c6d7e8` }, + /not a record URI/, + ], + ])("sends nothing for %s", async (_, bad, message) => { + const reads = stubIssuerPds({ [awardUri]: storedAward(forDid(DID)) }); + const { context, requests } = fakeRepo(); + + const error = await respondToBadgeAward(context, { ...respond(), ...bad } as never).catch( + (e) => e, + ); + + expect(error).toBeInstanceOf(TypeError); + expect(error.message).toMatch(message); + expect([requests.length, reads.length]).toEqual([0, 0]); + }); + + it("rejects a weight the lexicon does not allow without writing", async () => { + stubIssuerPds({ [awardUri]: storedAward(forDid(DID)) }); + const { context, requests } = fakeRepo(); + + const error = await respondToBadgeAward(context, respond({ weight: "1".repeat(51) })).catch( + (e) => e, + ); + + expect(error).toBeInstanceOf(TypeError); + expect(error.message).toMatch(/the response is not a valid app.certified.badge.response/); + expect(requests).toHaveLength(0); + }); + + it.each<[string, Record, RegExp]>([ + ["an award that does not exist", {}, /cannot resolve .*the record was not found/], + [ + "an award that is not valid", + { [awardUri]: { $type: AWARD, subject: forDid(DID) } }, + /is not a valid app.certified.badge.award record.*does not respond to it/, + ], + [ + "an award for something that is neither an account nor a record", + { [awardUri]: storedAward({ $type: "example.app.thing", id: "1" }) }, + /neither an account \(app.certified.defs#did\) nor a record \(com.atproto.repo.strongRef\)/, + ], + [ + "an award for a record named by handle", + { [awardUri]: storedAward(forRecord(`at://alice.test/${ACTIVITY}/3k2a4b5c6d7e8`)) }, + /does not name its repository by DID, so the SDK cannot tell who its recipient is/, + ], + ])("does not write for %s", async (_, records, message) => { + stubIssuerPds(records); + const { context, requests } = fakeRepo(); + + await expect(respondToBadgeAward(context, respond())).rejects.toThrow(message); + + expect(requests).toHaveLength(0); + }); +}); + +describe("respondToBadgeAward when the write fails", () => { + it("reports a rejected write as definite, and a write without an answer as unknown without retrying", async () => { + stubIssuerPds({ [awardUri]: storedAward(forDid(DID)) }); + const rejecting = fakeRepo({ + applyWrites: () => json(400, { error: "InvalidRequest", message: "no" }), + }); + const silent = fakeRepo({ applyWrites: () => json(500, {}) }); + + const rejected = await respondToBadgeAward(rejecting.context, respond()).catch((e) => e); + const unknown = await respondToBadgeAward(silent.context, respond()).catch((e) => e); + + expect(rejected).toBeInstanceOf(WriteRejectedError); + expect(unknown).toBeInstanceOf(WriteOutcomeUnknownError); + expect(unknown.attempted).toHaveLength(1); + expect(unknown.attempted[0].uri).toMatch(new RegExp(`^at://${DID}/${RESPONSE}/`)); + expect(unknown.message).toContain(unknown.attempted[0].uri); + expect(methods(silent.requests)).toEqual(["com.atproto.repo.applyWrites"]); + }); +}); diff --git a/packages/sdk/src/badge/respond-to-award.ts b/packages/sdk/src/badge/respond-to-award.ts new file mode 100644 index 0000000..db7633c --- /dev/null +++ b/packages/sdk/src/badge/respond-to-award.ts @@ -0,0 +1,177 @@ +import { type DatetimeString, type DidString, l } from "@atproto/lex"; +import * as award from "@hypercerts-org/lexicon/app/certified/badge/award"; +import * as response from "@hypercerts-org/lexicon/app/certified/badge/response"; +import * as certifiedDefs from "@hypercerts-org/lexicon/app/certified/defs"; +import * as strongRef from "@hypercerts-org/lexicon/com/atproto/repo/strongRef"; +import type { SDKContext } from "../context.js"; +import { createBuildContext, parseInput, prepareChecked } from "../internal/build-context.js"; +import { describeError } from "../internal/describe.js"; +import { compact, optionalText, strictObject, weightString } from "../internal/input.js"; +import { parseRecordUri, readRecord, type StrongRef } from "../internal/resolve-record-ref.js"; +import { submitWrites } from "../internal/submit-writes.js"; + +const OPERATION = "respondToBadgeAward"; + +/** The input of {@link respondToBadgeAward}. */ +export interface RespondToBadgeAwardInput { + /** + * The award to respond to, as `at:///app.certified.badge.award/`, identified by a DID, + * not a handle. It may be in any account's repository if it is public. + */ + awardUri: string; + /** Whether the recipient accepts or rejects the award. */ + response: "accepted" | "rejected"; + /** + * How much the recipient weighs this badge, a positive decimal number written as a string (for + * example `"2"` or `"0.5"`), only for an accepted award. It is stored exactly as written. At most + * 50 characters. + */ + weight?: string | undefined; + /** An ISO 8601 date-time. Defaults to the time of the call. */ + createdAt?: string | undefined; +} + +const inputSchema = l.refine( + strictObject({ + awardUri: l.string(), + response: l.enum(["accepted", "rejected"]), + weight: l.optional(weightString), + createdAt: optionalText, + }), + { + check: ({ response: answer, weight }) => !(answer === "rejected" && weight !== undefined), + message: 'has a weight on a rejected award; a weight applies only when response is "accepted"', + path: "weight", + }, +); + +// Checked before any request: the URI must name a badge award. +function assertAwardUri(uri: string): void { + const { collection } = parseRecordUri(uri, OPERATION); + if (collection !== award.main.$type) { + throw new TypeError( + `${OPERATION}: awardUri points at a record of type ${collection}, but it must be of type ${award.main.$type}: ${uri}. Expected at:///${award.main.$type}/.`, + ); + } +} + +// The account the award is for: the DID of an account subject, or the repository that holds a +// record subject. That a record's repository is its recipient is the SDK's rule; the lexicon only +// says responses are written by the recipient. +function recipientOf({ subject }: award.Main, uri: string): DidString { + if (certifiedDefs.did.isTypeOf(subject)) return subject.did as DidString; + if (!strongRef.main.isTypeOf(subject)) { + throw new Error( + `${OPERATION}: the award ${uri} is for something that is neither an account (${certifiedDefs.did.$type}) nor a record (${strongRef.main.$type}), so the SDK cannot tell who its recipient is. No record was written.`, + ); + } + try { + return parseRecordUri(subject.uri, OPERATION).did; + } catch (error) { + throw new Error( + `${OPERATION}: the award ${uri} is for ${subject.uri}, which does not name its repository by DID, so the SDK cannot tell who its recipient is. No record was written.`, + { cause: error }, + ); + } +} + +/** + * Accepts or rejects a badge award (`app.certified.badge.response`) as its recipient. + * + * @remarks + * The award is read from its repository and the response is created in the signed-in account's + * repo. The recipient of an award to an account is that account; the recipient of an award to a + * record is the account whose repository holds the record. The lexicon says only that a response + * comes from the recipient, so that second rule is this SDK's: only the recipient's own response is + * created. Awarding a badge does not accept it for the recipient, so an issuer cannot respond to + * their own award unless they are also the recipient. + * + * The response references the award by URI and the CID that was read. The award, the badge + * definition and the subject are not changed. `weight` is for an accepted award only and is stored + * exactly as given: `"007.50"` stays `"007.50"`. It must be a positive decimal number, as elsewhere + * in the SDK. `createdAt` defaults to the time of the call. + * + * Nothing is deduplicated or overwritten: every call creates a response under a new record key, so + * responding twice, even with a different answer, leaves two responses. The SDK has no operation + * that changes or removes one, and does not check for an earlier response; how to read several + * responses to one award is up to the consumer. A write that failed with an unknown outcome is not + * safe to repeat for the same reason. + * + * @param context - The shared context from {@link createSDKContext}. Its client must be + * authenticated as the recipient. + * @param input - The award, the answer and an optional weight. See {@link RespondToBadgeAwardInput}. + * @returns The new response's URI and CID. + * @throws {@link TypeError} If `awardUri` is not `at:///app.certified.badge.award/`, if + * `response` is not `"accepted"` or `"rejected"`, if `weight` is given with a rejected response or + * is not a positive decimal number, if `input` has an unknown field, or if a value is not allowed + * by the lexicon (for example a `weight` over 50 characters). Nothing was written. + * @throws {@link Error} If the client is not authenticated; the award cannot be read or is not a + * valid `app.certified.badge.award`; its recipient cannot be determined; or the signed-in account is + * not the recipient. Nothing was written. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the + * response may or may not exist. It carries the URI to check. The SDK does not retry, because + * calling again would create a second response if the first attempt had succeeded. + * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK + * computed. + * + * @example Accepting an award with a weight + * ```ts + * import { respondToBadgeAward } from "@hypercerts-org/sdk/badge"; + * + * // `context` comes from createSDKContext, signed in as the award's recipient. + * const response = await respondToBadgeAward(context, { + * awardUri: "at://did:plc:issuer/app.certified.badge.award/3k2a4b5c6d7e8", + * response: "accepted", + * weight: "2", + * }); + * console.log(response.uri, response.cid); + * ``` + * + * @example Rejecting an award + * ```ts + * import { respondToBadgeAward } from "@hypercerts-org/sdk/badge"; + * + * await respondToBadgeAward(context, { + * awardUri: "at://did:plc:issuer/app.certified.badge.award/3k2a4b5c6d7e8", + * response: "rejected", // a weight here throws a TypeError + * }); + * ``` + */ +export async function respondToBadgeAward( + context: SDKContext, + input: RespondToBadgeAwardInput, +): Promise { + const build = createBuildContext(context, OPERATION); + const parsed = parseInput(build, "input", inputSchema, input); + assertAwardUri(parsed.awardUri); + + const stored = await readRecord(context, parsed.awardUri, OPERATION); + const checked = award.main.safeValidate(stored.value); + if (!checked.success) { + throw new Error( + `${OPERATION}: ${parsed.awardUri} is not a valid ${award.main.$type} record (${describeError(checked.reason)}), so the SDK does not respond to it. No record was written.`, + { cause: checked.reason }, + ); + } + const recipient = recipientOf(checked.value, parsed.awardUri); + if (recipient !== build.did) { + throw new Error( + `${OPERATION}: only the recipient can respond to a badge award, but ${parsed.awardUri} is for ${recipient} and the client is signed in as ${build.did}. No record was written. For an award to a record, the recipient is the account whose repository holds that record.`, + ); + } + + const record = await prepareChecked( + build, + "the response", + response.main, + compact({ + badgeAward: stored.ref, + response: parsed.response, + weight: parsed.weight, + createdAt: (parsed.createdAt ?? build.createdAt) as DatetimeString, + }), + ); + await submitWrites(context, build.did, [record], OPERATION); + return record.ref; +} From 193b4fd75747529d50d58037061ea0ca4600f1f8 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 13:25:45 +0600 Subject: [PATCH 2/6] sdk/badge: reuse media upload checks Share the placeholder-blob type/size check and the wrapped upload error from internal/media.ts instead of keeping copies in build-definition.ts. --- packages/sdk/src/badge/build-definition.ts | 50 +++++---------- packages/sdk/src/internal/media.ts | 71 ++++++++++++++++------ 2 files changed, 68 insertions(+), 53 deletions(-) diff --git a/packages/sdk/src/badge/build-definition.ts b/packages/sdk/src/badge/build-definition.ts index b1fba57..3401bec 100644 --- a/packages/sdk/src/badge/build-definition.ts +++ b/packages/sdk/src/badge/build-definition.ts @@ -1,11 +1,10 @@ -import { type DidString, l, parseCid } from "@atproto/lex"; +import { type DidString, l } from "@atproto/lex"; import * as definition from "@hypercerts-org/lexicon/app/certified/badge/definition"; import * as certifiedDefs from "@hypercerts-org/lexicon/app/certified/defs"; -import { uploadBlob } from "../blob/upload-blob.js"; import type { BuildContext } from "../internal/build-context.js"; import { createStandalone, type StandaloneCreator } from "../internal/create-record.js"; -import { describeError } from "../internal/describe.js"; import { blob, optionalText } from "../internal/input.js"; +import { assertFileAllowed, uploadField } from "../internal/media.js"; import { type RecordKind, recordKind } from "../internal/record-kind.js"; /** The data of a new `app.certified.badge.definition` record. */ @@ -34,41 +33,20 @@ export interface BadgeDefinitionInput { createdAt?: string | undefined; } -// The lexicon decides which types and sizes an icon may have, so the check runs its own schema on a -// definition that holds a blob reference built from the file's type and size, with a well-formed CID -// standing in for the one the upload will return. A Blob with no type is left to `uploadBlob`, which -// explains how to supply one. -function assertIconAllowed(build: BuildContext, field: string, file: Blob): void { - if (file.type === "") return; - const placeholder = parseCid("bafkreibm6jg3ux5qumhcn2b3flc3tyu6dmlb4xa7u5bf44yegnrjhc4yeq", { - flavor: "raw", - }); - const result = definition.main.safeValidate({ - $type: definition.main.$type, - title: "icon check", - badgeType: "icon check", - createdAt: build.createdAt, - icon: { $type: "blob", ref: placeholder, mimeType: file.type, size: file.size }, - }); - if (!result.success) { - throw new TypeError( - `${build.operation}: ${field} cannot be used as a badge icon (${file.type}, ${file.size} bytes): ${result.message}. Nothing was uploaded.`, - { cause: result }, - ); - } -} - // `icon` is a blob field of the definition itself, not a wrapper object like the images of the -// other records, so the shared media helper does not apply and the reference is stored as it is. +// other records, so `mediaValue` does not apply and the reference is stored as it is. The lexicon +// decides which types and sizes an icon may have, so the check runs the definition's own schema. async function uploadIcon(build: BuildContext, field: string, file: Blob) { - assertIconAllowed(build, field, file); - try { - return await uploadBlob(build.context, file); - } catch (error) { - throw new Error(`${build.operation}: could not upload ${field}: ${describeError(error)}`, { - cause: error, - }); - } + assertFileAllowed(build, field, file, "used as a badge icon", (icon) => + definition.main.safeValidate({ + $type: definition.main.$type, + title: "icon check", + badgeType: "icon check", + createdAt: build.createdAt, + icon, + }), + ); + return uploadField(build, field, file); } export const badgeDefinitionKind: RecordKind = recordKind( diff --git a/packages/sdk/src/internal/media.ts b/packages/sdk/src/internal/media.ts index 55b0e20..1699d03 100644 --- a/packages/sdk/src/internal/media.ts +++ b/packages/sdk/src/internal/media.ts @@ -1,4 +1,4 @@ -import { type l, parseCid, type UriString } from "@atproto/lex"; +import { type Cid, type l, parseCid, type UriString } from "@atproto/lex"; import * as defs from "@hypercerts-org/lexicon/org/hypercerts/defs"; import { uploadBlob } from "../blob/upload-blob.js"; import type { BuildContext } from "./build-context.js"; @@ -30,14 +30,7 @@ export async function mediaValue( ): Promise | l.$Typed> { if (typeof value === "string") return defs.uri.build({ uri: value as UriString }); assertWithinLimits(build, field, value, kind); - let blob: Awaited>; - try { - blob = await uploadBlob(build.context, value); - } catch (error) { - throw new Error(`${build.operation}: could not upload ${field}: ${describeError(error)}`, { - cause: error, - }); - } + const blob = await uploadField(build, field, value); const { schema, property } = WRAPPERS[kind]; return { $type: schema.$type, [property]: blob } as unknown as l.$Typed; } @@ -53,27 +46,71 @@ const WRAPPERS = { blob: { schema: defs.smallBlob, property: "blob", label: "blob" }, } as const; -// The check runs the lexicon's own blob schema on a blob reference built from the file's type and -// size, with a well-formed CID standing in for the one the upload will return. A Blob with no type -// is left to `uploadBlob`, which explains how to supply one. -function assertWithinLimits(build: BuildContext, field: string, file: Blob, kind: BlobKind): void { +/** + * Uploads a file for a record field, wrapping a failure in an `Error` that names the operation and + * the field (`could not upload `) and keeps the original as `cause`. + * + * Internal. For fields that do not go through `mediaValue`, for example a blob stored directly in + * the record. Check the file against the lexicon first, see `assertFileAllowed`. + */ +export async function uploadField( + build: BuildContext, + field: string, + file: Blob, +): Promise>> { + try { + return await uploadBlob(build.context, file); + } catch (error) { + throw new Error(`${build.operation}: could not upload ${field}: ${describeError(error)}`, { + cause: error, + }); + } +} + +/** + * Checks a file against a lexicon's rules before it is uploaded, so a file the record would reject + * is not left behind as an unreferenced upload. + * + * Internal. `validate` runs the lexicon's own schema on a blob reference built from the file's type + * and size, with a well-formed CID standing in for the one the upload will return; that reference + * must never be put in a record. `purpose` finishes the sentence " cannot be ..." in the + * error. A Blob with no type is left to `uploadBlob`, which explains how to supply one. + * + * Throws TypeError when `validate` fails. + */ +export function assertFileAllowed( + build: BuildContext, + field: string, + file: Blob, + purpose: string, + validate: (ref: PlaceholderBlobRef) => l.ValidationResult, +): void { if (file.type === "") return; - const ref = { + const ref: PlaceholderBlobRef = { $type: "blob", ref: parseCid("bafkreibm6jg3ux5qumhcn2b3flc3tyu6dmlb4xa7u5bf44yegnrjhc4yeq", { flavor: "raw" }), mimeType: file.type, size: file.size, }; - const { schema, property, label } = WRAPPERS[kind]; - const result = schema.safeValidate({ [property]: ref }); + const result = validate(ref); if (!result.success) { throw new TypeError( - `${build.operation}: ${field} cannot be stored as a ${label} (${file.type}, ${file.size} bytes): ${result.message}. Nothing was uploaded.`, + `${build.operation}: ${field} cannot be ${purpose} (${file.type}, ${file.size} bytes): ${result.message}. Nothing was uploaded.`, { cause: result }, ); } } +type PlaceholderBlobRef = { $type: "blob"; ref: Cid; mimeType: string; size: number }; + +// The check runs the lexicon's own blob schema on the wrapper object for this kind. +function assertWithinLimits(build: BuildContext, field: string, file: Blob, kind: BlobKind): void { + const { schema, property, label } = WRAPPERS[kind]; + assertFileAllowed(build, field, file, `stored as a ${label}`, (ref) => + schema.safeValidate({ [property]: ref }), + ); +} + /** A field transform for `recordKind` that uploads a `Blob` or keeps a URL string, see `mediaValue`. */ export const mediaTransform = (kind: BlobKind) => (build: BuildContext, field: string, value: Blob | string) => From 5188be55984c365bc6fc8067ad3d53f6be85be6b Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 16:22:27 +0600 Subject: [PATCH 3/6] sdk/badge: extract nested ternary in the validity-range error SonarCloud flagged the nested ternary in assertValidityRange. The message is unchanged. --- packages/sdk/src/badge/award-badge.ts | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/sdk/src/badge/award-badge.ts b/packages/sdk/src/badge/award-badge.ts index f76f5cf..692a7e2 100644 --- a/packages/sdk/src/badge/award-badge.ts +++ b/packages/sdk/src/badge/award-badge.ts @@ -84,19 +84,24 @@ const awardInput = strictObject({ createdAt: optionalText, }); +function describeStart( + start: string, + { validFrom, createdAt }: Pick, "validFrom" | "createdAt">, +): string { + if (validFrom !== undefined) return `validFrom (${start})`; + const defaulted = + createdAt === undefined ? " and createdAt defaults to the time of the call" : ""; + return `createdAt (${start}), which is when the badge starts to apply because validFrom is left out${defaulted}`; +} + // The effective start is the one the lexicon documents: `validFrom`, else `createdAt` (which, left // out, is the time of the call). A date that does not parse is not judged here: the lexicon // rejects it when the award is validated. -function assertValidityRange( - build: BuildContext, - { validFrom, validUntil, createdAt }: l.InferOutput, -): void { +function assertValidityRange(build: BuildContext, input: l.InferOutput): void { + const { validFrom, validUntil, createdAt } = input; const start = validFrom ?? createdAt ?? build.createdAt; if (!endsBeforeStart({ startDate: start, endDate: validUntil })) return; - const startsAt = - validFrom === undefined - ? `createdAt (${start}), which is when the badge starts to apply because validFrom is left out${createdAt === undefined ? " and createdAt defaults to the time of the call" : ""}` - : `validFrom (${start})`; + const startsAt = describeStart(start, input); throw new TypeError( `${build.operation}: validUntil (${validUntil}) is earlier than ${startsAt}, so the badge would end before it starts. Nothing was written.`, ); From 1a69ce68496cc8cd19c9b29e6664f5d9bebb18d6 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 16:51:59 +0600 Subject: [PATCH 4/6] skill/badge: declare awardUri in the respondToBadgeAward example --- .../skills/hypercerts-org-sdk/references/badge.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/.agents/skills/hypercerts-org-sdk/references/badge.md b/.agents/skills/hypercerts-org-sdk/references/badge.md index 924f3cd..6d58b28 100644 --- a/.agents/skills/hypercerts-org-sdk/references/badge.md +++ b/.agents/skills/hypercerts-org-sdk/references/badge.md @@ -64,13 +64,12 @@ await awardBadge(context, { ```ts import { respondToBadgeAward } from "@hypercerts-org/sdk/badge"; -await respondToBadgeAward(context, { - awardUri: "at://did:plc:issuer/app.certified.badge.award/3k2a4b5c6d7e8", - response: "accepted", - weight: "2", -}); -// `awardUri` is the URI of the award, from the issuer or your app. -await respondToBadgeAward(context, { awardUri, response: "rejected" }); // no weight here +// The URI of the award, from the issuer or your app. +const awardUri = "at://did:plc:issuer/app.certified.badge.award/3k2a4b5c6d7e8"; + +await respondToBadgeAward(context, { awardUri, response: "accepted", weight: "2" }); +// Or reject it (no weight here): +await respondToBadgeAward(context, { awardUri, response: "rejected" }); ``` - The recipient of an award to an account is that account. For an award to a record it is the account whose repository holds the record (the SDK's rule; the lexicon does not say). Any other signed-in account, the issuer included, gets an `Error` and nothing is written. From 95e7c9837e7b590fb27a0419814759334078697c Mon Sep 17 00:00:00 2001 From: kzoeps Date: Tue, 10 Nov 2026 19:39:21 +0600 Subject: [PATCH 5/6] sdk/badge: describe uploads and write errors in the short form --- .../hypercerts-org-sdk/references/badge.md | 6 +++--- packages/sdk/src/badge/award-badge.ts | 17 ++++++++--------- packages/sdk/src/badge/build-definition.ts | 12 +++++------- packages/sdk/src/badge/respond-to-award.ts | 10 ++++------ packages/sdk/src/internal/media.ts | 2 +- 5 files changed, 21 insertions(+), 26 deletions(-) diff --git a/.agents/skills/hypercerts-org-sdk/references/badge.md b/.agents/skills/hypercerts-org-sdk/references/badge.md index 6d58b28..d5277c3 100644 --- a/.agents/skills/hypercerts-org-sdk/references/badge.md +++ b/.agents/skills/hypercerts-org-sdk/references/badge.md @@ -54,7 +54,7 @@ await awardBadge(context, { - `validFrom` defaults to `createdAt` (which defaults to the time of the call). A `validUntil` earlier than `validFrom`, or than `createdAt` when `validFrom` is omitted, throws `TypeError`. Timestamps are stored as given. `validUntil` marks the award expired; it is not revocation. - Awarding does not accept the badge for the recipient; they use `respondToBadgeAward`. - The new definition and the award are one `applyWrites` commit: both exist afterwards, or neither does. -- `WriteOutcomeUnknownError.attempted` lists the new definition (if any) first, then the award. Do not call again blindly: it would create a second award. Check the URIs with `com.atproto.repo.getRecord` first. +- After `WriteOutcomeUnknownError`, `attempted` lists the new definition (if any) first, then the award. Calling again is not safe: it would create a second award. - Nothing is deduplicated: awarding the same badge to the same subject twice creates two awards. ## respondToBadgeAward @@ -74,11 +74,11 @@ await respondToBadgeAward(context, { awardUri, response: "rejected" }); - The recipient of an award to an account is that account. For an award to a record it is the account whose repository holds the record (the SDK's rule; the lexicon does not say). Any other signed-in account, the issuer included, gets an `Error` and nothing is written. - `weight` only goes with `"accepted"`; with `"rejected"` it throws `TypeError`. It must be a positive decimal number written as a string and is stored exactly as written (`"007.50"` stays `"007.50"`). -- Nothing is deduplicated or overwritten: every call creates a response under a new key. Responding twice leaves two responses. Do not repeat after `WriteOutcomeUnknownError` without checking `attempted`. +- Nothing is deduplicated or overwritten: every call creates a response under a new key. Responding twice leaves two responses. Calling again after `WriteOutcomeUnknownError` is not safe: it would create a second response. ## Uploads are outside the commit -A new definition's `icon` is uploaded before the write. Invalid input, a refused issuer and an unreadable subject or definition fail before any upload; a rule of the award's or the new definition's lexicon (for example a `note` over 500 characters) is only found after it. If the write or such a rule fails, the blob stays unreferenced (a PDS usually deletes it later, not guaranteed). +A new definition's `icon` is the only file uploaded, before the write, and is not rolled back if it fails; see [Uploads are not part of the atomic write](../SKILL.md#uploads-are-not-part-of-the-atomic-write). Invalid input, a refused issuer and an unreadable subject or definition fail before any upload; a rule of the award's or the new definition's lexicon (for example a `note` over 500 characters) is found only after it. ## Input fields diff --git a/packages/sdk/src/badge/award-badge.ts b/packages/sdk/src/badge/award-badge.ts index 692a7e2..320bf57 100644 --- a/packages/sdk/src/badge/award-badge.ts +++ b/packages/sdk/src/badge/award-badge.ts @@ -138,9 +138,9 @@ function assertValidityRange(build: BuildContext, input: l.InferOutput = recordKind( * * `icon` is uploaded before the record is written. The SDK checks its type and size against the * lexicon (PNG, JPEG, WebP or SVG, at most 1 MiB) first, so a file the record would reject is not - * uploaded. The upload is not part of the write: if the write fails, the uploaded blob is left - * unreferenced. A PDS usually deletes unreferenced blobs after a while, but this is not guaranteed, - * and a blob with the same content that another record already uses stays. + * uploaded. Blobs are uploaded before the write and are not rolled back if it fails; see + * {@link uploadBlob}. * * @param context - The shared context from {@link createSDKContext}. Its client must be * authenticated. @@ -96,10 +95,9 @@ export const badgeDefinitionKind: RecordKind = recordKind( * does not allow (for example a `title` over 256 characters). Nothing was written. Blobs may * already have been uploaded when a lexicon rule other than the icon's rejects the record. * @throws {@link Error} If the client is not authenticated, or the icon upload fails. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the - * definition may or may not exist. It carries the URI to check. The SDK does not retry, because - * calling again would create a second definition if the first attempt had succeeded. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create a second definition if the first attempt had succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK * computed. * diff --git a/packages/sdk/src/badge/respond-to-award.ts b/packages/sdk/src/badge/respond-to-award.ts index db7633c..7d9afb5 100644 --- a/packages/sdk/src/badge/respond-to-award.ts +++ b/packages/sdk/src/badge/respond-to-award.ts @@ -94,8 +94,7 @@ function recipientOf({ subject }: award.Main, uri: string): DidString { * Nothing is deduplicated or overwritten: every call creates a response under a new record key, so * responding twice, even with a different answer, leaves two responses. The SDK has no operation * that changes or removes one, and does not check for an earlier response; how to read several - * responses to one award is up to the consumer. A write that failed with an unknown outcome is not - * safe to repeat for the same reason. + * responses to one award is up to the consumer. * * @param context - The shared context from {@link createSDKContext}. Its client must be * authenticated as the recipient. @@ -108,10 +107,9 @@ function recipientOf({ subject }: award.Main, uri: string): DidString { * @throws {@link Error} If the client is not authenticated; the award cannot be read or is not a * valid `app.certified.badge.award`; its recipient cannot be determined; or the signed-in account is * not the recipient. Nothing was written. - * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). Nothing was created. - * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS, so the - * response may or may not exist. It carries the URI to check. The SDK does not retry, because - * calling again would create a second response if the first attempt had succeeded. + * @throws {@link WriteRejectedError} If the PDS rejected the write (HTTP 4xx). + * @throws {@link WriteOutcomeUnknownError} If there was no usable answer from the PDS. Calling again + * is not safe: it would create a second response if the first attempt had succeeded. * @throws {@link WriteResultMismatchError} If the PDS reported a different URI or CID than the SDK * computed. * diff --git a/packages/sdk/src/internal/media.ts b/packages/sdk/src/internal/media.ts index 1699d03..27ae951 100644 --- a/packages/sdk/src/internal/media.ts +++ b/packages/sdk/src/internal/media.ts @@ -69,7 +69,7 @@ export async function uploadField( /** * Checks a file against a lexicon's rules before it is uploaded, so a file the record would reject - * is not left behind as an unreferenced upload. + * is never uploaded. * * Internal. `validate` runs the lexicon's own schema on a blob reference built from the file's type * and size, with a well-formed CID standing in for the one the upload will return; that reference From e4466e355e83be04ac531b70948ed9a6688609a3 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Wed, 11 Nov 2026 17:53:32 +0600 Subject: [PATCH 6/6] sdk/badge: expect the handle-authority error from shared slot checks --- packages/sdk/src/badge/award-badge.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sdk/src/badge/award-badge.test.ts b/packages/sdk/src/badge/award-badge.test.ts index 61640b3..67abe85 100644 --- a/packages/sdk/src/badge/award-badge.test.ts +++ b/packages/sdk/src/badge/award-badge.test.ts @@ -282,7 +282,7 @@ describe("awardBadge input and references", () => { [ "a definition URI with a handle", { definition: { uri: `at://alice.test/${DEFINITION}/3k2a4b5c6d7e8` } }, - /not a record URI/, + /definition must use a DID as the authority, not a handle/, ], [ "a new definition without a title",