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
233
234
235
236
237
238
239
240
241
import Foundation
import XCTest
@testable import OldFella
extension ATProtoServiceTests {
func testLoadPostPreservesTextAndMapsOnlyValidFacets() async throws {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: configuration)
StubURLProtocol.clearRequests()
let uri = "at://did:plc:facet/app.bsky.feed.post/one"
let text = "🌙 https://example.com @friend.example #sky and https://ordinary.example"
let facets = facetFixture(text: text)
let postObject: [String: Any] = [
"uri": uri,
"cid": "facet-cid",
"author": ["did": "did:plc:author", "handle": "author.example"],
"record": ["text": text, "facets": facets],
"indexedAt": "2024-05-06T12:34:56.123Z"
]
StubURLProtocol.handler = { request in
XCTAssertEqual(request.url?.host, "public.api.bsky.app")
XCTAssertNil(request.value(forHTTPHeaderField: "Authorization"))
if request.url?.path == "/xrpc/app.bsky.unspecced.getPostThreadV2" {
return (404, Data("{\"error\":\"MethodNotFound\"}".utf8))
}
let response = try JSONSerialization.data(withJSONObject: ["thread": ["post": postObject, "replies": []]])
return (200, response)
}
defer {
StubURLProtocol.handler = nil
session.invalidateAndCancel()
}
let service = ATProtoBlueskyService(defaults: .standard, session: session)
let loadedPosts = try await service.loadPost(uri: uri)
let post = try XCTUnwrap(loadedPosts.first)
XCTAssertEqual(post.text, text)
XCTAssertEqual(post.facets.count, 4)
XCTAssertEqual(
post.facets.map(\.feature),
[
.link(URL(string: "https://example.com")!),
.mention("did:plc:friend"),
.tag("sky"),
.link(URL(string: "https://ordinary.example")!)
])
XCTAssertTrue(post.links.isEmpty)
}
func testThreadUsesValidNumbersFromV2WithoutChangingThePostOrder() async throws {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: configuration)
let prefix = "at://did:plc:reader/app.bsky.feed.post/"
func post(_ name: String) -> [String: Any] {
[
"uri": prefix + name, "cid": "\(name)-cid",
"author": ["did": "did:plc:reader", "handle": "reader.example"],
"record": ["text": name], "indexedAt": "2024-05-06T12:34:56Z"
]
}
func numbered(_ name: String, _ index: Int, hidden: Bool = false) -> [String: Any] {
[
"uri": prefix + name,
"value": [
"post": post(name), "opThread": true, "hiddenByThreadgate": hidden,
"opThreadPostIndex": index, "opThreadPostCount": 2
]
]
}
StubURLProtocol.handler = { request in
if request.url?.path == "/xrpc/app.bsky.unspecced.getPostThreadV2" {
let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
XCTAssertEqual(query?.first { $0.name == "anchor" }?.value, prefix + "root")
let items = [
numbered("root", 1), numbered("second", 2), numbered("side", 3),
numbered("hidden", 2, hidden: true), numbered("v2-only", 2)
]
return (200, try JSONSerialization.data(withJSONObject: ["thread": items]))
}
let replies = ["side", "hidden", "second"].map { ["post": post($0)] }
return (200, try JSONSerialization.data(withJSONObject: ["thread": ["post": post("root"), "replies": replies]]))
}
defer {
StubURLProtocol.handler = nil
session.invalidateAndCancel()
}
let service = ATProtoBlueskyService(defaults: .standard, session: session)
let result = try await service.loadThread(uri: prefix + "root")
XCTAssertEqual(result.posts.map(\.id), ["root", "side", "hidden", "second"].map { prefix + $0 })
XCTAssertEqual(result.positions, [
prefix + "root": ThreadPosition(index: 1, count: 2),
prefix + "second": ThreadPosition(index: 2, count: 2)
].compactMapValues { $0 })
}
func testLoadPostResolvesHandleAuthorityButPreservesDIDAuthority() async throws {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: configuration)
StubURLProtocol.clearRequests()
let didURI = "at://did:plc:reader/app.bsky.feed.post/selected"
let handleURI = "at://reader.bsky.social/app.bsky.feed.post/selected"
let response = Data("{\"thread\":{}}".utf8)
StubURLProtocol.handler = { request in
if request.url?.path == "/xrpc/com.atproto.identity.resolveHandle" {
return (200, Data("{\"did\":\"did:plc:reader\"}".utf8))
}
if request.url?.path == "/xrpc/app.bsky.feed.getPostThread" {
let query = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems
let requestedURI = query?.first(where: { $0.name == "uri" })?.value
XCTAssertEqual(requestedURI, didURI)
return (200, response)
}
return (404, Data("{\"error\":\"NotFound\"}".utf8))
}
defer {
StubURLProtocol.handler = nil
session.invalidateAndCancel()
}
let service = ATProtoBlueskyService(defaults: .standard, session: session)
_ = try await service.loadPost(uri: handleURI)
_ = try await service.loadPost(uri: didURI)
XCTAssertEqual(
StubURLProtocol.recordedRequests.filter { $0.url?.path == "/xrpc/com.atproto.identity.resolveHandle" }
.count, 1)
}
func testPublicProfileRequestDoesNotUsePDSProxyOrAuthorization() async throws {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: configuration)
StubURLProtocol.clearRequests()
StubURLProtocol.handler = { request in
XCTAssertEqual(request.url?.host, "public.api.bsky.app")
XCTAssertNil(request.value(forHTTPHeaderField: "Authorization"))
XCTAssertNil(request.value(forHTTPHeaderField: "atproto-proxy"))
let profile: [String: Any] = [
"did": "did:plc:public", "handle": "public.example",
"links": [
[
"uri": "at://did:plc:public/app.bsky.actor.link/photos", "title": "My Photos!",
"url": "https://geesawra.github.io/crossgrain/did:plc:6ll5xi67lyuyovt6fiv4fnjo"
],
[
"uri": "at://did:plc:public/app.bsky.actor.link/github", "title": "GitHub",
"url": "https://github.com/geesawra"
],
["uri": "empty-title", "title": " ", "url": "https://example.com"],
["uri": "unsafe", "url": "javascript:alert(1)"],
["uri": "relative", "url": "/relative"],
[
"uri": "labelled", "title": "Labelled", "url": "https://example.org",
"labels": [["src": "did:plc:labeler", "val": "porn"]]
]
]
]
return (200, try JSONSerialization.data(withJSONObject: profile))
}
defer {
StubURLProtocol.handler = nil
session.invalidateAndCancel()
}
let service = ATProtoBlueskyService(defaults: .standard, session: session)
let profile = try await service.loadProfile(actorID: "did:plc:public")
XCTAssertEqual(profile?.author.id, "did:plc:public")
XCTAssertEqual(profile?.links.map(\.title), ["My Photos!", "GitHub", "https://example.com", "Labelled"])
XCTAssertEqual(profile?.links[1].url.absoluteString, "https://github.com/geesawra")
XCTAssertEqual(profile?.links.last?.moderationLabels.first?.value, "porn")
}
func testProfileMapsBothFollowDirections() async throws {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: configuration)
var viewer: [String: Any]?
StubURLProtocol.handler = { request in
XCTAssertEqual(request.url?.path, "/xrpc/app.bsky.actor.getProfile")
var profile: [String: Any] = ["did": "did:plc:public", "handle": "public.example"]
if let viewer { profile["viewer"] = viewer }
return (200, try JSONSerialization.data(withJSONObject: profile))
}
defer {
StubURLProtocol.handler = nil
session.invalidateAndCancel()
}
let service = ATProtoBlueskyService(defaults: .standard, session: session)
for following in [false, true] {
for followedBy in [false, true] {
viewer = [:]
if following { viewer?["following"] = "at://did:plc:reader/app.bsky.graph.follow/one" }
if followedBy { viewer?["followedBy"] = "at://did:plc:public/app.bsky.graph.follow/two" }
let loadedProfile = try await service.loadProfile(actorID: "did:plc:public")
let profile = try XCTUnwrap(loadedProfile)
XCTAssertEqual(profile.isFollowing, following)
XCTAssertEqual(profile.isFollowedBy, followedBy)
}
}
viewer = nil
let profile = try await service.loadProfile(actorID: "did:plc:public")
XCTAssertEqual(profile?.isFollowedBy, false)
}
private func facetFixture(text: String) -> [[String: Any]] {
let (linkStart, linkEnd) = byteRange(of: "https://example.com", in: text)
let (mentionStart, mentionEnd) = byteRange(of: "@friend.example", in: text)
let (tagStart, tagEnd) = byteRange(of: "#sky", in: text)
let facets: [[String: Any]] = [
[
"index": ["byteStart": linkStart, "byteEnd": linkEnd],
"features": [["$type": "app.bsky.richtext.facet#link", "uri": "https://example.com"]]
],
[
"index": ["byteStart": mentionStart, "byteEnd": mentionEnd],
"features": [["$type": "app.bsky.richtext.facet#mention", "did": "did:plc:friend"]]
],
[
"index": ["byteStart": tagStart, "byteEnd": tagEnd],
"features": [["$type": "app.bsky.richtext.facet#tag", "tag": "sky"]]
],
[
"index": ["byteStart": 1, "byteEnd": 2],
"features": [["$type": "app.bsky.richtext.facet#tag", "tag": "invalid-boundary"]]
],
[
"index": ["byteStart": -1, "byteEnd": 2],
"features": [["$type": "app.bsky.richtext.facet#tag", "tag": "negative"]]
],
[
"index": ["byteStart": 0, "byteEnd": 500],
"features": [["$type": "app.bsky.richtext.facet#tag", "tag": "past-end"]]
]
]
return facets
}
}