* 🚧 WIP with proposed lexicons for event based mod architecture * 🚧 Remove unnecessary moderation action lexicon * 🚧 Working on event based actions * ✨ Add escalated subject status * 🐛 Alright, fixed the error in lexicon * 🚧 Working through reversal * ✨ Cleanup build errors * ✨ Add subject status endpoint * ✨ Add handler * ✨ get reports from mod actions table * :rightwards_twisted_arrows: Merge with upstream * 🚧 Builds but test network doesnt start * ✨ Tests passing on event based status change * ✨ Rename index * ♻️ Rename takeModerationAction->emitModerationEvent * ✨ Implement label reversal * ✅ Auto-revert test working * ♻️ ✅ Refactored to event types and tests are passing * ✨ Add takedown event sequence validation * ✨ Adds support for blobCid status * 🧹 Cleanup unnecessary method: * ✨ Hydrate handles with status and events * ✨ Re-implement auto reversal * ✨ Add takendown and mute filters * ✨ Allow filtering events by type * ✨ Allow filtering events by creator did * ✨ Add subjectStatus to record and repoview * ✨ Add persistent note feature * ✨ Log send email event * 🐛 Fix logging send email event * ✨ Better type * ✨ Adjust migration to create separate moderation_event table * 🧹 Cleanup types * ✅ Adjust tests with mod event emitter * ✨ Fix more tests around takedowns * ✅ Get test suite to pass * ✅ Get test suite to pass for pds * ✅ Get test suite to pass for pds * ✅ Update snapshot for feedgen * ✅ Why are more snapshots updating? * ♻️ Rename getModerationEvents -> queryModerationEvents * ♻️ Rename getModerationStatuses -> queryModerationStatuses * ♻️ Rename persistNote->sticky * 🐛 Rename subject * ♻️ Cleanup expiresAt for scheduled actions * ✨ Add more tests, allow fetching mod history for all content by a user * ✅ Fix repo and record tests * ✨ Migrate reports and actions to events * 🐛 Fix escalated status overwrite * ✨ Implement direct sql query to create events from actions and reports * 🚧 Adding keyset pagination for subject statuses * ✨ Add migration for lastReportedAt * ✨ Migrate blob cids * ✨ Fix pagination on mod subject list endpoint * 🐛 Fix blob actions * ✅ All tests passing on bsky package * ✅ Bring back snapshots * ✅ Skipping timeline test temporarily * ✅ Skipping some more tests to isolate failing ones * ✅ Bring back list-feed test * ✅ Bring back timeline test * ✅ Fix label action in seeding * ✅ Enable timeline proxied test * ✅ Enable search actor proxied test * ✅ Enable feedgen tests * ✅ Fix test for admin/get-record * ✨ Move note to comment for subject status * ✨ Accept comments in mute event * ✨ Remap flag event to ack event * 🐛 Add legacyRef in report union selection * @atproto/api 0.6.24-next.0 * @atproto/api 0.6.24-next.1 * ✨ Adjust migration export and add index for blobCids column * ✨ Maintin action ids when migrating * ✨ Paginate events using createdAt timestamp * ✅ Update snapshot for pds test with events cursor update * ✅ Use only events for snapshot testing * ✅ Use only events for snapshot in the remaining test * relative paths to lexicons for build * fix bsky periodic event reversal in service entrypoint * ✨ Allow comments in takedown and label * ✨ Only import reports on consecutive run of the migration script * ✨ Adjust moderation property of blob entries * determine latest reports to migrate * ✨ Process new reports for subject status * ✨ Process unresolved reports on first migration run * fix transaction error, process just unresolved reports, make reported-at updates safe for reruns * tidy --------- Co-authored-by: Devin Ivy <devinivy@gmail.com>
ATP API
This API is a client for ATProtocol servers. It communicates using HTTP. It includes:
- ✔️ APIs for ATProto and Bluesky.
- ✔️ Validation and complete typescript types.
- ✔️ Session management.
- ✔️ A RichText library.
Getting started
First install the package:
yarn add @atproto/api
Then in your application:
import { BskyAgent } from '@atproto/api'
const agent = new BskyAgent({ service: 'https://example.com' })
Usage
Session management
Log into a server or create accounts using these APIs. You'll need an active session for most methods.
import { BskyAgent, AtpSessionEvent, AtpSessionData } from '@atproto/api'
// configure connection to the server, without account authentication
const agent = new BskyAgent({
service: 'https://example.com',
persistSession: (evt: AtpSessionEvent, sess?: AtpSessionData) => {
// store the session-data for reuse
},
})
// create a new account on the server
await agent.createAccount({
email: 'alice@mail.com',
password: 'hunter2',
handle: 'alice.example.com',
inviteCode: 'some-code-12345-abcde',
})
// if an existing session (accessed with 'agent.session') was securely stored previously, then reuse that
await agent.resumeSession(savedSessionData)
// if no old session was available, create a new one by logging in with password (App Password)
await agent.login({ identifier: 'alice@mail.com', password: 'hunter2' })
API calls
The agent includes methods for many common operations, including:
// Feeds and content
await agent.getTimeline(params, opts)
await agent.getAuthorFeed(params, opts)
await agent.getPostThread(params, opts)
await agent.getPost(params)
await agent.getPosts(params, opts)
await agent.getLikes(params, opts)
await agent.getRepostedBy(params, opts)
await agent.post(record)
await agent.deletePost(postUri)
await agent.like(uri, cid)
await agent.deleteLike(likeUri)
await agent.repost(uri, cid)
await agent.deleteRepost(repostUri)
await agent.uploadBlob(data, opts)
// Social graph
await agent.getFollows(params, opts)
await agent.getFollowers(params, opts)
await agent.follow(did)
await agent.deleteFollow(followUri)
// Actors
await agent.getProfile(params, opts)
await agent.upsertProfile(updateFn)
await agent.getProfiles(params, opts)
await agent.getSuggestions(params, opts)
await agent.searchActors(params, opts)
await agent.searchActorsTypeahead(params, opts)
await agent.mute(did)
await agent.unmute(did)
await agent.muteModList(listUri)
await agent.unmuteModList(listUri)
await agent.blockModList(listUri)
await agent.unblockModList(listUri)
// Notifications
await agent.listNotifications(params, opts)
await agent.countUnreadNotifications(params, opts)
await agent.updateSeenNotifications()
// Identity
await agent.resolveHandle(params, opts)
await agent.updateHandle(params, opts)
// Session management
await agent.createAccount(params)
await agent.login(params)
await agent.resumeSession(session)
Validation and types
The package includes a complete types system which includes validation and type-guards. For example, to validate a post record:
import { AppBskyFeedPost } from '@atproto/api'
const post = {...}
if (AppBskyFeedPost.isRecord(post)) {
// typescript now recognizes `post` as a AppBskyFeedPost.Record
// however -- we still need to validate it
const res = AppBskyFeedPost.validateRecord(post)
if (res.success) {
// a valid record
} else {
// something is wrong
console.log(res.error)
}
}
Rich text
Some records (ie posts) use the app.bsky.richtext
lexicon. At the moment richtext is only used for links and mentions, but it will be extended over time to include bold, italic, and so on.
ℹ️ It is strongly recommended to use this package's RichText
library. Javascript encodes strings in utf16 while the protocol (and most other programming environments) use utf8. Converting between the two is challenging, but RichText
handles that for you.
import { RichText } from '@atproto/api'
// creating richtext
const rt = new RichText({
text: 'Hello @alice.com, check out this link: https://example.com',
})
await rt.detectFacets(agent) // automatically detects mentions and links
const postRecord = {
$type: 'app.bsky.feed.post',
text: rt.text,
facets: rt.facets,
createdAt: new Date().toISOString(),
}
// rendering as markdown
let markdown = ''
for (const segment of rt.segments()) {
if (segment.isLink()) {
markdown += `[${segment.text}](${segment.link?.uri})`
} else if (segment.isMention()) {
markdown += `[${segment.text}](https://my-bsky-app.com/user/${segment.mention?.did})`
} else {
markdown += segment.text
}
}
// calculating string lengths
const rt2 = new RichText({ text: 'Hello' })
console.log(rt2.length) // => 5
console.log(rt2.graphemeLength) // => 5
const rt3 = new RichText({ text: '👨👩👧👧' })
console.log(rt3.length) // => 25
console.log(rt3.graphemeLength) // => 1
Moderation
Applying the moderation system is a challenging task, but we've done our best to simplify it for you. The Moderation API helps handle a wide range of tasks, including:
- User muting (including mutelists)
- User blocking
- Moderator labeling
For more information, see the Moderation Documentation or the associated Labels Reference.
import { moderatePost, moderateProfile } from '@atproto/api'
// We call the appropriate moderation function for the content
// =
const postMod = moderatePost(postView, getOpts())
const profileMod = moderateProfile(profileView, getOpts())
// We then use the output to decide how to affect rendering
// =
if (postMod.content.filter) {
// dont render in feeds or similar
// in contexts where this is disruptive (eg threads) you should ignore this and instead check blur
}
if (postMod.content.blur) {
// render the whole object behind a cover (use postMod.content.cause to explain)
if (postMod.content.noOverride) {
// do not allow the cover the be removed
}
}
if (postMod.content.alert) {
// render a warning on the content (use postMod.content.cause to explain)
}
if (postMod.embed.blur) {
// render the embedded media behind a cover (use postMod.embed.cause to explain)
if (postMod.embed.noOverride) {
// do not allow the cover the be removed
}
}
if (postMod.embed.alert) {
// render a warning on the embedded media (use postMod.embed.cause to explain)
}
if (postMod.avatar.blur) {
// render the avatar behind a cover
}
if (postMod.avatar.alert) {
// render an alert on the avatar
}
// The options passed into `apply()` supply the user's preferences
// =
function getOpts() {
return {
// the logged-in user's DID
userDid: 'did:plc:1234...',
// is adult content allowed?
adultContentEnabled: true,
// the global label settings (used on self-labels)
labels: {
porn: 'hide',
sexual: 'warn',
nudity: 'ignore',
// ...
},
// the per-labeler settings
labelers: [
{
labeler: {
did: '...',
displayName: 'My mod service',
},
labels: {
porn: 'hide',
sexual: 'warn',
nudity: 'ignore',
// ...
},
},
],
}
}
Advanced
Advanced API calls
The methods above are convenience wrappers. It covers most but not all available methods.
The AT Protocol identifies methods and records with reverse-DNS names. You can use them on the agent as well:
const res1 = await agent.com.atproto.repo.createRecord({
did: alice.did,
collection: 'app.bsky.feed.post',
record: {
$type: 'app.bsky.feed.post',
text: 'Hello, world!',
createdAt: new Date().toISOString(),
},
})
const res2 = await agent.com.atproto.repo.listRecords({
repo: alice.did,
collection: 'app.bsky.feed.post',
})
const res3 = await agent.app.bsky.feed.post.create(
{ repo: alice.did },
{
text: 'Hello, world!',
createdAt: new Date().toISOString(),
},
)
const res4 = await agent.app.bsky.feed.post.list({ repo: alice.did })
Generic agent
If you want a generic AT Protocol agent without methods related to the Bluesky social lexicon, use the AtpAgent
instead of the BskyAgent
.
import { AtpAgent } from '@atproto/api'
const agent = new AtpAgent({ service: 'https://example.com' })
Non-browser configuration
In non-browser environments you'll need to specify a fetch polyfill. See the example react-native polyfill here.
import { BskyAgent } from '@atproto/api'
const agent = new BskyAgent({ service: 'https://example.com' })
// provide a custom fetch implementation (shouldnt be needed in node or the browser)
import {
AtpAgentFetchHeaders,
AtpAgentFetchHandlerResponse,
} from '@atproto/api'
BskyAgent.configure({
async fetch(
httpUri: string,
httpMethod: string,
httpHeaders: AtpAgentFetchHeaders,
httpReqBody: any,
): Promise<AtpAgentFetchHandlerResponse> {
// insert definition here...
return { status: 200 /*...*/ }
},
})
License
This project is dual-licensed under MIT and Apache 2.0 terms:
- MIT license (LICENSE-MIT.txt or http://opensource.org/licenses/MIT)
- Apache License, Version 2.0, (LICENSE-APACHE.txt or http://www.apache.org/licenses/LICENSE-2.0)
Downstream projects and end users may chose either license individually, or both together, at their discretion. The motivation for this dual-licensing is the additional software patent assurance provided by Apache 2.0.