-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtools.ts
More file actions
285 lines (241 loc) · 8.08 KB
/
tools.ts
File metadata and controls
285 lines (241 loc) · 8.08 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
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
import sanitizeHtml from 'sanitize-html'
import type { Request, Response } from 'express'
import { PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3'
import _ from 'underscore'
import he from 'he'
import {
filterDeepProperties,
getDefaultData,
getS3AndParams,
streamToString
} from '../services/utils.js'
import { S3FileNotFoundError } from '../services/errors.js'
import {
ConfigVersions,
CreateConfigRequest,
SanitizedFields,
SaveUserConfigRequest
} from './types.js'
import { getSession } from '@/services/session.js'
export const getDefault = async (_: Request, res: Response) => {
try {
const data = await getDefaultData()
res.status(200).send(JSON.parse(data))
} catch (error) {
console.log(error)
res.status(500).send('An error occurred when fetching data')
}
}
export const createUserConfig = async (req: Request, res: Response) => {
try {
const data: CreateConfigRequest = req.body
const tag = data.version || data.tag
if (!data?.walletAddress) {
throw 'Wallet address is required'
}
const walletAddress = decodeURIComponent(`https://${data.walletAddress}`)
const cookieHeader = req.headers.cookie
const session = await getSession(cookieHeader)
const validForWallet = session?.get('validForWallet')
if (!session || validForWallet !== walletAddress) {
throw 'Grant confirmation is required'
}
const defaultData = await getDefaultData()
const defaultDataContent: ConfigVersions['default'] =
JSON.parse(defaultData).default
defaultDataContent.walletAddress = walletAddress
sanitizeConfigFields({ ...defaultDataContent, tag })
const { s3, params } = getS3AndParams(data.walletAddress)
let fileContentString = '{}'
try {
// existing config
const s3data = await s3.send(new GetObjectCommand(params))
// Convert the file stream to a string
fileContentString = await streamToString(
s3data.Body as NodeJS.ReadableStream
)
} catch (error) {
const err = error as Error
if (err.name === 'NoSuchKey') {
// file / config not found, continue with defaults
} else {
console.log(error)
res.status(500).send('An error occurred while fetching data')
return
}
}
let currentData = JSON.parse(fileContentString)
if (currentData?.default) {
currentData = Object.assign(filterDeepProperties(currentData), {
[tag]: defaultDataContent
})
} else {
currentData = Object.assign(
{ default: currentData },
{
[tag]: defaultDataContent
}
)
}
const fileContent = JSON.stringify(currentData)
const extendedParams = { ...params, Body: fileContent }
// save json to file
await s3.send(new PutObjectCommand(extendedParams))
res.status(200).send(currentData)
} catch (error) {
console.log(error)
res.status(500).send('An error occurred when fetching data')
}
}
export const saveUserConfig = async (req: Request, res: Response) => {
try {
const data: SaveUserConfigRequest = req.body
const cookieHeader = req.headers.cookie
const session = await getSession(cookieHeader)
const validForWallet = session?.get('validForWallet')
if (!data.walletAddress) {
throw 'Wallet address is required'
}
if (!session || validForWallet !== data.walletAddress) {
throw 'Grant confirmation is required'
}
const { s3, params } = getS3AndParams(data.walletAddress)
const fullConfig: ConfigVersions = JSON.parse(data?.fullconfig)
// sanitize all versions/tags in the config
Object.keys(fullConfig).forEach((key) => {
if (typeof fullConfig[key] === 'object') {
fullConfig[key] = sanitizeConfigFields(fullConfig[key])
}
})
const filteredData = filterDeepProperties(fullConfig)
const fileContent = JSON.stringify(filteredData)
const extendedParams = { ...params, Body: fileContent }
await s3.send(new PutObjectCommand(extendedParams))
res.status(200).send(filteredData)
} catch (err) {
console.log(err)
res.status(500).send('An error occurred when saving data')
}
}
export const getUserConfig = async (req: Request, res: Response) => {
try {
const id = req.params.id
if (!id) {
throw new S3FileNotFoundError('Wallet address is required')
}
// ensure we have all keys w default values, user config will overwrite values that exist in saved json
const defaultData = await getDefaultData()
const { s3, params } = getS3AndParams(id)
const data = await s3.send(new GetObjectCommand(params))
// Convert the file stream to a string
const fileContentString = await streamToString(
data.Body as NodeJS.ReadableStream
)
let fileContent = Object.assign(
JSON.parse(defaultData),
...[JSON.parse(fileContentString)]
)
fileContent = filterDeepProperties(fileContent)
res.status(200).send(fileContent)
} catch (error) {
const err = error as Error
if (err.name === 'NoSuchKey') {
// file / config not found, serve default
const defaultData = await getDefaultData()
res.status(200).send(defaultData)
} else {
console.log(error)
res.status(500).send('An error occurred while fetching data')
}
}
}
export const getUserConfigByTag = async (req: Request, res: Response) => {
try {
const id = req.params.id
const tag = req.params.tag ?? 'default'
if (!id) {
throw new S3FileNotFoundError('Wallet address is required')
}
// ensure we have all keys w default values, user config will overwrite values that exist in saved json
const defaultDataResp = await getDefaultData()
const defaultData = JSON.parse(defaultDataResp)?.default
const { s3, params } = getS3AndParams(id)
const data = await s3.send(new GetObjectCommand(params))
// Convert the file stream to a string
const fileContentString = await streamToString(
data.Body as NodeJS.ReadableStream
)
const userConfig = JSON.parse(fileContentString)
const selectedConfig = userConfig[tag] ?? defaultData
const fileContent = Object.assign(defaultData, ...[selectedConfig])
res.status(200).send(fileContent)
} catch (error) {
const err = error as Error
if (err.name === 'NoSuchKey') {
// file / config not found, serve default
const defaultData = await getDefaultData()
res.status(200).send(defaultData)
} else {
console.log(error)
res.status(500).send('An error occurred while fetching data')
}
}
}
const sanitizeConfigFields = <T extends Partial<SanitizedFields>>(
config: T
): T => {
const textFields: Array<keyof SanitizedFields> = [
'bannerTitleText',
'widgetTitleText',
'widgetButtonText',
'buttonText',
'buttonDescriptionText',
'walletAddress',
'tag',
'version'
]
const htmlFields: Array<keyof SanitizedFields> = [
'bannerDescriptionText',
'widgetDescriptionText'
]
for (const field of textFields) {
const value = config[field]
if (typeof value === 'string' && value) {
const decoded = he.decode(value)
const sanitizedText = sanitizeHtml(value, {
allowedTags: [],
allowedAttributes: {},
textFilter(text) {
return he.decode(text)
}
})
if (sanitizedText !== decoded) {
throw new Error(`HTML not allowed in field: ${field}`)
}
config[field] = sanitizedText
}
}
for (const field of htmlFields) {
if (typeof config[field] === 'string' && config[field]) {
const decoded = he.decode(config[field].replace(/ /g, '').trim())
const sanitizedHTML = sanitizeHtml(decoded, {
allowedTags: [],
allowedAttributes: {},
allowProtocolRelative: false
})
const decodedSanitized = he.decode(sanitizedHTML)
// compare decoded versions to check for malicious content
if (decodedSanitized !== decoded) {
throw new Error(`Invalid HTML in field: ${field}`)
}
config[field] = decodedSanitized
}
}
return config
}
export default {
getDefault,
getUserConfig,
createUserConfig,
saveUserConfig
}