forked from evanp/onepage.pub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
3102 lines (2910 loc) · 101 KB
/
index.mjs
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express'
import sqlite3 from 'sqlite3'
import passport from 'passport'
import LocalStrategy from 'passport-local'
import * as fsp from 'node:fs/promises'
import fs from 'node:fs'
import https from 'https'
import wrap from 'express-async-handler'
import createError from 'http-errors'
import { nanoid } from 'nanoid'
import { expressjwt } from 'express-jwt'
import jwt from 'jsonwebtoken'
import { promisify } from 'util'
import crypto from 'crypto'
import session from 'express-session'
import querystring from 'node:querystring'
import multer from 'multer'
import mime from 'mime'
import path from 'path'
import { tmpdir } from 'os'
import { isSSRFSafeURL } from 'ssrfcheck'
import page from './modules/page.mjs'
import logger from './modules/logger.mjs'
import Server from './modules/server.mjs'
import Database from './modules/database.mjs'
import User from './modules/user.mjs'
import limiter from './modules/rate-limit.mjs'
import actorRoutes from './routes/actor.mjs'
import helpRoutes from './routes/help.mjs'
import feedbackRoutes from './routes/feedback.mjs'
import settingsRoutes from './routes/settings.mjs'
import registerRoutes from './routes/register.mjs'
import loginRoutes from './routes/login.mjs'
import inboxRoutes from './routes/inbox.mjs'
// Configuration
const DATABASE = process.env.OPP_DATABASE
const HOSTNAME = process.env.OPP_HOSTNAME
const PORT = process.env.OPP_PORT
const KEY = process.env.OPP_KEY
const CERT = process.env.OPP_CERT
const SESSION_SECRET = process.env.OPP_SESSION_SECRET
const BLOCK_LIST = process.env.OPP_BLOCK_LIST
export const ORIGIN = ((PORT === 443) ? `https://${HOSTNAME}` : `https://${HOSTNAME}:${PORT}`)
const UPLOAD_DIR = process.env.OPP_UPLOAD_DIR || path.join(tmpdir(), nanoid())
const OPP_ROOT = process.cwd()
// Ensure the Upload directory exists
if (!fs.existsSync(UPLOAD_DIR)) {
fs.mkdirSync(UPLOAD_DIR)
}
// Calculated constants
const KEY_DATA = fs.readFileSync(KEY)
const CERT_DATA = fs.readFileSync(CERT)
const BLOCKED_DOMAINS = (() => {
const domains = []
if (BLOCK_LIST) {
const data = fs.readFileSync(BLOCK_LIST, { encoding: 'utf-8' })
const lines = data.split('\n')
for (const line of lines) {
const fields = line.split(',')
domains.push(fields[0])
}
}
return domains
})()
// Constants
const AS_CONTEXT = 'https://www.w3.org/ns/activitystreams'
const SEC_CONTEXT = 'https://w3id.org/security'
const BLOCKED_CONTEXT = 'https://purl.archive.org/socialweb/blocked'
const PENDING_CONTEXT = 'https://purl.archive.org/socialweb/pending'
const WEBFINGER_CONTEXT = 'https://purl.archive.org/socialweb/webfinger'
export const CONTEXT = [AS_CONTEXT, SEC_CONTEXT, BLOCKED_CONTEXT, PENDING_CONTEXT, WEBFINGER_CONTEXT]
const LD_MEDIA_TYPE = 'application/ld+json'
const ACTIVITY_MEDIA_TYPE = 'application/activity+json'
const JSON_MEDIA_TYPE = 'application/json'
const ACCEPT_HEADER = `${LD_MEDIA_TYPE};q=1.0, ${ACTIVITY_MEDIA_TYPE};q=0.9, ${JSON_MEDIA_TYPE};q=0.3`
const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public'
const PUBLIC_OBJ = { id: PUBLIC, nameMap: { en: 'Public' }, type: 'Collection' }
const MAX_PAGE_SIZE = 20
// Functions
const jwtsign = promisify(jwt.sign)
const jwtverify = promisify(jwt.verify)
const generateKeyPair = promisify(crypto.generateKeyPair)
const isString = value => typeof value === 'string' || value instanceof String
const base64URLEncode = (str) =>
str.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '')
export async function toId (value) {
if (typeof value === 'undefined') {
return null
} else if (value === null) {
return null
} else if (value instanceof ActivityObject) {
return await value.id()
} else if (typeof value === 'string') {
return value
} else if (typeof value === 'object' && 'id' in value) {
return value.id
} else {
throw new Error(`Can't convert ${JSON.stringify(value)} to id`)
}
}
export function toArray (value) {
if (typeof value === 'undefined') {
return []
} else if (value === null) {
return []
} else if (Array.isArray(value)) {
return value
} else {
return [value]
}
}
export function makeUrl (relative) {
if (relative.length > 0 && relative[0] === '/') {
relative = relative.slice(1)
}
return `${ORIGIN}/${relative}`
}
function standardEndpoints () {
return {
proxyUrl: makeUrl('endpoint/proxyUrl'),
oauthAuthorizationEndpoint: makeUrl('endpoint/oauth/authorize'),
oauthTokenEndpoint: makeUrl('endpoint/oauth/token'),
uploadMedia: makeUrl('endpoint/upload')
}
}
function domainIsBlocked (url) {
if (typeof url !== 'string') {
logger.warn(`Invalid URL: ${JSON.stringify(url)}`)
return false
}
let u = null
try {
u = new URL(url)
} catch (err) {
logger.warn(`Invalid URL: ${url}`)
return false
}
const hostname = u.host
return BLOCKED_DOMAINS.includes(hostname)
}
export function toSpki (pem) {
if (pem.startsWith('-----BEGIN RSA PUBLIC KEY-----')) {
const key = crypto.createPublicKey(pem)
pem = key.export({ type: 'spki', format: 'pem' })
}
return pem
}
export function toPkcs8 (pem) {
if (pem.startsWith('-----BEGIN RSA PRIVATE KEY-----')) {
const key = crypto.createPrivateKey(pem)
pem = key.export({ type: 'pkcs8', format: 'pem' })
}
return pem
}
export function digestBody (body) {
const hash = crypto.createHash('sha256')
hash.update(body)
return `sha-256=${hash.digest('base64')}`
}
// Classes
export class HTTPSignature {
constructor (keyId, privateKey = null, method = null, url = null, date = null, digest = null) {
if (!privateKey) {
const sigHeader = keyId
const parts = Object.fromEntries(sigHeader.split(',').map((clause) => {
const match = clause.match(/^\s*(\w+)\s*=\s*"(.*?)"\s*$/)
return [match[1], match[2].replace(/\\"/, '"')]
}))
if (!parts.keyId || !parts.headers || !parts.signature || !parts.algorithm) {
throw new Error('Invalid signature header')
}
if (parts.algorithm !== 'rsa-sha256') {
throw new Error('unsupported algorithm')
}
this.keyId = parts.keyId
this.headers = parts.headers
this.signature = parts.signature
this.algorithm = parts.algorithm
} else {
this.keyId = keyId
this.privateKey = privateKey
this.method = method
this.url = (isString(url)) ? new URL(url) : url
this.date = date
this.digest = digest
this.signature = this.sign(this.signableData())
this.header = `keyId="${this.keyId}",headers="(request-target) host date${(this.digest) ? ' digest' : ''}",signature="${this.signature.replace(/"/g, '\\"')}",algorithm="rsa-sha256"`
}
}
signableData () {
const target = (this.url.search && this.url.search.length)
? `${this.url.pathname}?${this.url.search}`
: `${this.url.pathname}`
let data = `(request-target): ${this.method.toLowerCase()} ${target}\n`
data += `host: ${this.url.host}\n`
data += `date: ${this.date}`
if (this.digest) {
data += `\ndigest: ${this.digest}`
}
return data
}
sign (data) {
const signer = crypto.createSign('sha256')
signer.update(data)
const signature = signer.sign(this.privateKey).toString('base64')
signer.end()
return signature
}
async validate (req) {
const lines = []
for (const name of this.headers.split(' ')) {
if (name === '(request-target)') {
lines.push(`(request-target): ${req.method.toLowerCase()} ${req.originalUrl}`)
} else {
const value = req.get(name)
lines.push(`${name}: ${value}`)
}
}
const data = lines.join('\n')
const url = new URL(this.keyId)
const fragment = (url.hash) ? url.hash.slice(1) : null
url.hash = ''
const ao = await ActivityObject.get(url.toString())
let publicKey = null
// Mastodon uses 'main-key' instead of 'publicKey'
if (!fragment) {
publicKey = ao
} else if (fragment in await ao.json()) {
publicKey = await ActivityObject.get(await ao.prop(fragment), ['publicKeyPem', 'owner'])
} else if (fragment === 'main-key' && 'publicKey' in await ao.json()) {
publicKey = await ActivityObject.get(await ao.prop('publicKey'), ['publicKeyPem', 'owner'])
} else {
return null
}
if (!await publicKey.json() || !await publicKey.prop('owner') || !await publicKey.prop('publicKeyPem')) {
return null
}
const verifier = crypto.createVerify('sha256')
verifier.write(data)
verifier.end()
if (verifier.verify(await publicKey.prop('publicKeyPem'), Buffer.from(this.signature, 'base64'))) {
const ownerId = await publicKey.prop('owner')
const owner = await ActivityObject.get(ownerId)
await owner.cache(ownerId, [PUBLIC])
await publicKey.cache(ownerId, [PUBLIC])
return owner
} else {
return null
}
}
static async authenticate (req, res, next) {
const sigHeader = req.headers.signature
if (sigHeader) {
const signature = new HTTPSignature(sigHeader)
const remote = await signature.validate(req)
if (remote) {
req.auth = { subject: await remote.id() }
} else {
next(new createError.Unauthorized('Invalid HTTP signature'))
}
}
next()
}
}
// This delightfully simple queue class is
// from https://dev.to/doctolib/using-promises-as-a-queue-co5
class PromiseQueue {
last = Promise.resolve(true)
count = 0
add (operation, title = null) {
return new Promise((resolve, reject) => {
this.count++
this.last = this.last
.then(() => {
return operation
})
.then((...args) => {
this.count--
resolve(...args)
})
.catch((err) => {
this.count--
reject(err)
})
})
}
}
export class ActivityObject {
#id
#json
#owner
#addressees
#complete = false
constructor (data) {
if (!data) {
throw new Error('No data provided')
} else if (isString(data)) {
this.#id = data
} else {
this.#json = data
this.#id = this.#json.id || this.#json['@id'] || null
}
}
static async makeId (type) {
const best = ActivityObject.bestType(type)
if (best) {
return makeUrl(`${best.toLowerCase()}/${nanoid()}`)
} else {
return makeUrl(`object/${nanoid()}`)
}
}
static async getJSON (id) {
if (id === PUBLIC) {
return PUBLIC_OBJ
}
const row = await db.get('SELECT data FROM object WHERE id = ?', [id])
if (!row) {
return null
} else {
return JSON.parse(row.data)
}
}
static async get (ref, props = null, subject = null) {
if (props && !Array.isArray(props)) {
throw new Error(`Invalid props: ${JSON.stringify(props)}`)
}
if (typeof ref === 'string') {
return await ActivityObject.getById(ref, subject)
} else if (typeof ref === 'object') {
if (ref instanceof ActivityObject) {
return ref
} else if (props && props.every((prop) =>
Array.isArray(prop) ? prop.some(p => p in ref) : prop in ref)) {
return new ActivityObject(ref)
} else if ('id' in ref) {
return await ActivityObject.getById(ref.id, subject)
} else {
throw new Error(`Can't get object from ${JSON.stringify(ref)}`)
}
}
}
static async getById (id, subject = null) {
if (id === PUBLIC) {
return new ActivityObject(PUBLIC_OBJ)
}
const obj = await ActivityObject.getFromDatabase(id, subject)
if (obj) {
return obj
} else if (ActivityObject.isRemoteId(id)) {
return await ActivityObject.getFromRemote(id, subject)
} else {
return null
}
}
static async getFromDatabase (id, subject = null) {
const row = await db.get('SELECT data FROM object WHERE id = ?', [id])
if (!row) {
return null
} else {
const obj = new ActivityObject(JSON.parse(row.data))
obj.#complete = true
return obj
}
}
/**
* Fetches an ActivityObject from a remote server.
*
* @param {string} id - The ID of the ActivityObject to fetch
* @param {Object} [subject=null] - The subject making the request, used for signing
* @returns {Promise<ActivityObject>} The fetched ActivityObject, or null if not found
*/
static async getFromRemote (id, subject = null) {
const date = new Date().toISOString()
const headers = {
Date: date,
Accept: ACCEPT_HEADER
}
let keyId = null
let privKey = null
if (subject && await User.isUser(subject)) {
const user = await User.fromActorId(await toId(subject))
const subjectObj = await ActivityObject.get(subject, ['publicKey'], subject)
keyId = await toId(await subjectObj.prop('publicKey'))
privKey = user.privateKey
} else {
const server = await Server.get()
keyId = server.keyId()
privKey = server.privateKey()
}
const signature = new HTTPSignature(keyId, privKey, 'GET', id, date)
headers.Signature = signature.header
if(!isSSRFSafeURL(id) && process.env.NODE_ENV === 'production') {
logger.warn(`unsafe URL: ${id}`)
return null
}
const res = await fetch(id, { headers })
if (res.status !== 200) {
logger.warn(`Error fetching ${id}: ${res.status} ${res.statusText}`)
return null
} else {
const json = await res.json()
const obj = new ActivityObject(json)
const owner = ActivityObject.guessOwner(json)
const addressees = ActivityObject.guessAddressees(json)
obj.#complete = true
await obj.cache(owner, addressees)
return obj
}
}
static guessOwner (json) {
for (const prop of ['attributedTo', 'actor', 'owner']) {
if (prop in json) {
return json[prop]
}
}
return null
}
static guessAddressees (json) {
let addressees = []
for (const prop of ['to', 'cc', 'bto', 'bcc', 'audience']) {
if (prop in json) {
addressees = addressees.concat(toArray(json[prop]))
}
}
return addressees
}
static async exists (id) {
const row = await db.get('SELECT id FROM object WHERE id = ?', [id])
return !!row
}
async json () {
if (!this.#json) {
this.#json = await ActivityObject.getJSON(this.#id)
}
return this.#json
}
async _setJson (json) {
this.#json = json
}
async _hasJson () {
return !!this.#json
}
async id () {
if (!this.#id) {
this.#id = await this.prop('id')
}
return this.#id
}
async type () {
return this.prop('type')
}
async name (lang = null) {
const [name, nameMap, summary, summaryMap] = await Promise.all([
this.prop('name'),
this.prop('nameMap'),
this.prop('summary'),
this.prop('summaryMap')
])
if (nameMap && lang in nameMap) {
return nameMap[lang]
} else if (name) {
return name
} else if (summaryMap && lang in summaryMap) {
return summaryMap[lang]
} else if (summary) {
return summary
}
}
async prop (name) {
const json = await this.json()
if (json) {
return json[name]
} else {
return null
}
}
async setProp (name, value) {
const json = await this.json()
if (json) {
json[name] = value
this.#json = json
} else {
this.#json = { [name]: value }
}
}
async expand () {
const json = await this.expanded()
this.#json = json
return this.#json
}
async isCollection () {
return ['Collection', 'OrderedCollection'].includes(await this.type())
}
async isCollectionPage () {
return ['CollectionPage', 'OrderedCollectionPage'].includes(await this.type())
}
async save (owner = null, addressees = null) {
const data = await this.compressed()
if (!owner) {
owner = ActivityObject.guessOwner(data)
}
if (!addressees) {
addressees = ActivityObject.guessAddressees(data)
}
data.type = data.type || this.defaultType()
data.id = data.id || await ActivityObject.makeId(data.type)
data.updated = new Date().toISOString()
data.published = data.published || data.updated
// self-ownership
const ownerId = (await toId(owner)) || data.id
const addresseeIds = await Promise.all(addressees.map((addressee) => toId(addressee)))
await db.run('INSERT INTO object (id, owner, data) VALUES (?, ?, ?)', [data.id, ownerId, JSON.stringify(data)])
await Promise.all(addresseeIds.map((addresseeId) =>
db.run(
'INSERT INTO addressee (objectId, addresseeId) VALUES (?, ?)',
[data.id, addresseeId]
)))
this.#id = data.id
this.#json = data
}
static #coreTypes = ['Object', 'Link', 'Activity', 'IntransitiveActivity', 'Collection',
'OrderedCollection', 'CollectionPage', 'OrderedCollectionPage']
static #activityTypes = ['Accept', 'Add', 'Announce', 'Arrive', 'Block', 'Create',
'Delete', 'Dislike', 'Flag', 'Follow', 'Ignore', 'Invite', 'Join', 'Leave',
'Like', 'Listen', 'Move', 'Offer', 'Question', 'Reject', 'Read', 'Remove',
'TentativeReject', 'TentativeAccept', 'Travel', 'Undo', 'Update', 'View']
static #actorTypes = ['Application', 'Group', 'Organization', 'Person', 'Service']
static #objectTypes = [
'Article', 'Audio', 'Document', 'Event', 'Image', 'Note', 'Page', 'Place',
'Profile', 'Relationship', 'Tombstone', 'Video']
static #linkTypes = ['Mention']
static #knownTypes = [].concat(ActivityObject.#coreTypes, ActivityObject.#activityTypes,
ActivityObject.#actorTypes, ActivityObject.#objectTypes,
ActivityObject.#linkTypes)
static bestType (type) {
const types = (Array.isArray(type)) ? type : [type]
for (const item of types) {
if (item in ActivityObject.#knownTypes) {
return item
}
}
// TODO: more filtering here?
return types[0]
}
static isActivityType (type) {
const types = (Array.isArray(type)) ? type : [type]
return types.some(t => {
return ['Activity', 'IntransitiveActivity'].includes(t) ||
ActivityObject.#activityTypes.includes(t)
})
}
static isObjectType (type) {
const types = (Array.isArray(type)) ? type : [type]
return types.some(t => {
return ['Object', 'Link', 'Collection', 'CollectionPage', 'OrderedCollection', 'OrderedCollectionPage'].includes(t) ||
ActivityObject.#objectTypes.includes(t)
})
}
async cache (owner = null, addressees = null) {
const dataId = await this.id()
const data = await this.json()
if (!owner) {
owner = ActivityObject.guessOwner(data)
}
if (!addressees) {
addressees = ActivityObject.guessAddressees(data)
}
const ownerId = await toId(owner) || data.id
const addresseeIds = await Promise.all(addressees.map((addressee) => toId(addressee)))
const qry = 'INSERT OR REPLACE INTO object (id, owner, data) VALUES (?, ?, ?)'
await db.run(qry, [dataId, ownerId, JSON.stringify(data)])
await Promise.all(addresseeIds.map(async (addresseeId) =>
await db.run(
'INSERT OR IGNORE INTO addressee (objectId, addresseeId) VALUES (?, ?)',
[dataId, await toId(addresseeId)]
)))
}
async patch (patch) {
const merged = { ...await this.json(), ...patch, updated: new Date().toISOString() }
// null means delete
for (const prop in patch) {
if (patch[prop] == null) {
delete merged[prop]
}
}
await db.run(
'UPDATE object SET data = ? WHERE id = ?',
[JSON.stringify(merged), await this.id()]
)
this.#json = merged
}
async replace (replacement) {
await db.run(
'UPDATE object SET data = ? WHERE id = ?',
[JSON.stringify(replacement), await this.id()]
)
this.#json = replacement
}
async owner () {
if (!this.#owner) {
const row = await db.get('SELECT owner FROM object WHERE id = ?', [await this.id()])
if (!row) {
this.#owner = null
} else {
this.#owner = await ActivityObject.get(row.owner)
}
}
return this.#owner
}
async addressees () {
if (!this.#addressees) {
const id = await this.id()
const rows = await db.all('SELECT addresseeId FROM addressee WHERE objectId = ?', [id])
this.#addressees = await Promise.all(rows.map((row) => ActivityObject.get(row.addresseeId)))
}
return this.#addressees
}
async canRead (subject) {
const owner = await this.owner()
const addressees = await this.addressees()
const addresseeIds = await Promise.all(addressees.map((addressee) => addressee.id()))
if (subject && typeof subject !== 'string') {
throw new Error(`Unexpected subject: ${JSON.stringify(subject)}`)
}
// subjects from blocked domains can never read
if (subject && domainIsBlocked(subject)) {
return false
}
if (subject && await User.isUser(owner)) {
const blockedProp = await owner.prop('blocked')
const blocked = new Collection(blockedProp)
if (await blocked.hasMember(subject)) {
return false
}
}
// anyone can read if it's public
if (addresseeIds.includes(PUBLIC)) {
return true
}
// otherwise, unauthenticated can't read
if (!subject) {
return false
}
// owner can always read
if (subject === await owner.id()) {
return true
}
// direct addressees can always read
if (addresseeIds.includes(subject)) {
return true
}
// if they're a member of any addressed collection
for (const addresseeId of addresseeIds) {
const obj = await ActivityObject.get(addresseeId)
if (await obj.isCollection()) {
const coll = new Collection(obj.json())
if (await coll.hasMember(subject)) {
return true
}
}
}
// Otherwise, can't read
return false
}
async canWrite (subject) {
const owner = await this.owner()
// owner can always write
if (subject === await owner.id()) {
return true
}
// TODO: if we add a way to grant write access
// to non-owner, add the check here!
return false
}
async brief () {
const object = await this.json()
if (!object) {
return await this.id()
}
let brief = {
id: await this.id(),
type: await this.type(),
icon: await this.prop('icon')
}
for (const prop of ['nameMap', 'name', 'summaryMap', 'summary']) {
if (prop in object) {
brief[prop] = object[prop]
break
}
}
switch (object.type) {
case 'Key':
brief = {
...brief,
owner: object.owner,
publicKeyPem: object.publicKeyPem
}
break
case 'Note':
brief = {
...brief,
content: object.content,
contentMap: object.contentMap
}
break
case 'OrderedCollection':
case 'Collection':
brief = {
...brief,
first: object.first
}
}
return brief
}
static #idProps = [
'actor',
'alsoKnownAs',
'attachment',
'attributedTo',
'anyOf',
'audience',
'blocked',
'cc',
'context',
'current',
'describes',
'first',
'following',
'followers',
'generator',
'href',
'icon',
'image',
'inbox',
'inReplyTo',
'instrument',
'last',
'liked',
'likes',
'location',
'next',
'object',
'oneOf',
'origin',
'outbox',
'partOf',
'pendingFollowers',
'pendingFollowing',
'prev',
'preview',
'publicKey',
'relationship',
'replies',
'result',
'shares',
'subject',
'tag',
'target',
'to',
'url'
]
static #arrayProps = [
'items',
'orderedItems'
]
async expanded () {
// force a full read
const id = await this.id()
if (!id) {
throw new Error('No id for object being expanded')
}
const ao = await ActivityObject.getById(id)
if (!ao) {
throw new Error(`No such object: ${id}`)
}
const object = await ao.json()
const toBrief = async (value) => {
if (value) {
const obj = new ActivityObject(value)
return await obj.brief()
} else {
return value
}
}
for (const prop of ActivityObject.#idProps) {
if (prop in object) {
if (Array.isArray(object[prop])) {
object[prop] = await Promise.all(object[prop].map(toBrief))
} else if (prop === 'object' && await this.needsExpandedObject()) {
object[prop] = await (new ActivityObject(object[prop])).expanded()
} else {
object[prop] = await toBrief(object[prop])
}
}
}
// Fix for PKCS1 format public keys
if ('publicKeyPem' in object) {
object.publicKeyPem = toSpki(object.publicKeyPem)
}
return object
}
async compressed () {
const object = this.json()
const toIdOrValue = async (value) => {
const id = await new ActivityObject(value).id()
if (id) {
return id
} else {
return value
}
}
for (const prop of ActivityObject.#idProps) {
if (prop in object) {
if (Array.isArray(object[prop])) {
object[prop] = await Promise.all(object[prop].map(toIdOrValue))
} else {
object[prop] = await toIdOrValue(object[prop])
}
}
}
for (const prop of ActivityObject.#arrayProps) {
if (prop in object) {
if (Array.isArray(object[prop])) {
object[prop] = await Promise.all(object[prop].map(toIdOrValue))
} else {
object[prop] = await toIdOrValue(object[prop])
}
}
}
return object
}
static async fromActivityObject (object) {
return new ActivityObject(await object.json())
}
defaultType () {
return 'Object'
}
async needsExpandedObject () {
const needs = ['Create', 'Update', 'Accept', 'Reject', 'Announce']
const type = await this.type()
const types = (Array.isArray(type)) ? type : [type]
return types.some((t) => needs.includes(t))
}
async hasProp (prop) {
const json = await this.json()
return prop in json
}
static isRemoteId (id) {
return !id.startsWith(ORIGIN)
}
static async copyAddresseeProps (to, from) {
for (const prop of ['to', 'cc', 'bto', 'bcc', 'audience']) {
const toValues = toArray(to[prop])
const fromValues = toArray(from[prop])
const merged = [...toValues, ...fromValues]
const ids = await Promise.all(merged.map((addressee) => toId(addressee)))
const unique = [...new Set(ids)]
if (unique.length > 0) {
to[prop] = unique
}
}
}
async ensureAddressee (addressee) {
const id = await toId(addressee)
const addressees = await this.addressees()
for (const a of addressees) {
if (await a.id() === id) {
return
}
}
await db.run('INSERT INTO addressee (objectId, addresseeId) VALUES (?, ?)', [await this.id(), id])
}
}
class Activity extends ActivityObject {
static async fromActivityObject (object) {
return new Activity(await object.json())
}
defaultType () {
return 'Activity'
}
async apply () {
let activity = await this.json()
const actor = await ActivityObject.guessOwner(activity)
const addressees = ActivityObject.guessAddressees(activity)
const actorObj = await ActivityObject.get(actor, ['followers', 'following', 'pendingFollowers', 'pendingFollowing'], actor)
const appliers = {
Follow: async () => {
const objectProp = await this.prop('object')
if (!objectProp) {
throw new createError.BadRequest('No object followed')
}
const other = await ActivityObject.get(objectProp, null, actorObj)
if (!other) {
throw new createError.BadRequest(`No such object to follow: ${JSON.stringify(objectProp)}`)
}
await other.expand()
const otherId = await other.id()
const following = new Collection(await actorObj.prop('following'))
if (await following.hasMember(otherId)) {
throw new createError.BadRequest('Already following')
}
const pendingFollowing = new Collection(await actorObj.prop('pendingFollowing'))
if (await pendingFollowing.find(async (act) =>