bluesky.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /**
  2. * @node bluesky
  3. * @name Bluesky
  4. * @category integration
  5. * @version 1.0.0
  6. * @description Post to Bluesky over the AT Protocol, with links, tags and mentions made clickable
  7. * @icon at-sign
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. credentialId: {
  13. type: 'string',
  14. title: 'Account Credential',
  15. description: 'A basic credential whose username is the handle, such as name.bsky.social, and whose password is an app password created under Settings, App Passwords. Never your account password',
  16. dynamicOptions: {
  17. source: 'credentials',
  18. filter: { type: ['basic'] }
  19. }
  20. },
  21. service: {
  22. type: 'string',
  23. title: 'Service',
  24. description: 'Address of the PDS holding the account. Only change this for a self-hosted server',
  25. default: 'https://bsky.social'
  26. },
  27. operation: {
  28. type: 'string',
  29. title: 'Operation',
  30. enum: ['post', 'delete'],
  31. default: 'post',
  32. description: 'post publishes a new entry, delete removes one this account owns'
  33. },
  34. text: {
  35. type: 'string',
  36. title: 'Text',
  37. description: 'The post body, up to 300 graphemes. Supports {{variable}} interpolation',
  38. format: 'textarea'
  39. },
  40. detectFacets: {
  41. type: 'boolean',
  42. title: 'Detect Links, Tags and Mentions',
  43. description: 'Find URLs, #hashtags and @handles in the text and mark them up so Bluesky renders them as links. Each mention costs one extra request to resolve the handle',
  44. default: true
  45. },
  46. languages: {
  47. type: 'string',
  48. title: 'Languages',
  49. description: 'Comma separated language codes for the post, such as en or en,hu. Leave empty to send none',
  50. default: 'en'
  51. },
  52. replyTo: {
  53. type: 'string',
  54. title: 'Reply To',
  55. description: 'An at:// URI of a post to reply to. The node looks up its thread root itself'
  56. },
  57. uri: {
  58. type: 'string',
  59. title: 'Post URI',
  60. description: 'The at:// URI of the post to remove, for the delete operation'
  61. },
  62. timeout: {
  63. type: 'number',
  64. title: 'Timeout (ms)',
  65. default: 30000
  66. }
  67. },
  68. required: ['credentialId']
  69. };
  70. const inputSchema = {
  71. type: 'object',
  72. properties: {
  73. data: { type: 'any' }
  74. }
  75. };
  76. const outputSchema = {
  77. type: 'object',
  78. properties: {
  79. uri: { type: 'string', description: 'at:// URI of the post that was created or removed' },
  80. cid: { type: 'string', description: 'Content id of the created post' },
  81. url: { type: 'string', description: 'Browsable https://bsky.app address of the created post' },
  82. handle: { type: 'string', description: 'Handle the post was made as' },
  83. did: { type: 'string', description: 'DID of the posting account' }
  84. }
  85. };
  86. // Facet ranges are UTF-8 byte offsets, while JavaScript indexes UTF-16 code
  87. // units. Any emoji or accented character ahead of a link shifts the two apart,
  88. // and a facet built from string indexes then highlights the wrong span.
  89. function utf8Length(text) {
  90. let bytes = 0;
  91. for (let i = 0; i < text.length; i++) {
  92. const code = text.charCodeAt(i);
  93. if (code < 0x80) {
  94. bytes += 1;
  95. } else if (code < 0x800) {
  96. bytes += 2;
  97. } else if (code >= 0xd800 && code <= 0xdbff) {
  98. bytes += 4;
  99. i++;
  100. } else {
  101. bytes += 3;
  102. }
  103. }
  104. return bytes;
  105. }
  106. function byteRange(text, start, length) {
  107. const byteStart = utf8Length(text.substring(0, start));
  108. return {
  109. byteStart: byteStart,
  110. byteEnd: byteStart + utf8Length(text.substring(start, start + length))
  111. };
  112. }
  113. function readCredential(credentialId) {
  114. const auth = smartbotic.credentials.get(credentialId);
  115. if (!auth || auth.success !== true) {
  116. throw new Error('Bluesky: could not read the account credential: ' +
  117. ((auth && auth.error) || 'unknown error'));
  118. }
  119. const value = auth.headerValue || '';
  120. if (value.indexOf('Basic ') !== 0) {
  121. throw new Error('Bluesky: the credential must be a basic one, holding the handle as ' +
  122. 'its username and an app password as its password');
  123. }
  124. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  125. const separator = decoded.indexOf(':');
  126. if (separator < 1) {
  127. throw new Error('Bluesky: the credential is malformed, expected a username and a password');
  128. }
  129. const identifier = decoded.substring(0, separator);
  130. const password = decoded.substring(separator + 1);
  131. if (!identifier || !password) {
  132. throw new Error('Bluesky: the credential needs both a handle and an app password');
  133. }
  134. return { identifier: identifier, password: password };
  135. }
  136. function call(options) {
  137. const response = smartbotic.http.request(options);
  138. let body = response.data;
  139. if (typeof body === 'string' && body.length > 0) {
  140. try {
  141. body = JSON.parse(body);
  142. } catch (e) {
  143. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  144. throw new Error('Bluesky: ' + options.what + ' returned HTTP ' + response.status +
  145. ' with a body that is not JSON: ' + snippet);
  146. }
  147. }
  148. if (response.status < 200 || response.status >= 300) {
  149. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  150. throw new Error('Bluesky: ' + options.what + ' failed: ' + detail);
  151. }
  152. return body || {};
  153. }
  154. function createSession(service, credential, timeout) {
  155. return call({
  156. method: 'POST',
  157. url: service + '/xrpc/com.atproto.server.createSession',
  158. headers: { 'Content-Type': 'application/json' },
  159. body: JSON.stringify({
  160. identifier: credential.identifier,
  161. password: credential.password
  162. }),
  163. timeout: timeout,
  164. what: 'sign in'
  165. });
  166. }
  167. // at://did:plc:xyz/app.bsky.feed.post/3k2a4b
  168. function parseAtUri(uri, what) {
  169. const match = String(uri || '').match(/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/);
  170. if (!match) {
  171. throw new Error('Bluesky: ' + what + ' must be an at:// URI like ' +
  172. 'at://did:plc:example/app.bsky.feed.post/3k2a4b, got "' + uri + '"');
  173. }
  174. return { repo: match[1], collection: match[2], rkey: match[3] };
  175. }
  176. function findLinks(text) {
  177. const found = [];
  178. const pattern = /https?:\/\/[^\s]+/g;
  179. let match;
  180. while ((match = pattern.exec(text)) !== null) {
  181. // A URL that ends a sentence swallows the punctuation, and the shortened
  182. // link then 404s. Trailing characters that cannot end a real URL go back
  183. // to the sentence - but a closing bracket is only punctuation when it
  184. // has no opener inside the URL, or every Wikipedia link ending in
  185. // "_(disambiguation)" loses its last character.
  186. let value = match[0];
  187. while (value.length > 0) {
  188. const last = value.charAt(value.length - 1);
  189. if ('.,;:!?\'"'.indexOf(last) !== -1) {
  190. value = value.substring(0, value.length - 1);
  191. continue;
  192. }
  193. const opener = last === ')' ? '(' : last === ']' ? '[' : last === '}' ? '{' : '';
  194. if (opener !== '') {
  195. const opened = value.split(opener).length - 1;
  196. const closed = value.split(last).length - 1;
  197. if (closed > opened) {
  198. value = value.substring(0, value.length - 1);
  199. continue;
  200. }
  201. }
  202. break;
  203. }
  204. if (value.length === 0) {
  205. continue;
  206. }
  207. const range = byteRange(text, match.index, value.length);
  208. found.push({
  209. index: range,
  210. features: [{ $type: 'app.bsky.richtext.facet#link', uri: value }]
  211. });
  212. }
  213. return found;
  214. }
  215. function findTags(text) {
  216. const found = [];
  217. const pattern = /(^|\s)#([^\s#]+)/g;
  218. let match;
  219. while ((match = pattern.exec(text)) !== null) {
  220. const tag = match[2].replace(/[.,;:!?]+$/, '');
  221. if (tag.length === 0) {
  222. continue;
  223. }
  224. const start = match.index + match[1].length;
  225. const range = byteRange(text, start, tag.length + 1);
  226. found.push({
  227. index: range,
  228. features: [{ $type: 'app.bsky.richtext.facet#tag', tag: tag }]
  229. });
  230. }
  231. return found;
  232. }
  233. function findMentions(text, service, timeout) {
  234. const found = [];
  235. const pattern = /(^|\s)@([a-zA-Z0-9][a-zA-Z0-9-]*(?:\.[a-zA-Z0-9-]+)+)/g;
  236. let match;
  237. while ((match = pattern.exec(text)) !== null) {
  238. const handle = match[2].replace(/[.,;:!?]+$/, '');
  239. if (handle.indexOf('.') === -1) {
  240. continue;
  241. }
  242. let resolved;
  243. try {
  244. resolved = call({
  245. method: 'GET',
  246. url: service + '/xrpc/com.atproto.identity.resolveHandle?handle=' +
  247. encodeURIComponent(handle),
  248. timeout: timeout,
  249. what: 'resolving @' + handle
  250. });
  251. } catch (e) {
  252. // An unknown handle is ordinary text, not a failure. Posting it as
  253. // plain text is what the author sees in the composer anyway.
  254. smartbotic.log.info('Bluesky: @' + handle + ' did not resolve, leaving it as text');
  255. continue;
  256. }
  257. if (!resolved || !resolved.did) {
  258. continue;
  259. }
  260. const start = match.index + match[1].length;
  261. const range = byteRange(text, start, handle.length + 1);
  262. found.push({
  263. index: range,
  264. features: [{ $type: 'app.bsky.richtext.facet#mention', did: resolved.did }]
  265. });
  266. }
  267. return found;
  268. }
  269. function buildReply(service, token, replyTo, timeout) {
  270. const parent = parseAtUri(replyTo, 'Reply To');
  271. const record = call({
  272. method: 'GET',
  273. url: service + '/xrpc/com.atproto.repo.getRecord?repo=' + encodeURIComponent(parent.repo) +
  274. '&collection=' + encodeURIComponent(parent.collection) +
  275. '&rkey=' + encodeURIComponent(parent.rkey),
  276. headers: { 'Authorization': 'Bearer ' + token },
  277. timeout: timeout,
  278. what: 'reading the post being replied to'
  279. });
  280. if (!record.uri || !record.cid) {
  281. throw new Error('Bluesky: the post at ' + replyTo + ' could not be read');
  282. }
  283. const parentRef = { uri: record.uri, cid: record.cid };
  284. // Replying to a reply must point at the thread root, not at the post being
  285. // answered, or the reply hangs outside the thread.
  286. const existingRoot = record.value && record.value.reply && record.value.reply.root;
  287. const root = existingRoot && existingRoot.uri && existingRoot.cid
  288. ? { uri: existingRoot.uri, cid: existingRoot.cid }
  289. : parentRef;
  290. return { root: root, parent: parentRef };
  291. }
  292. async function execute(config, input, context) {
  293. const operation = config.operation || 'post';
  294. const service = (config.service || 'https://bsky.social').replace(/\/+$/, '');
  295. const timeout = Number(config.timeout) || 30000;
  296. if (!config.credentialId) {
  297. throw new Error('Bluesky: an account credential is required');
  298. }
  299. const credential = readCredential(config.credentialId);
  300. const session = createSession(service, credential, timeout);
  301. if (!session.accessJwt || !session.did) {
  302. throw new Error('Bluesky: sign in returned no session for ' + credential.identifier);
  303. }
  304. const token = session.accessJwt;
  305. if (operation === 'delete') {
  306. const target = parseAtUri(config.uri, 'Post URI');
  307. if (target.repo !== session.did && target.repo !== session.handle) {
  308. throw new Error('Bluesky: ' + config.uri + ' does not belong to ' +
  309. session.handle + ', and only your own posts can be deleted');
  310. }
  311. call({
  312. method: 'POST',
  313. url: service + '/xrpc/com.atproto.repo.deleteRecord',
  314. headers: {
  315. 'Authorization': 'Bearer ' + token,
  316. 'Content-Type': 'application/json'
  317. },
  318. body: JSON.stringify({
  319. repo: session.did,
  320. collection: target.collection,
  321. rkey: target.rkey
  322. }),
  323. timeout: timeout,
  324. what: 'deleting the post'
  325. });
  326. smartbotic.log.info('Bluesky: deleted ' + config.uri);
  327. return {
  328. uri: config.uri,
  329. handle: session.handle,
  330. did: session.did
  331. };
  332. }
  333. const text = config.text;
  334. if (typeof text !== 'string' || text.length === 0) {
  335. throw new Error('Bluesky: post text is required');
  336. }
  337. const record = {
  338. $type: 'app.bsky.feed.post',
  339. text: text,
  340. createdAt: new Date().toISOString()
  341. };
  342. const languages = String(config.languages || '')
  343. .split(',')
  344. .map(function (code) { return code.trim(); })
  345. .filter(function (code) { return code.length > 0; });
  346. if (languages.length > 0) {
  347. record.langs = languages;
  348. }
  349. if (config.detectFacets !== false) {
  350. const facets = findLinks(text)
  351. .concat(findTags(text))
  352. .concat(findMentions(text, service, timeout));
  353. if (facets.length > 0) {
  354. facets.sort(function (left, right) {
  355. return left.index.byteStart - right.index.byteStart;
  356. });
  357. record.facets = facets;
  358. }
  359. }
  360. if (config.replyTo) {
  361. record.reply = buildReply(service, token, config.replyTo, timeout);
  362. }
  363. const created = call({
  364. method: 'POST',
  365. url: service + '/xrpc/com.atproto.repo.createRecord',
  366. headers: {
  367. 'Authorization': 'Bearer ' + token,
  368. 'Content-Type': 'application/json'
  369. },
  370. body: JSON.stringify({
  371. repo: session.did,
  372. collection: 'app.bsky.feed.post',
  373. record: record
  374. }),
  375. timeout: timeout,
  376. what: 'creating the post'
  377. });
  378. if (!created.uri) {
  379. throw new Error('Bluesky: the post was accepted but no URI came back');
  380. }
  381. const rkey = created.uri.substring(created.uri.lastIndexOf('/') + 1);
  382. const facetCount = record.facets ? record.facets.length : 0;
  383. smartbotic.log.info('Bluesky: posted as ' + session.handle + ' with ' + facetCount + ' facets');
  384. return {
  385. uri: created.uri,
  386. cid: created.cid || '',
  387. url: 'https://bsky.app/profile/' + session.handle + '/post/' + rkey,
  388. handle: session.handle,
  389. did: session.did
  390. };
  391. }
  392. module.exports = { configSchema, inputSchema, outputSchema, execute };