-
Notifications
You must be signed in to change notification settings - Fork 33
/
routes.ts
277 lines (254 loc) · 7.57 KB
/
routes.ts
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
import assert from 'node:assert'
import path from 'node:path'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { OAuthResolverError } from '@atproto/oauth-client-node'
import { isValidHandle } from '@atproto/syntax'
import { TID } from '@atproto/common'
import { Agent } from '@atproto/api'
import express from 'express'
import { getIronSession } from 'iron-session'
import type { AppContext } from '#/index'
import { home } from '#/pages/home'
import { login } from '#/pages/login'
import { env } from '#/lib/env'
import { page } from '#/lib/view'
import * as Status from '#/lexicon/types/xyz/statusphere/status'
import * as Profile from '#/lexicon/types/app/bsky/actor/profile'
type Session = { did: string }
// Helper function for defining routes
const handler =
(fn: express.Handler) =>
async (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
try {
await fn(req, res, next)
} catch (err) {
next(err)
}
}
// Helper function to get the Atproto Agent for the active session
async function getSessionAgent(
req: IncomingMessage,
res: ServerResponse<IncomingMessage>,
ctx: AppContext
) {
const session = await getIronSession<Session>(req, res, {
cookieName: 'sid',
password: env.COOKIE_SECRET,
})
if (!session.did) return null
try {
const oauthSession = await ctx.oauthClient.restore(session.did)
return oauthSession ? new Agent(oauthSession) : null
} catch (err) {
ctx.logger.warn({ err }, 'oauth restore failed')
await session.destroy()
return null
}
}
export const createRouter = (ctx: AppContext) => {
const router = express.Router()
// Static assets
router.use('/public', express.static(path.join(__dirname, 'pages', 'public')))
// OAuth metadata
router.get(
'/client-metadata.json',
handler((_req, res) => {
return res.json(ctx.oauthClient.clientMetadata)
})
)
// OAuth callback to complete session creation
router.get(
'/oauth/callback',
handler(async (req, res) => {
const params = new URLSearchParams(req.originalUrl.split('?')[1])
try {
const { session } = await ctx.oauthClient.callback(params)
const clientSession = await getIronSession<Session>(req, res, {
cookieName: 'sid',
password: env.COOKIE_SECRET,
})
assert(!clientSession.did, 'session already exists')
clientSession.did = session.did
await clientSession.save()
} catch (err) {
ctx.logger.error({ err }, 'oauth callback failed')
return res.redirect('/?error')
}
return res.redirect('/')
})
)
// Login page
router.get(
'/login',
handler(async (_req, res) => {
return res.type('html').send(page(login({})))
})
)
// Login handler
router.post(
'/login',
handler(async (req, res) => {
// Validate
const handle = req.body?.handle
if (typeof handle !== 'string' || !isValidHandle(handle)) {
return res.type('html').send(page(login({ error: 'invalid handle' })))
}
// Initiate the OAuth flow
try {
const url = await ctx.oauthClient.authorize(handle, {
scope: 'atproto transition:generic',
})
return res.redirect(url.toString())
} catch (err) {
ctx.logger.error({ err }, 'oauth authorize failed')
return res.type('html').send(
page(
login({
error:
err instanceof OAuthResolverError
? err.message
: "couldn't initiate login",
})
)
)
}
})
)
// Logout handler
router.post(
'/logout',
handler(async (req, res) => {
const session = await getIronSession<Session>(req, res, {
cookieName: 'sid',
password: env.COOKIE_SECRET,
})
await session.destroy()
return res.redirect('/')
})
)
// Homepage
router.get(
'/',
handler(async (req, res) => {
// If the user is signed in, get an agent which communicates with their server
const agent = await getSessionAgent(req, res, ctx)
// Fetch data stored in our SQLite
const statuses = await ctx.db
.selectFrom('status')
.selectAll()
.orderBy('indexedAt', 'desc')
.limit(10)
.execute()
const myStatus = agent
? await ctx.db
.selectFrom('status')
.selectAll()
.where('authorDid', '=', agent.assertDid)
.orderBy('indexedAt', 'desc')
.executeTakeFirst()
: undefined
// Map user DIDs to their domain-name handles
const didHandleMap = await ctx.resolver.resolveDidsToHandles(
statuses.map((s) => s.authorDid)
)
if (!agent) {
// Serve the logged-out view
return res.type('html').send(page(home({ statuses, didHandleMap })))
}
// Fetch additional information about the logged-in user
const { data: profileRecord } = await agent.com.atproto.repo.getRecord({
repo: agent.assertDid,
collection: 'app.bsky.actor.profile',
rkey: 'self',
})
const profile =
Profile.isRecord(profileRecord.value) &&
Profile.validateRecord(profileRecord.value).success
? profileRecord.value
: {}
// Serve the logged-in view
return res.type('html').send(
page(
home({
statuses,
didHandleMap,
profile,
myStatus,
})
)
)
})
)
// "Set status" handler
router.post(
'/status',
handler(async (req, res) => {
// If the user is signed in, get an agent which communicates with their server
const agent = await getSessionAgent(req, res, ctx)
if (!agent) {
return res
.status(401)
.type('html')
.send('<h1>Error: Session required</h1>')
}
// Construct & validate their status record
const rkey = TID.nextStr()
const record = {
$type: 'xyz.statusphere.status',
status: req.body?.status,
createdAt: new Date().toISOString(),
}
if (!Status.validateRecord(record).success) {
return res
.status(400)
.type('html')
.send('<h1>Error: Invalid status</h1>')
}
let uri
try {
// Write the status record to the user's repository
const res = await agent.com.atproto.repo.putRecord({
repo: agent.assertDid,
collection: 'xyz.statusphere.status',
rkey,
record,
validate: false,
})
uri = res.data.uri
} catch (err) {
ctx.logger.warn({ err }, 'failed to write record')
return res
.status(500)
.type('html')
.send('<h1>Error: Failed to write record</h1>')
}
try {
// Optimistically update our SQLite
// This isn't strictly necessary because the write event will be
// handled in #/firehose/ingestor.ts, but it ensures that future reads
// will be up-to-date after this method finishes.
await ctx.db
.insertInto('status')
.values({
uri,
authorDid: agent.assertDid,
status: record.status,
createdAt: record.createdAt,
indexedAt: new Date().toISOString(),
})
.execute()
} catch (err) {
ctx.logger.warn(
{ err },
'failed to update computed view; ignoring as it should be caught by the firehose'
)
}
return res.redirect('/')
})
)
return router
}