bluesky.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. images: {
  58. type: 'array',
  59. title: 'Images',
  60. description: 'Up to four images to attach. Each is uploaded from the file store before the post is created',
  61. items: {
  62. type: 'object',
  63. properties: {
  64. fileId: {
  65. type: 'string',
  66. title: 'Stored File ID',
  67. description: 'Id of the image in the file store'
  68. },
  69. alt: {
  70. type: 'string',
  71. title: 'Alt Text',
  72. description: 'Description of the image for people using a screen reader. Bluesky shows an ALT badge when this is set'
  73. }
  74. }
  75. }
  76. },
  77. uri: {
  78. type: 'string',
  79. title: 'Post URI',
  80. description: 'The at:// URI of the post to remove, for the delete operation'
  81. },
  82. timeout: {
  83. type: 'number',
  84. title: 'Timeout (ms)',
  85. default: 30000
  86. }
  87. },
  88. required: ['credentialId']
  89. };
  90. const inputSchema = {
  91. type: 'object',
  92. properties: {
  93. data: { type: 'any' }
  94. }
  95. };
  96. const outputSchema = {
  97. type: 'object',
  98. properties: {
  99. uri: { type: 'string', description: 'at:// URI of the post that was created or removed' },
  100. cid: { type: 'string', description: 'Content id of the created post' },
  101. url: { type: 'string', description: 'Browsable https://bsky.app address of the created post' },
  102. handle: { type: 'string', description: 'Handle the post was made as' },
  103. did: { type: 'string', description: 'DID of the posting account' },
  104. imageCount: { type: 'number', description: 'How many images were attached' }
  105. }
  106. };
  107. // Facet ranges are UTF-8 byte offsets, while JavaScript indexes UTF-16 code
  108. // units. Any emoji or accented character ahead of a link shifts the two apart,
  109. // and a facet built from string indexes then highlights the wrong span.
  110. function utf8Length(text) {
  111. let bytes = 0;
  112. for (let i = 0; i < text.length; i++) {
  113. const code = text.charCodeAt(i);
  114. if (code < 0x80) {
  115. bytes += 1;
  116. } else if (code < 0x800) {
  117. bytes += 2;
  118. } else if (code >= 0xd800 && code <= 0xdbff) {
  119. bytes += 4;
  120. i++;
  121. } else {
  122. bytes += 3;
  123. }
  124. }
  125. return bytes;
  126. }
  127. function byteRange(text, start, length) {
  128. const byteStart = utf8Length(text.substring(0, start));
  129. return {
  130. byteStart: byteStart,
  131. byteEnd: byteStart + utf8Length(text.substring(start, start + length))
  132. };
  133. }
  134. function readCredential(credentialId) {
  135. const auth = smartbotic.credentials.get(credentialId);
  136. if (!auth || auth.success !== true) {
  137. throw new Error('Bluesky: could not read the account credential: ' +
  138. ((auth && auth.error) || 'unknown error'));
  139. }
  140. const value = auth.headerValue || '';
  141. if (value.indexOf('Basic ') !== 0) {
  142. throw new Error('Bluesky: the credential must be a basic one, holding the handle as ' +
  143. 'its username and an app password as its password');
  144. }
  145. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  146. const separator = decoded.indexOf(':');
  147. if (separator < 1) {
  148. throw new Error('Bluesky: the credential is malformed, expected a username and a password');
  149. }
  150. const identifier = decoded.substring(0, separator);
  151. const password = decoded.substring(separator + 1);
  152. if (!identifier || !password) {
  153. throw new Error('Bluesky: the credential needs both a handle and an app password');
  154. }
  155. return { identifier: identifier, password: password };
  156. }
  157. function call(options) {
  158. const response = smartbotic.http.request(options);
  159. let body = response.data;
  160. if (typeof body === 'string' && body.length > 0) {
  161. try {
  162. body = JSON.parse(body);
  163. } catch (e) {
  164. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  165. throw new Error('Bluesky: ' + options.what + ' returned HTTP ' + response.status +
  166. ' with a body that is not JSON: ' + snippet);
  167. }
  168. }
  169. if (response.status < 200 || response.status >= 300) {
  170. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  171. throw new Error('Bluesky: ' + options.what + ' failed: ' + detail);
  172. }
  173. return body || {};
  174. }
  175. function createSession(service, credential, timeout) {
  176. return call({
  177. method: 'POST',
  178. url: service + '/xrpc/com.atproto.server.createSession',
  179. headers: { 'Content-Type': 'application/json' },
  180. body: JSON.stringify({
  181. identifier: credential.identifier,
  182. password: credential.password
  183. }),
  184. timeout: timeout,
  185. what: 'sign in'
  186. });
  187. }
  188. // at://did:plc:xyz/app.bsky.feed.post/3k2a4b
  189. function parseAtUri(uri, what) {
  190. const match = String(uri || '').match(/^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/);
  191. if (!match) {
  192. throw new Error('Bluesky: ' + what + ' must be an at:// URI like ' +
  193. 'at://did:plc:example/app.bsky.feed.post/3k2a4b, got "' + uri + '"');
  194. }
  195. return { repo: match[1], collection: match[2], rkey: match[3] };
  196. }
  197. function findLinks(text) {
  198. const found = [];
  199. const pattern = /https?:\/\/[^\s]+/g;
  200. let match;
  201. while ((match = pattern.exec(text)) !== null) {
  202. // A URL that ends a sentence swallows the punctuation, and the shortened
  203. // link then 404s. Trailing characters that cannot end a real URL go back
  204. // to the sentence - but a closing bracket is only punctuation when it
  205. // has no opener inside the URL, or every Wikipedia link ending in
  206. // "_(disambiguation)" loses its last character.
  207. let value = match[0];
  208. while (value.length > 0) {
  209. const last = value.charAt(value.length - 1);
  210. if ('.,;:!?\'"'.indexOf(last) !== -1) {
  211. value = value.substring(0, value.length - 1);
  212. continue;
  213. }
  214. const opener = last === ')' ? '(' : last === ']' ? '[' : last === '}' ? '{' : '';
  215. if (opener !== '') {
  216. const opened = value.split(opener).length - 1;
  217. const closed = value.split(last).length - 1;
  218. if (closed > opened) {
  219. value = value.substring(0, value.length - 1);
  220. continue;
  221. }
  222. }
  223. break;
  224. }
  225. if (value.length === 0) {
  226. continue;
  227. }
  228. const range = byteRange(text, match.index, value.length);
  229. found.push({
  230. index: range,
  231. features: [{ $type: 'app.bsky.richtext.facet#link', uri: value }]
  232. });
  233. }
  234. return found;
  235. }
  236. function findTags(text) {
  237. const found = [];
  238. const pattern = /(^|\s)#([^\s#]+)/g;
  239. let match;
  240. while ((match = pattern.exec(text)) !== null) {
  241. const tag = match[2].replace(/[.,;:!?]+$/, '');
  242. if (tag.length === 0) {
  243. continue;
  244. }
  245. const start = match.index + match[1].length;
  246. const range = byteRange(text, start, tag.length + 1);
  247. found.push({
  248. index: range,
  249. features: [{ $type: 'app.bsky.richtext.facet#tag', tag: tag }]
  250. });
  251. }
  252. return found;
  253. }
  254. function findMentions(text, service, timeout) {
  255. const found = [];
  256. const pattern = /(^|\s)@([a-zA-Z0-9][a-zA-Z0-9-]*(?:\.[a-zA-Z0-9-]+)+)/g;
  257. let match;
  258. while ((match = pattern.exec(text)) !== null) {
  259. const handle = match[2].replace(/[.,;:!?]+$/, '');
  260. if (handle.indexOf('.') === -1) {
  261. continue;
  262. }
  263. let resolved;
  264. try {
  265. resolved = call({
  266. method: 'GET',
  267. url: service + '/xrpc/com.atproto.identity.resolveHandle?handle=' +
  268. encodeURIComponent(handle),
  269. timeout: timeout,
  270. what: 'resolving @' + handle
  271. });
  272. } catch (e) {
  273. // An unknown handle is ordinary text, not a failure. Posting it as
  274. // plain text is what the author sees in the composer anyway.
  275. smartbotic.log.info('Bluesky: @' + handle + ' did not resolve, leaving it as text');
  276. continue;
  277. }
  278. if (!resolved || !resolved.did) {
  279. continue;
  280. }
  281. const start = match.index + match[1].length;
  282. const range = byteRange(text, start, handle.length + 1);
  283. found.push({
  284. index: range,
  285. features: [{ $type: 'app.bsky.richtext.facet#mention', did: resolved.did }]
  286. });
  287. }
  288. return found;
  289. }
  290. // Bluesky rejects anything over a megabyte on the blob upload, and the message
  291. // it returns names a byte count rather than the picture, so the check happens
  292. // here where the file is still identifiable.
  293. const MAX_IMAGE_BYTES = 1000000;
  294. const MAX_IMAGES = 4;
  295. function uploadImages(service, token, images, timeout) {
  296. if (images.length > MAX_IMAGES) {
  297. throw new Error('Bluesky: a post takes at most ' + MAX_IMAGES + ' images, got ' + images.length);
  298. }
  299. const uploaded = [];
  300. for (const entry of images) {
  301. const fileId = entry && entry.fileId;
  302. if (!fileId) {
  303. throw new Error('Bluesky: an image entry has no stored file id');
  304. }
  305. const info = smartbotic.storage.getFileInfo(fileId);
  306. const file = smartbotic.storage.downloadFile(fileId);
  307. if (!file || file.success !== true || !file.data) {
  308. throw new Error('Bluesky: stored file ' + fileId + ' could not be read');
  309. }
  310. const mimeType = (info && info.mimeType) || 'image/jpeg';
  311. if (mimeType.indexOf('image/') !== 0) {
  312. throw new Error('Bluesky: stored file ' + fileId + ' is ' + mimeType +
  313. ', which is not an image');
  314. }
  315. // file.data is base64, so its decoded length is what the server sees.
  316. const padding = (file.data.match(/=+$/) || [''])[0].length;
  317. const size = Math.floor(file.data.length / 4) * 3 - padding;
  318. if (size > MAX_IMAGE_BYTES) {
  319. throw new Error('Bluesky: image ' + ((info && info.name) || fileId) + ' is ' +
  320. Math.round(size / 1024) + ' KB, over the ' +
  321. Math.round(MAX_IMAGE_BYTES / 1024) + ' KB limit. Resize it before posting');
  322. }
  323. const blob = call({
  324. method: 'POST',
  325. url: service + '/xrpc/com.atproto.repo.uploadBlob',
  326. headers: {
  327. 'Authorization': 'Bearer ' + token,
  328. 'Content-Type': mimeType
  329. },
  330. bodyBase64: file.data,
  331. timeout: timeout,
  332. what: 'uploading ' + ((info && info.name) || fileId)
  333. });
  334. if (!blob || !blob.blob) {
  335. throw new Error('Bluesky: the upload of ' + ((info && info.name) || fileId) +
  336. ' returned no blob reference');
  337. }
  338. uploaded.push({
  339. alt: (entry && entry.alt) || '',
  340. image: blob.blob
  341. });
  342. }
  343. return uploaded;
  344. }
  345. function buildReply(service, token, replyTo, timeout) {
  346. const parent = parseAtUri(replyTo, 'Reply To');
  347. const record = call({
  348. method: 'GET',
  349. url: service + '/xrpc/com.atproto.repo.getRecord?repo=' + encodeURIComponent(parent.repo) +
  350. '&collection=' + encodeURIComponent(parent.collection) +
  351. '&rkey=' + encodeURIComponent(parent.rkey),
  352. headers: { 'Authorization': 'Bearer ' + token },
  353. timeout: timeout,
  354. what: 'reading the post being replied to'
  355. });
  356. if (!record.uri || !record.cid) {
  357. throw new Error('Bluesky: the post at ' + replyTo + ' could not be read');
  358. }
  359. const parentRef = { uri: record.uri, cid: record.cid };
  360. // Replying to a reply must point at the thread root, not at the post being
  361. // answered, or the reply hangs outside the thread.
  362. const existingRoot = record.value && record.value.reply && record.value.reply.root;
  363. const root = existingRoot && existingRoot.uri && existingRoot.cid
  364. ? { uri: existingRoot.uri, cid: existingRoot.cid }
  365. : parentRef;
  366. return { root: root, parent: parentRef };
  367. }
  368. async function execute(config, input, context) {
  369. const operation = config.operation || 'post';
  370. const service = (config.service || 'https://bsky.social').replace(/\/+$/, '');
  371. const timeout = Number(config.timeout) || 30000;
  372. if (!config.credentialId) {
  373. throw new Error('Bluesky: an account credential is required');
  374. }
  375. const credential = readCredential(config.credentialId);
  376. const session = createSession(service, credential, timeout);
  377. if (!session.accessJwt || !session.did) {
  378. throw new Error('Bluesky: sign in returned no session for ' + credential.identifier);
  379. }
  380. const token = session.accessJwt;
  381. if (operation === 'delete') {
  382. const target = parseAtUri(config.uri, 'Post URI');
  383. if (target.repo !== session.did && target.repo !== session.handle) {
  384. throw new Error('Bluesky: ' + config.uri + ' does not belong to ' +
  385. session.handle + ', and only your own posts can be deleted');
  386. }
  387. call({
  388. method: 'POST',
  389. url: service + '/xrpc/com.atproto.repo.deleteRecord',
  390. headers: {
  391. 'Authorization': 'Bearer ' + token,
  392. 'Content-Type': 'application/json'
  393. },
  394. body: JSON.stringify({
  395. repo: session.did,
  396. collection: target.collection,
  397. rkey: target.rkey
  398. }),
  399. timeout: timeout,
  400. what: 'deleting the post'
  401. });
  402. smartbotic.log.info('Bluesky: deleted ' + config.uri);
  403. return {
  404. uri: config.uri,
  405. handle: session.handle,
  406. did: session.did
  407. };
  408. }
  409. const text = config.text;
  410. if (typeof text !== 'string' || text.length === 0) {
  411. throw new Error('Bluesky: post text is required');
  412. }
  413. const record = {
  414. $type: 'app.bsky.feed.post',
  415. text: text,
  416. createdAt: new Date().toISOString()
  417. };
  418. const languages = String(config.languages || '')
  419. .split(',')
  420. .map(function (code) { return code.trim(); })
  421. .filter(function (code) { return code.length > 0; });
  422. if (languages.length > 0) {
  423. record.langs = languages;
  424. }
  425. if (config.detectFacets !== false) {
  426. const facets = findLinks(text)
  427. .concat(findTags(text))
  428. .concat(findMentions(text, service, timeout));
  429. if (facets.length > 0) {
  430. facets.sort(function (left, right) {
  431. return left.index.byteStart - right.index.byteStart;
  432. });
  433. record.facets = facets;
  434. }
  435. }
  436. if (config.replyTo) {
  437. record.reply = buildReply(service, token, config.replyTo, timeout);
  438. }
  439. const images = Array.isArray(config.images) ? config.images : [];
  440. if (images.length > 0) {
  441. record.embed = {
  442. $type: 'app.bsky.embed.images',
  443. images: uploadImages(service, token, images, timeout)
  444. };
  445. }
  446. const created = call({
  447. method: 'POST',
  448. url: service + '/xrpc/com.atproto.repo.createRecord',
  449. headers: {
  450. 'Authorization': 'Bearer ' + token,
  451. 'Content-Type': 'application/json'
  452. },
  453. body: JSON.stringify({
  454. repo: session.did,
  455. collection: 'app.bsky.feed.post',
  456. record: record
  457. }),
  458. timeout: timeout,
  459. what: 'creating the post'
  460. });
  461. if (!created.uri) {
  462. throw new Error('Bluesky: the post was accepted but no URI came back');
  463. }
  464. const rkey = created.uri.substring(created.uri.lastIndexOf('/') + 1);
  465. const facetCount = record.facets ? record.facets.length : 0;
  466. const imageCount = record.embed ? record.embed.images.length : 0;
  467. smartbotic.log.info('Bluesky: posted as ' + session.handle + ' with ' + facetCount +
  468. ' facets and ' + imageCount + ' images');
  469. return {
  470. uri: created.uri,
  471. cid: created.cid || '',
  472. url: 'https://bsky.app/profile/' + session.handle + '/post/' + rkey,
  473. handle: session.handle,
  474. did: session.did,
  475. imageCount: imageCount
  476. };
  477. }
  478. module.exports = { configSchema, inputSchema, outputSchema, execute };