@evanp/activitypub-bot 0.41.2 → 0.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,129 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ mailto:contact@socialwebfoundation.org.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html).
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq).
128
+ Translations are available at
129
+ [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations).
@@ -24,8 +24,8 @@ const COLLECTION_TYPES = [
24
24
  export class ActivityDeliverer {
25
25
  static #QUEUE_ID = 'delivery'
26
26
  static #INTAKE_QUEUE_ID = 'intake'
27
- static #TTL_SEEN_PUBLIC = 3 * 24 * 60 * 60 * 1000 // 3 days
28
- static #MAX_SEEN_PUBLIC = 1000000
27
+ static #TTL_SEEN_PUBLIC = 6 * 60 * 60 * 1000 // 6 hours
28
+ static #MAX_SEEN_PUBLIC = 100_000
29
29
  #actorStorage
30
30
  #formatter
31
31
  #logger
@@ -915,7 +915,7 @@ export class ActivityHandler {
915
915
  actor: {
916
916
  id: this.#botId(bot),
917
917
  name: bot.fullname,
918
- type: 'Service'
918
+ type: bot.type
919
919
  },
920
920
  published: now,
921
921
  updated: now
@@ -1027,7 +1027,7 @@ export class ActivityHandler {
1027
1027
  return await as2.import({
1028
1028
  id: this.#formatter.format({ username: bot.username }),
1029
1029
  name: bot.fullname,
1030
- type: 'Service'
1030
+ type: bot.type
1031
1031
  })
1032
1032
  }
1033
1033
 
package/lib/bot.js CHANGED
@@ -64,6 +64,10 @@ export default class Bot {
64
64
  return this.#context
65
65
  }
66
66
 
67
+ get type () {
68
+ return 'Service'
69
+ }
70
+
67
71
  async onMention (object, activity) {
68
72
  ; // no-op
69
73
  }
package/lib/botcontext.js CHANGED
@@ -438,6 +438,57 @@ export class BotContext {
438
438
  return await this.#doActivity(data, distribute)
439
439
  }
440
440
 
441
+ getFollowersId () {
442
+ return this.#formatter.format({
443
+ username: this.#botId,
444
+ collection: 'followers'
445
+ })
446
+ }
447
+
448
+ async isFollower (obj) {
449
+ assert.ok(obj)
450
+ assert.equal(typeof obj, 'object')
451
+ return await this.#isInCollection('followers', obj)
452
+ }
453
+
454
+ async isFollowing (obj) {
455
+ assert.ok(obj)
456
+ assert.equal(typeof obj, 'object')
457
+ return await this.#isInCollection('following', obj)
458
+ }
459
+
460
+ async isPendingFollowing (obj) {
461
+ assert.ok(obj)
462
+ assert.equal(typeof obj, 'object')
463
+ const followId =
464
+ await this.#actorStorage.getLastActivity(this.#botId, 'Follow', obj)
465
+ if (!followId) return false
466
+ const followActivity = await this.#objectStorage.read(followId)
467
+ return await this.#isInCollection('pendingFollowing', followActivity)
468
+ }
469
+
470
+ isLocal (url) {
471
+ assert.ok(url)
472
+ assert.equal(typeof url, 'string')
473
+ return this.#formatter.isLocal(url)
474
+ }
475
+
476
+ async * followers () {
477
+ yield * this.#actorStorage.items(this.#botId, 'followers')
478
+ }
479
+
480
+ async * following () {
481
+ yield * this.#actorStorage.items(this.#botId, 'following')
482
+ }
483
+
484
+ async #isInCollection (name, obj) {
485
+ assert.ok(name)
486
+ assert.equal(typeof name, 'string')
487
+ assert.ok(obj)
488
+ assert.equal(typeof obj, 'object')
489
+ return await this.#actorStorage.isInCollection(this.#botId, name, obj)
490
+ }
491
+
441
492
  async #findInOutbox (type, obj) {
442
493
  const full = `https://www.w3.org/ns/activitystreams#${type}`
443
494
  let found = null
@@ -490,8 +541,7 @@ export class BotContext {
490
541
  nanoid: nanoid()
491
542
  }),
492
543
  actor: {
493
- id: this.#formatter.format({ username: this.#botId }),
494
- type: 'Service'
544
+ id: this.#formatter.format({ username: this.#botId })
495
545
  },
496
546
  published: now,
497
547
  updated: now
@@ -0,0 +1,86 @@
1
+ import assert from 'node:assert'
2
+
3
+ import Bot from '../bot.js'
4
+
5
+ const NS = 'https://www.w3.org/ns/activitystreams#'
6
+ const CREATE = `${NS}Create`
7
+
8
+ const DEFAULT_NAME = 'LitePubRelayClientBot'
9
+ const DEFAULT_DESCRIPTION = 'A LitePub relay client'
10
+
11
+ export default class LitePubRelayClientBot extends Bot {
12
+ #relay
13
+ #relayForwarding
14
+
15
+ constructor (username, options = {}) {
16
+ if (typeof username !== 'string') {
17
+ throw new Error('username must be a string')
18
+ }
19
+ if (typeof options !== 'object') {
20
+ throw new Error('options must be an object')
21
+ }
22
+ if (typeof options.relay !== 'string' &&
23
+ !Array.isArray(options.relay)) {
24
+ throw new Error('relay option must be a string or array')
25
+ }
26
+ super(username, {
27
+ fullname: DEFAULT_NAME,
28
+ description: DEFAULT_DESCRIPTION,
29
+ ...options
30
+ })
31
+ this.#relay = Array.isArray(options.relay)
32
+ ? options.relay
33
+ : [options.relay]
34
+ this.#relayForwarding = ('relayForwarding' in options)
35
+ ? options.relayForwarding
36
+ : true
37
+ }
38
+
39
+ get type () {
40
+ return 'Application'
41
+ }
42
+
43
+ async initialize (context) {
44
+ await super.initialize(context)
45
+ this._context.logger.info(
46
+ { relay: this.#relay },
47
+ 'Initialising relay client'
48
+ )
49
+
50
+ assert.ok(Array.isArray(this.#relay))
51
+
52
+ const toFollow = new Set(this.#relay)
53
+
54
+ for await (const actor of this._context.following()) {
55
+ if (toFollow.has(actor.id)) {
56
+ toFollow.delete(actor.id)
57
+ } else {
58
+ await this._context.unfollowActor(actor)
59
+ }
60
+ }
61
+
62
+ for (const id of toFollow) {
63
+ const actor = await this._context.getObject(id)
64
+ await this._context.followActor(actor)
65
+ }
66
+ }
67
+
68
+ async onPublic (activity) {
69
+ if (this.#relayForwarding &&
70
+ await this.#hasAnyFollower() &&
71
+ this._context.isLocal(activity.id) &&
72
+ activity.type === CREATE &&
73
+ activity.object?.first) {
74
+ await this._context.announceObject(activity.object.first)
75
+ }
76
+ }
77
+
78
+ async #hasAnyFollower () {
79
+ for await (const actor of this._context.followers()) {
80
+ if (this.#relay.includes(actor.id)) {
81
+ return true
82
+ }
83
+ }
84
+ return false
85
+ }
86
+ }
@@ -0,0 +1,96 @@
1
+ import FollowBackBot from './followback.js'
2
+
3
+ const DEFAULT_FULLNAME = 'LitePub Relay Server Bot'
4
+ const DEFAULT_DESCRIPTION = 'Implements server side of LitePub relay.'
5
+
6
+ const NS = 'https://www.w3.org/ns/activitystreams#'
7
+ const ANNOUNCE = `${NS}Announce`
8
+ const APPLICATION = `${NS}Application`
9
+
10
+ export default class LitePubRelayServer extends FollowBackBot {
11
+ #relayForwarding
12
+ constructor (username, options = {}) {
13
+ super(username, {
14
+ fullname: DEFAULT_FULLNAME,
15
+ description: DEFAULT_DESCRIPTION,
16
+ ...options
17
+ })
18
+ this.#relayForwarding = ('relayForwarding' in options)
19
+ ? options.relayForwarding
20
+ : true
21
+ }
22
+
23
+ async onFollow (actor, activity) {
24
+ await super.onFollow(actor, activity)
25
+ if (!actor.id?.endsWith('/relay')) {
26
+ this._context.logger.warn(
27
+ { actor: actor.id },
28
+ 'LitePub relay follower id does not end with /relay'
29
+ )
30
+ }
31
+ try {
32
+ const actorFull = await this._context.getObject(actor.id)
33
+ if (!this.#objectType(actorFull, APPLICATION)) {
34
+ this._context.logger.warn(
35
+ { actor: actorFull.id, actorType: actorFull.type },
36
+ 'LitePub relay follower is not an Application'
37
+ )
38
+ }
39
+ } catch (err) {
40
+ this._context.logger.warn(
41
+ { err, actor: actor.id },
42
+ 'Error loading follower in LitePubRelayServer'
43
+ )
44
+ }
45
+ }
46
+
47
+ async handleActivity (activity) {
48
+ this._context.logger.debug(
49
+ { class: this.constructor.name, activity: activity.id },
50
+ 'handling activity'
51
+ )
52
+ if (this.#objectType(activity, ANNOUNCE) &&
53
+ activity.actor?.first?.id &&
54
+ activity.object?.first?.id &&
55
+ await this._context.isFollower(activity.actor.first) &&
56
+ this.#addressedToFollowers(activity)) {
57
+ if (this.#relayForwarding) {
58
+ this._context.logger.debug(
59
+ {
60
+ class: this.constructor.name,
61
+ activity: activity.id,
62
+ actor: activity.actor.first.id,
63
+ object: activity.object.first.id
64
+ },
65
+ 'sharing object from follower'
66
+ )
67
+ await this._context.announceObject(activity.object.first)
68
+ }
69
+ return true
70
+ } else {
71
+ return false
72
+ }
73
+ }
74
+
75
+ #objectType (object, type) {
76
+ return (Array.isArray(object.type) && object.type.includes(type)) ||
77
+ (typeof object.type === 'string' && object.type === type)
78
+ }
79
+
80
+ #addressedToFollowers (activity) {
81
+ const recipients = this.#getRecipientIds(activity)
82
+ const followersId = this._context.getFollowersId()
83
+ return recipients.includes(followersId)
84
+ }
85
+
86
+ #getRecipientIds (obj) {
87
+ let r = []
88
+ for (const prop of ['to', 'cc', 'audience']) {
89
+ const val = obj.get(prop)
90
+ if (val) {
91
+ r = r.concat(Array.from(val))
92
+ }
93
+ }
94
+ return r.map(obj => obj.id)
95
+ }
96
+ }
@@ -4,7 +4,7 @@ const NS = 'https://www.w3.org/ns/activitystreams#'
4
4
  const ACCEPT = `${NS}Accept`
5
5
  const REJECT = `${NS}Reject`
6
6
 
7
- export default class RelayClientBot extends Bot {
7
+ export default class MastodonRelayClientBot extends Bot {
8
8
  #relay
9
9
  #unsubscribe
10
10
 
@@ -15,7 +15,7 @@ export default class RelayClientBot extends Bot {
15
15
  }
16
16
 
17
17
  get fullname () {
18
- return 'Relay Client Bot'
18
+ return 'Mastodon Relay Client Bot'
19
19
  }
20
20
 
21
21
  get description () {
@@ -11,9 +11,9 @@ const PUBLICS = [
11
11
  ]
12
12
  const CLIENTS = 'relay-clients'
13
13
 
14
- export default class RelayServerBot extends Bot {
14
+ export default class MastodonRelayServerBot extends Bot {
15
15
  get fullname () {
16
- return 'Relay Server Bot'
16
+ return 'Mastodon Relay Server Bot'
17
17
  }
18
18
 
19
19
  get description () {
@@ -19,62 +19,62 @@ export class DistributionWorker extends Worker {
19
19
  try {
20
20
  await this.#client.post(inbox, activityObj, username)
21
21
  this._logger.info({ activity: activity.id, inbox }, 'Delivered activity')
22
- } catch (error) {
23
- if (!error.status) {
22
+ } catch (err) {
23
+ if (!err.status) {
24
24
  this._logger.warn(
25
- { error, activity: activity.id, inbox },
25
+ { err, activity: activity.id, inbox },
26
26
  'Could not deliver activity and no HTTP status available')
27
- throw error
28
- } else if (error.status >= 300 && error.status < 400) {
27
+ throw err
28
+ } else if (err.status >= 300 && err.status < 400) {
29
29
  this._logger.warn(
30
- { error, activity: activity.id, inbox },
30
+ { err, activity: activity.id, inbox },
31
31
  'Could not deliver activity and unexpected redirect code'
32
32
  )
33
- throw error
34
- } else if (error.status >= 400 && error.status < 500) {
33
+ throw err
34
+ } else if (err.status >= 400 && err.status < 500) {
35
35
  this._logger.warn(
36
- { error, activity: activity.id, inbox },
36
+ { err, activity: activity.id, inbox },
37
37
  'Could not deliver activity due to client error'
38
38
  )
39
- if ([408, 425, 429].includes(error.status)) {
39
+ if ([408, 425, 429].includes(err.status)) {
40
40
  this._logger.debug(
41
- { error, activity: activity.id, inbox },
41
+ { err, activity: activity.id, inbox },
42
42
  'Retrying on recoverable status'
43
43
  )
44
- const recoverable = new RecoverableError(error.message)
45
- recoverable.delay = this.#retryDelay(error.headers, attempts)
44
+ const recoverable = new RecoverableError(err.message)
45
+ recoverable.delay = this.#retryDelay(err.headers, attempts)
46
46
  throw recoverable
47
47
  } else {
48
- throw error
48
+ throw err
49
49
  }
50
- } else if (error.status >= 500 && error.status < 600) {
51
- if ([501, 505, 508, 510].includes(error.status)) {
50
+ } else if (err.status >= 500 && err.status < 600) {
51
+ if ([501, 505, 508, 510].includes(err.status)) {
52
52
  this._logger.warn(
53
- { error, activity: activity.id, inbox, attempts },
53
+ { err, activity: activity.id, inbox, attempts },
54
54
  'Could not deliver activity due to unrecoverable server error'
55
55
  )
56
- throw error
56
+ throw err
57
57
  } else if (attempts >= DistributionWorker.#MAX_ATTEMPTS) {
58
58
  this._logger.warn(
59
- { error, activity: activity.id, inbox, attempts },
59
+ { err, activity: activity.id, inbox, attempts },
60
60
  'Could not deliver activity due to server error; no more attempts'
61
61
  )
62
- throw error
62
+ throw err
63
63
  } else {
64
- const recoverable = new RecoverableError(error.message)
65
- recoverable.delay = this.#retryDelay(error.headers, attempts)
64
+ const recoverable = new RecoverableError(err.message)
65
+ recoverable.delay = this.#retryDelay(err.headers, attempts)
66
66
  this._logger.warn(
67
- { error, activity: activity.id, inbox, attempts, delay: recoverable.delay },
67
+ { err, activity: activity.id, inbox, attempts, delay: recoverable.delay },
68
68
  'Could not deliver activity due to server error; will retry'
69
69
  )
70
70
  throw recoverable
71
71
  }
72
72
  } else {
73
73
  this._logger.warn(
74
- { error, activity: activity.id, inbox },
74
+ { err, activity: activity.id, inbox },
75
75
  'Could not deliver activity due to unexpected status range'
76
76
  )
77
- throw error
77
+ throw err
78
78
  }
79
79
  }
80
80
  }
package/lib/index.js CHANGED
@@ -3,6 +3,6 @@ export { default as Bot } from './bot.js'
3
3
  export { default as BotFactory } from './botfactory.js'
4
4
  export { default as OKBot } from './bots/ok.js'
5
5
  export { default as DoNothingBot } from './bots/donothing.js'
6
- export { default as RelayClientBot } from './bots/relayclient.js'
7
- export { default as RelayServerBot } from './bots/relayserver.js'
6
+ export { default as MastodonRelayClientBot } from './bots/mastodonrelayclient.js'
7
+ export { default as MastodonRelayServerBot } from './bots/mastodonrelayserver.js'
8
8
  export { default as FollowBackBot } from './bots/followback.js'
@@ -25,7 +25,7 @@ async function toLink (url, formatter, username, type) {
25
25
 
26
26
  router.get('/user/:username', async (req, res, next) => {
27
27
  const { username } = req.params
28
- const { actorStorage, keyStorage, formatter, bots, origin } = req.app.locals
28
+ const { keyStorage, formatter, bots, origin } = req.app.locals
29
29
  const bot = await BotMaker.makeBot(bots, username)
30
30
  if (!bot) {
31
31
  return next(new ProblemDetailsError(404, `User ${username} not found`))
@@ -33,12 +33,21 @@ router.get('/user/:username', async (req, res, next) => {
33
33
  const publicKeyPem = await keyStorage.getPublicKey(username)
34
34
  const acct = formatter.acct(username)
35
35
  const wf = acct.slice(5)
36
- const actor = await actorStorage.getActor(username, {
36
+ const actor = await as2.import({
37
37
  '@context': [
38
38
  'https://www.w3.org/ns/activitystreams',
39
39
  'https://w3id.org/security/v1',
40
40
  'https://purl.archive.org/socialweb/webfinger'
41
41
  ],
42
+ id: formatter.format({ username }),
43
+ type: bot.type,
44
+ preferredUsername: username,
45
+ inbox: formatter.format({ username, collection: 'inbox' }),
46
+ outbox: formatter.format({ username, collection: 'outbox' }),
47
+ followers: formatter.format({ username, collection: 'followers' }),
48
+ following: formatter.format({ username, collection: 'following' }),
49
+ liked: formatter.format({ username, collection: 'liked' }),
50
+ to: 'as:Public',
42
51
  name: bot.fullname,
43
52
  summary: bot.description,
44
53
  webfinger: wf,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evanp/activitypub-bot",
3
- "version": "0.41.2",
3
+ "version": "0.42.1",
4
4
  "description": "server-side ActivityPub bot framework",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",