-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
217 lines (192 loc) · 7.48 KB
/
index.js
File metadata and controls
217 lines (192 loc) · 7.48 KB
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
/**
* ActivityPub Plugin for JSS
* Adds federation support via the ActivityPub protocol
*/
import { webfinger } from 'microfed'
import { loadOrCreateKeypair, getKeyId } from './keys.js'
import { initStore } from './store.js'
import { createInboxHandler } from './routes/inbox.js'
import { createOutboxHandler, createOutboxPostHandler } from './routes/outbox.js'
import { createCollectionsHandler } from './routes/collections.js'
import { createActorHandler } from './routes/actor.js'
import { createAppsHandler, createVerifyCredentialsHandler, createInstanceHandler } from './routes/mastodon.js'
import { createAuthorizeHandler, createAuthorizePostHandler, createTokenHandler } from './routes/oauth.js'
// Shared state for actor handler (accessed by server.js)
let sharedActorHandler = null
export function getActorHandler() { return sharedActorHandler }
/**
* ActivityPub Fastify plugin
* @param {FastifyInstance} fastify
* @param {object} options
* @param {string} options.username - Default username for single-user mode
* @param {string} options.displayName - Display name
* @param {string} options.summary - Bio/description
* @param {string} options.nostrPubkey - Nostr public key (hex) for identity linking
*/
export async function activityPubPlugin(fastify, options = {}) {
// Initialize storage and keypair
const keypair = loadOrCreateKeypair()
await initStore()
// Store config for handlers
const config = {
keypair,
username: options.username || 'me',
displayName: options.displayName || options.username || 'Anonymous',
summary: options.summary || '',
nostrPubkey: options.nostrPubkey || null
}
// Decorate fastify with AP config
fastify.decorate('apConfig', config)
// Helper to detect protocol from proxy headers
const getProtocol = (request) => {
// Check X-Forwarded-Proto first
let protocol = request.headers['x-forwarded-proto']
if (!protocol) {
// Cloudflare uses cf-visitor: {"scheme":"https"}
const cfVisitor = request.headers['cf-visitor']
if (cfVisitor) {
try {
const parsed = JSON.parse(cfVisitor)
protocol = parsed.scheme
} catch { /* ignore */ }
}
}
// If still no protocol and hostname looks like a public domain, assume https
if (!protocol && request.hostname && !request.hostname.match(/^(localhost|127\.|192\.168\.|10\.)/)) {
protocol = 'https'
}
return protocol || request.protocol
}
// Helper to build actor ID from request
const getActorId = (request) => {
const protocol = getProtocol(request)
const host = request.headers['x-forwarded-host'] || request.hostname
return `${protocol}://${host}/profile/card#me`
}
// Helper to get base URL
const getBaseUrl = (request) => {
const protocol = getProtocol(request)
const host = request.headers['x-forwarded-host'] || request.hostname
return `${protocol}://${host}`
}
// WebFinger endpoint
fastify.get('/.well-known/webfinger', async (request, reply) => {
const resource = request.query.resource
if (!resource) {
return reply.code(400).send({ error: 'Missing resource parameter' })
}
const parsed = webfinger.parseResource(resource)
if (!parsed) {
return reply.code(400).send({ error: 'Invalid resource format' })
}
// Check if this is our user
const host = request.headers['x-forwarded-host'] || request.hostname
if (parsed.domain !== host) {
return reply.code(404).send({ error: 'Not found' })
}
// For now, accept any username and map to /profile/card#me
// In multi-user mode, we'd look up the user
const baseUrl = getBaseUrl(request)
const actorUrl = `${baseUrl}/profile/card#me`
const profileUrl = `${baseUrl}/profile/card`
const response = webfinger.createResponse(
`${parsed.username}@${parsed.domain}`,
actorUrl,
{ profileUrl }
)
// Add remoteStorage link relation
response.links.push({
rel: 'http://tools.ietf.org/id/draft-dejong-remotestorage',
href: `${baseUrl}/storage/${config.username}/`,
properties: {
'http://remotestorage.io/spec/version': 'draft-dejong-remotestorage-22',
'http://tools.ietf.org/html/rfc6749#section-4.2': `${baseUrl}/oauth/authorize`,
'http://tools.ietf.org/html/rfc6750#section-2.3': 'Bearer'
}
})
return reply
.header('Content-Type', 'application/jrd+json')
.header('Access-Control-Allow-Origin', '*')
.send(response)
})
// NodeInfo discovery (for Mastodon compatibility)
fastify.get('/.well-known/nodeinfo', async (request, reply) => {
const baseUrl = getBaseUrl(request)
return reply
.header('Content-Type', 'application/json')
.send({
links: [
{
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1',
href: `${baseUrl}/.well-known/nodeinfo/2.1`
}
]
})
})
fastify.get('/.well-known/nodeinfo/2.1', async (request, reply) => {
const { getPostCount } = await import('./store.js')
return reply
.header('Content-Type', 'application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.1#"')
.send({
version: '2.1',
software: {
name: 'jss',
version: '0.0.99',
repository: 'https://github.com/JavaScriptSolidServer/JavaScriptSolidServer'
},
protocols: ['activitypub', 'solid'],
services: { inbound: [], outbound: [] },
usage: {
users: { total: 1, activeMonth: 1, activeHalfyear: 1 },
localPosts: getPostCount()
},
openRegistrations: true,
metadata: {
nodeName: config.displayName,
nodeDescription: 'SAND Stack: Solid + ActivityPub + Nostr + DID'
}
})
})
// Actor endpoint - expose handler for profile/card AP requests
const actorHandler = createActorHandler(config, keypair)
// Store actorHandler in shared state for use by server-level hook
sharedActorHandler = actorHandler
// Inbox endpoint
const inboxHandler = createInboxHandler(config, keypair)
fastify.post('/inbox', inboxHandler)
fastify.post('/profile/card/inbox', inboxHandler)
// Outbox endpoint
const outboxHandler = createOutboxHandler(config, keypair)
const outboxPostHandler = createOutboxPostHandler(config, keypair)
fastify.get('/profile/card/outbox', outboxHandler)
fastify.post('/profile/card/outbox', outboxPostHandler)
// Followers/Following collections
const collectionsHandler = createCollectionsHandler(config)
fastify.get('/profile/card/followers', (req, reply) => collectionsHandler(req, reply, 'followers'))
fastify.get('/profile/card/following', (req, reply) => collectionsHandler(req, reply, 'following'))
// Mastodon-compatible API endpoints
fastify.post('/api/v1/apps', createAppsHandler())
fastify.get('/api/v1/accounts/verify_credentials', createVerifyCredentialsHandler(config))
fastify.get('/api/v1/instance', createInstanceHandler(config))
// OAuth 2.0 authorize/token flow (Mastodon clients, remoteStorage, third-party panes)
fastify.get('/oauth/authorize', createAuthorizeHandler())
fastify.post('/oauth/authorize', {
config: {
rateLimit: {
max: 10,
timeWindow: '1 minute',
keyGenerator: (request) => request.ip
}
}
}, createAuthorizePostHandler())
fastify.post('/oauth/token', {
config: {
rateLimit: {
max: 10,
timeWindow: '1 minute',
keyGenerator: (request) => request.ip
}
}
}, createTokenHandler())
}
export default activityPubPlugin