-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluesky-client.ts
232 lines (210 loc) · 6.73 KB
/
bluesky-client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { BskyAgent } from "@atproto/api";
import type { BlueskyCredentials, BlockPattern } from "./types";
import {
DEFAULT_PATTERNS,
ADULT_CONTENT_PATTERN,
PROMO_LINK_PATTERN,
checkFollowRatio
} from "./patterns";
import { DB } from "./db";
export class BlueskyBlocker {
private agent: BskyAgent;
private patterns: BlockPattern[];
private db: DB;
private debug!: boolean;
constructor(
patterns: BlockPattern[] = DEFAULT_PATTERNS,
debug: boolean = false
) {
this.agent = new BskyAgent({ service: "https://bsky.social" });
this.patterns = patterns;
this.db = new DB();
this.debug = debug;
}
async login(credentials: BlueskyCredentials): Promise<void> {
try {
await this.agent.login({
identifier: credentials.identifier,
password: credentials.password
});
console.log(`✅ Successfully logged in as ${credentials.identifier}`);
} catch (error) {
throw new Error(`Failed to login: ${(error as Error).message}`);
}
}
private async matchesPatterns(
profile: any
): Promise<{ matches: boolean; reason?: string }> {
// Fetch full profile data
try {
const profileView = await this.agent.api.app.bsky.actor.getProfile({
actor: profile.did
});
const fullProfile = profileView.data;
// Debug logging
if (this.debug) {
console.log(`\nDebug - Checking profile: ${fullProfile.handle}`);
console.log(JSON.stringify(fullProfile, null, 2));
}
// Check for adult content indicators combined with follower ratio
if (fullProfile.followersCount && fullProfile.followsCount) {
const result = checkFollowRatio(
fullProfile.followsCount,
fullProfile.followersCount,
fullProfile.description || "",
this.debug
);
if (result.matches) {
return result;
}
}
// Then check standard patterns
for (const pattern of this.patterns) {
if (
pattern.displayNamePattern &&
pattern.displayNamePattern.test(fullProfile.displayName || "")
) {
return {
matches: true,
reason: `Display name matches pattern: ${pattern.displayNamePattern}`
};
}
if (
pattern.descriptionPattern &&
pattern.descriptionPattern.test(fullProfile.description || "")
) {
return {
matches: true,
reason: `Description matches pattern: ${pattern.descriptionPattern}`
};
}
}
return { matches: false };
} catch (error) {
console.error(
`Failed to fetch full profile data for ${profile.handle}:`,
error
);
return { matches: false };
}
}
async checkNewFollowers(limit: number = 50): Promise<void> {
try {
const followers = await this.agent.getFollowers({
actor: this.agent.session?.did || "",
limit
});
for (const follower of followers.data.followers) {
if (!this.db.hasBeenChecked(follower.did)) {
console.log(`\n👤 Checking follower: ${follower.handle}`);
const matchResult = await this.matchesPatterns(follower);
if (matchResult?.matches) {
console.log(
`🚫 Adding user ${follower.handle} (${follower.did}) to block list`
);
console.log(` Reason: ${matchResult.reason}`);
await this.addUserToBlockList(
follower.did,
follower.handle,
matchResult.reason || "Unknown"
);
}
await this.db.recordCheck({
did: follower.did,
handle: follower.handle,
checkedAt: new Date(),
blocked: matchResult?.matches || false,
reason: matchResult?.reason
});
}
}
} catch (error) {
console.error("❌ Error checking followers:", error);
}
}
async addUserToBlockList(
did: string,
handle: string,
reason: string = "Unknown"
): Promise<void> {
try {
const listId = process.env.BLOCKLIST_ID;
if (!listId) {
throw new Error(
"BLOCKLIST_ID environment variable must be set (the UUID from your list's URL)"
);
}
try {
await this.agent.com.atproto.repo.createRecord({
repo: this.agent.session?.did || "",
collection: "app.bsky.graph.listitem",
record: {
$type: "app.bsky.graph.listitem",
subject: did,
list: `at://${this.agent.session?.did}/app.bsky.graph.list/${listId}`,
createdAt: new Date().toISOString()
}
});
console.log(`✅ Added ${handle} to shared block list`);
} catch (listError) {
// Check if user is already in the list
if ((listError as Error).message?.includes("duplicate")) {
console.log(`ℹ️ ${handle} is already in the block list`);
} else {
throw listError;
}
}
} catch (error) {
console.error(
`❌ Failed to add user ${handle} to block list:`,
(error as Error).message
);
}
}
async checkAllFollowers(): Promise<void> {
console.log("🔍 Starting comprehensive follower check...");
let totalChecked = 0;
let cursor: string | undefined;
do {
const followers = await this.agent.getFollowers({
actor: this.agent.session?.did || "",
cursor,
limit: 100
});
console.log(
`\nProcessing batch of ${followers.data.followers.length} followers...`
);
for (const follower of followers.data.followers) {
totalChecked++;
if (!this.db.hasBeenChecked(follower.did)) {
const matchResult = await this.matchesPatterns(follower);
if (matchResult?.matches) {
console.log(`👤 Checking follower: ${follower.handle}`);
console.log(
`🚫 Adding user ${follower.handle} (${follower.did}) to block list`
);
console.log(` Reason: ${matchResult.reason}`);
await this.addUserToBlockList(
follower.did,
follower.handle,
matchResult.reason || "Unknown"
);
}
await this.db.recordCheck({
did: follower.did,
handle: follower.handle,
checkedAt: new Date(),
blocked: matchResult?.matches || false,
reason: matchResult?.reason
});
} else {
console.log(`Skipped ${follower.handle} (already checked)`);
}
}
cursor = followers.data.cursor;
} while (cursor);
console.log(
`\n✅ Finished comprehensive follower check (processed ${totalChecked} followers)`
);
}
}