This repository was archived by the owner on Mar 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
186 lines (153 loc) · 5.36 KB
/
server.js
File metadata and controls
186 lines (153 loc) · 5.36 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
const path = require('path')
const url = require('url')
const gh = require('gh-got')
const stringify = require('json-stringify-pretty-compact')
const body = require('raw-body')
const { json, send, createError } = require('micro')
const { authenticator, authRoute } = require('plug-auth-server')
const HostChecker = require('./HostChecker')
const compileCss = require('./compileCss')
const commit = require('./commit')
const ghToken = process.env.GITHUB_TOKEN
const ghRepo = 'extplug/faerss'
if (!ghToken) {
throw new Error(`Must specify a Github API token with access to ${ghRepo} in the GITHUB_TOKEN environment variable.`)
}
if (!process.env.PLUG_EMAIL || !process.env.PLUG_PASSWORD) {
throw new Error('Must specify plug.dj account credentials in the PLUG_EMAIL and PLUG_PASSWORD environment variables.')
}
if (!process.env.SECRET) {
throw new Error('Must specify a session secret in the SECRET environment variable.')
}
const engine = authenticator({
auth: { email: process.env.PLUG_EMAIL, password: process.env.PLUG_PASSWORD },
secret: Buffer.from(process.env.SECRET, 'hex')
})
// Default room settings to use if a room host hasn't configured settings.
const emptyRoomSettings = {}
function cors (req, res) {
res.setHeader('Access-Control-Allow-Origin', '*')
const corsMethod = req.headers['access-control-request-method']
if (corsMethod) res.setHeader('Access-Control-Allow-Methods', corsMethod)
const corsHeaders = req.headers['access-control-request-headers']
if (corsHeaders) res.setHeader('Access-Control-Allow-Headers', corsHeaders)
}
function tryAuthenticate (params, req, res) {
if (params.stage === 'token') {
return engine.getAuthBlurb(params.user)
} else if (params.stage === 'verify') {
try {
return engine.verifyBlurb(params.user)
} catch (err) {
return send(res, 403, { status: 'fail', data: [err.message] })
}
}
return send(res, 400, { status: 'fail', data: ['invalid stage'] })
}
const hostChecker = new HostChecker()
function assertUserIsHost (room, user) {
return hostChecker.push({ room, user })
}
function getCommitMessage(room, user, message) {
return `[${room}] ${message}\n\nhttps://plug.dj/${room}`
}
function saveRoomSettings (room, user, settings) {
return commit(user, getCommitMessage(room, user, 'Update room settings.'), [
{ path: `${room}/settings.json`, content: stringify(settings) }
])
}
async function saveRoomStyles (room, user, cssText) {
const result = await compileCss(cssText)
return commit(user, getCommitMessage(room, user, 'Update room styles.'), [
{ path: `${room}/style.css`, content: cssText },
{ path: `${room}/style.min.css`, content: result.css },
])
}
async function getRoomFile (room, filename) {
const url = `repos/${ghRepo}/contents/${room}/${filename}`
const { body } = await gh(url, { token: ghToken })
return Buffer.from(body.content, 'base64').toString('utf8')
}
async function getHistory (room) {
const url = `repos/${ghRepo}/commits`
const { body } = await gh(url, {
token: ghToken,
query: { path: room }
})
function getUserId (user) {
return parseInt(user.email.replace(/^user\.(\d+)@extplug\.com$/, '$1'), 10)
}
return body.map((change) => ({
id: change.sha,
message: change.commit.message,
user: getUserId(change.commit.author),
time: new Date(change.commit.author.date).getTime()
}))
}
const parseUrl = (reqUrl) => {
const parts = url.parse(reqUrl)
const ext = path.extname(parts.pathname)
const roomName = parts.pathname.slice(1)
if (ext) {
Object.assign(parts, {
ext,
roomName: path.parse(roomName).name
})
} else {
Object.assign(parts, { roomName: roomName })
}
if (/\/history$/.test(parts.roomName)) {
parts.action = 'history'
parts.roomName = parts.roomName.split('/')[0]
}
return parts
}
module.exports = async (req, res) => {
cors(req, res)
if (req.method === 'OPTIONS') {
return send(res, 204, null)
}
if (req.url === '/auth') {
const params = await json(req)
return tryAuthenticate(params, req, res)
}
const { ext, roomName, query, action } = parseUrl(req.url)
if (!roomName) {
return send(res, 404, null)
}
if (req.method === 'PUT') {
const authHeader = req.headers.authorization
if (!/^JWT /.test(authHeader)) {
throw new Error('No authentication token received')
}
const user = await engine.verifyToken(authHeader.slice(4))
await assertUserIsHost(roomName, user)
if (ext === '.css') {
const css = await body(req, { encoding: 'utf-8' })
const result = await saveRoomStyles(roomName, user, css)
return send(res, 200, result)
}
if (ext && ext !== '.json') {
throw createError(403, 'You can only store CSS and JSON files.')
}
const params = await json(req)
const result = await saveRoomSettings(roomName, user, params)
return send(res, 200, result)
}
if (req.method === 'GET') {
if (action === 'history') {
return getHistory(roomName)
}
if (ext === '.css') {
res.setHeader('content-type', 'text/css')
return getRoomFile(roomName,
// reanna.css?source returns the full source. Otherwise, return the
// minified css.
query === 'source' ? 'style.css' : 'style.min.css')
}
if (ext && ext !== '.json') {
throw createError(404, 'Not Found')
}
return getRoomFile(roomName, 'settings.json').then(JSON.parse)
}
}