-
Notifications
You must be signed in to change notification settings - Fork 114
/
user.js
760 lines (684 loc) · 20.7 KB
/
user.js
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
import * as JWT from './utils/jwt.js'
import { JSONResponse, notFound } from './utils/json-response.js'
import { JWT_ISSUER } from './constants.js'
import { HTTPError, PSAErrorInvalidData, PSAErrorRequiredData, PSAErrorResourceNotFound, RangeNotSatisfiableError } from './errors.js'
import { getTagValue, hasPendingTagProposal, hasTag } from './utils/tags.js'
import {
NO_READ_OR_WRITE,
READ_WRITE,
READ_ONLY,
maintenanceHandler
} from './maintenance.js'
import { pagination } from './utils/pagination.js'
import { toPinStatusResponse } from './pins.js'
import { INVALID_REQUEST_ID, REQUIRED_REQUEST_ID, validateSearchParams } from './utils/psa.js'
import { magicLinkBypassForE2ETestingInTestmode } from './magic.link.js'
import { CustomerNotFound, getPaymentSettings, initializeBillingForNewUser, isStoragePriceName, savePaymentSettings } from './utils/billing.js'
/**
* @typedef {{ _id: string, issuer: string, name?: string, email?: string }} User
* @typedef {{ _id: string, name: string }} AuthToken
* @typedef {{ user: User, authToken?: AuthToken }} Auth
* @typedef {Request & { auth: Auth }} AuthenticatedRequest
* @typedef {import('@web3-storage/db').PageRequest} PageRequest
*/
/**
* @typedef {object} IssuedAuthentication
* @property {string} issuer
* @property {string} publicAddress
* @property {string} [email]
*/
/**
* @typedef {(req: Request) => Promise<null|IssuedAuthentication>} RequestAuthenticator
*/
/**
* Context needed to perform new user registration
* @typedef {object} UserRegistrationContext
* @property {object} magic
* @property {object} magic.utils
* @property {import('./env').Env['magic']['utils']['parseAuthorizationHeader']} magic.utils.parseAuthorizationHeader
* @property {import('./env').Env['MODE']} MODE
* @property {object} db
* @property {import('./env').Env['db']['upsertUser']} db.upsertUser
* @property {import('./env').Env['db']['getUser']} db.getUser
* @property {import('./env').Env['DANGEROUSLY_BYPASS_MAGIC_AUTH']} [DANGEROUSLY_BYPASS_MAGIC_AUTH]
* @property {RequestAuthenticator} authenticateRequest
* @property {import('../src/utils/billing-types').CustomersService} customers
* @property {import('../src/utils/billing-types').SubscriptionsService} subscriptions
*/
/**
* @param {Request} request
* @param {UserRegistrationContext} env
* @returns {Promise<Response>}
*/
export async function userLoginPost (request, env) {
const user = await loginOrRegister(request, env)
return new JSONResponse({ issuer: user.issuer })
}
/**
* Controller for logging in using a magic.link token
*/
function createMagicLoginController (env, testModeBypass = magicLinkBypassForE2ETestingInTestmode) {
const createTestmodeMetadata = (token) => {
const { issuer } = testModeBypass.authenticateMagicToken(env, token)
return {
issuer,
email: 'testMode@magic.link',
publicAddress: issuer
}
}
/**
* authenticate an incoming request that has a magic.link token.
* throws error if token isnt valid
* @returns {Promise} metadata about the validated token
*/
const authenticate = async ({ token }) => {
if (testModeBypass.isEnabledForToken(env, token)) {
return createTestmodeMetadata(token)
}
await env.magic.token.validate(token)
return env.magic.users.getMetadataByToken(token)
}
return {
authenticate
}
}
/**
* @param {UserRegistrationContext} env
* @returns {RequestAuthenticator}
*/
const createMagicLinkRequestAuthenticator = (env) => async (request) => {
const auth = request.headers.get('Authorization') || ''
const token = env.magic.utils.parseAuthorizationHeader(auth)
const metadata = await (createMagicLoginController(env).authenticate({ token }))
/** @type {IssuedAuthentication} */
const authentication = {
...metadata,
issuer: metadata.issuer,
publicAddress: metadata.publicAddress
}
return authentication
}
/**
* Initialize a new user that just registered.
* @param {object} ctx
* @param {object} user
* @param {string} user.id
* @param {string} user.issuer
* @param {import('../src/utils/billing-types').UserCreationOptions} [userCreationOptions]
*/
async function initializeNewUser (ctx, user, userCreationOptions) {
await initializeBillingForNewUser(
{
customers: ctx.customers,
subscriptions: ctx.subscriptions,
user: { ...user, id: user.id.toString() },
userCreationOptions
}
)
}
/**
* @param {Request} request
* @param {UserRegistrationContext} env
* @returns {Promise<{ issuer: string }>}
*/
async function loginOrRegister (request, env) {
const data = await request.json()
const authenticateRequest = env.authenticateRequest || createMagicLinkRequestAuthenticator(env)
const metadata = await authenticateRequest(request)
if (!metadata) {
throw new Error('unable to authenticate request')
}
const { issuer, email, publicAddress } = metadata
if (!issuer || !email || !publicAddress) {
throw new Error('missing required metadata')
}
const parsed =
data.type === 'github'
? parseGitHub(data.data, metadata)
: parseMagic(metadata)
let user
// check if maintenance mode
if (env.MODE === NO_READ_OR_WRITE) {
return maintenanceHandler()
} else if (env.MODE === READ_WRITE) {
user = await env.db.upsertUser(parsed)
// initialize billing, etc, but only if the user was newly inserted
if (user.inserted) {
await initializeNewUser(
env,
{ ...user, id: user.id },
{ name: parsed.name, email: parsed.email }
)
}
} else if (env.MODE === READ_ONLY) {
user = await env.db.getUser(parsed.issuer, {})
} else {
throw new Error('Unknown maintenance mode')
}
return user
}
/**
* @param {import('@magic-ext/oauth').OAuthRedirectResult} data
* @param {IssuedAuthentication} magicMetadata
* @returns {import('@web3-storage/db/db-client-types').UpsertUserInput}
*/
function parseGitHub ({ oauth }, { issuer, email, publicAddress }) {
return {
name: oauth.userInfo.name || '',
picture: oauth.userInfo.picture || '',
issuer: issuer ?? '',
email: email ?? '',
github: oauth.userHandle,
publicAddress
}
}
/**
* @param {IssuedAuthentication} magicMetadata
* @returns {import('@web3-storage/db/db-client-types').UpsertUserInput}
*/
function parseMagic ({ issuer, email, publicAddress }) {
const name = email?.split('@')[0]
return {
name: name ?? '',
issuer,
email: email ?? '',
publicAddress
}
}
/**
* Create a new auth key.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
* @returns {Promise<Response>}
*/
export async function userTokensPost (request, env) {
const { name } = await request.json()
if (!name || typeof name !== 'string') {
throw Object.assign(new Error('invalid name'), { status: 400 })
}
const { _id, issuer } = request.auth.user
const sub = issuer
const iss = JWT_ISSUER
const secret = await JWT.sign({ sub, iss, iat: Date.now(), name }, env.SALT)
const key = await env.db.createKey({
// @ts-ignore
user: _id,
name,
secret
})
return new JSONResponse(key, { status: 201 })
}
/**
* Retrieve user account data.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userAccountGet (request, env) {
const [usedStorage, storageLimitBytes] = await Promise.all([
// @ts-ignore
env.db.getStorageUsed(request.auth.user._id),
// @ts-ignore
env.db.getUserTagValue(request.auth.user._id, 'StorageLimitBytes')
])
return new JSONResponse({
usedStorage,
storageLimitBytes
})
}
/**
* Retrieve user info
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userInfoGet (request, env) {
const user = await env.db.getUser(request.auth.user.issuer, {
includeTags: true,
// @ts-ignore
includeTagProposals: true
})
return new JSONResponse({
info: {
...user,
tags: {
HasAccountRestriction: hasTag(user, 'HasAccountRestriction', 'true'),
HasDeleteRestriction: hasTag(user, 'HasDeleteRestriction', 'true'),
HasPsaAccess: hasTag(user, 'HasPsaAccess', 'true'),
HasSuperHotAccess: hasTag(user, 'HasSuperHotAccess', 'true'),
StorageLimitBytes: getTagValue(user, 'StorageLimitBytes', '')
},
tagProposals: {
HasAccountRestriction: hasPendingTagProposal(user, 'HasAccountRestriction'),
HasDeleteRestriction: hasPendingTagProposal(user, 'HasDeleteRestriction'),
HasPsaAccess: hasPendingTagProposal(user, 'HasPsaAccess'),
HasSuperHotAccess: hasPendingTagProposal(user, 'HasSuperHotAccess'),
StorageLimitBytes: hasPendingTagProposal(user, 'StorageLimitBytes')
}
}
})
}
/**
* Post a new user request.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userRequestPost (request, env) {
const user = request.auth.user
const { tagName, requestedTagValue, userProposalForm } = await request.json()
// @ts-ignore
const res = await env.db.createUserRequest(
user._id,
tagName,
requestedTagValue,
userProposalForm
)
try {
notifySlack(user, tagName, requestedTagValue, userProposalForm, env)
} catch (e) {
console.error('Failed to notify Slack: ', e)
}
return new JSONResponse(res)
}
/**
* Retrieve user auth tokens.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userTokensGet (request, env) {
const tokens = await env.db.listKeys(request.auth.user._id)
return new JSONResponse(tokens)
}
/**
* Delete a user auth token. This actually raises a tombstone rather than
* deleting it entirely.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userTokensDelete (request, env) {
// @ts-ignore
const res = await env.db.deleteKey(request.auth.user._id, request.params.id)
return new JSONResponse(res)
}
/**
* Retrieve a page of user uploads.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userUploadsGet (request, env) {
const requestUrl = new URL(request.url)
const { searchParams } = requestUrl
const pageRequest = pagination(searchParams)
let data
try {
// @ts-ignore
data = await env.db.listUploads(request.auth.user._id, pageRequest)
} catch (err) {
// @ts-ignore
if (err.code === 'RANGE_NOT_SATISFIABLE_ERROR_DB') {
throw new RangeNotSatisfiableError()
}
throw err
}
const headers = { Count: data.count }
if (pageRequest.size != null) {
headers.Size = pageRequest.size // Deprecated, use Link header instead.
}
// @ts-ignore
if (pageRequest.page != null) {
// @ts-ignore
headers.Page = pageRequest.page // Deprecated, use Link header instead.
}
const link = getLinkHeader({
url: requestUrl.pathname,
pageRequest,
items: data.uploads,
count: data.count
})
if (link) {
headers.Link = link
}
// @ts-ignore
return new JSONResponse(data.uploads, { headers })
}
/**
* Generates a HTTP `Link` header for the given page request and data.
*
* @param {Object} args
* @param {string|URL} args.url Base URL
* @param {PageRequest} args.pageRequest Details for the current page of data
* @param {Array<{ created: string }>} args.items Page items
* @param {number} args.count Total items available
*/
function getLinkHeader ({ url, pageRequest, items, count }) {
const rels = []
if ('before' in pageRequest) {
const { size } = pageRequest
if (items.length === size) {
const oldest = items[items.length - 1]
// @ts-ignore
const nextParams = new URLSearchParams({ size, before: oldest.created })
rels.push(`<${url}?${nextParams}>; rel="next"`)
}
} else if ('page' in pageRequest) {
const { size, page } = pageRequest
// @ts-ignore
const pages = Math.ceil(count / size)
if (page < pages) {
// @ts-ignore
const nextParams = new URLSearchParams({ size, page: page + 1 })
rels.push(`<${url}?${nextParams}>; rel="next"`)
}
// @ts-ignore
const lastParams = new URLSearchParams({ size, page: pages })
rels.push(`<${url}?${lastParams}>; rel="last"`)
// @ts-ignore
const firstParams = new URLSearchParams({ size, page: 1 })
rels.push(`<${url}?${firstParams}>; rel="first"`)
if (page > 1) {
// @ts-ignore
const prevParams = new URLSearchParams({ size, page: page - 1 })
rels.push(`<${url}?${prevParams}>; rel="previous"`)
}
} else {
throw new Error('unknown page request type')
}
return rels.join(', ')
}
/**
* Retrieve a single user upload.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userUploadGet (request, env) {
// @ts-ignore
const cid = request.params.cid
let res
try {
// @ts-ignore
res = await env.db.getUpload(cid, request.auth.user._id)
} catch (error) {
return notFound()
}
return new JSONResponse(res)
}
/**
* Delete an user upload. This actually raises a tombstone rather than
* deleting it entirely.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userUploadsDelete (request, env) {
// @ts-ignore
const cid = request.params.cid
const user = request.auth.user._id
// @ts-ignore
const res = await env.db.deleteUpload(user, cid)
if (res) {
return new JSONResponse(res)
}
throw new HTTPError('Upload not found', 404)
}
/**
* Renames a user's upload.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userUploadsRename (request, env) {
const user = request.auth.user._id
// @ts-ignore
const { cid } = request.params
const { name } = await request.json()
// @ts-ignore
const res = await env.db.renameUpload(user, cid, name)
return new JSONResponse(res)
}
/**
* List a user's pins regardless of the token used.
* As we don't want to scope the Pinning Service API to users
* we need a new endpoint as an umbrella.
*
* @param {AuthenticatedRequest} request
* @param {import('./env').Env} env
*/
export async function userPinsGet (request, env) {
const requestUrl = new URL(request.url)
const { searchParams } = requestUrl
const pageRequest = pagination(searchParams)
const urlParams = new URLSearchParams(requestUrl.search)
const params = Object.fromEntries(urlParams)
const psaParams = validateSearchParams(params)
if (psaParams.error) {
throw psaParams.error
}
const tokens = (await env.db.listKeys(request.auth.user._id, { includeDeleted: true })).map((key) => key._id)
let pinRequests
try {
// @ts-ignore
pinRequests = await env.db.listPsaPinRequests(tokens, {
...psaParams.data,
limit: pageRequest.size,
// @ts-ignore
offset: pageRequest.size * (pageRequest.page - 1)
})
} catch (err) {
// @ts-ignore
if (err.code === 'RANGE_NOT_SATISFIABLE_ERROR_DB') {
throw new RangeNotSatisfiableError()
}
throw err
}
const pins = pinRequests.results.map((pinRequest) => toPinStatusResponse(pinRequest))
const headers = {
Count: pinRequests.count
}
if (pageRequest.size != null) {
headers.Size = pageRequest.size // Deprecated, use Link header instead.
}
// @ts-ignore
if (pageRequest.page != null) {
// @ts-ignore
headers.Page = pageRequest.page // Deprecated, use Link header instead.
}
const link = getLinkHeader({
url: requestUrl.pathname,
pageRequest,
items: pinRequests.results,
count: pinRequests.count
})
if (link) {
headers.Link = link
}
return new JSONResponse({
count: pinRequests.count,
results: pins
// @ts-ignore
}, { headers })
}
/**
* List a user's pins regardless of the token used.
* As we don't want to scope the Pinning Service API to users
* we need a new endpoint as an umbrella.
*
* @param {import('./user').AuthenticatedRequest} request
* @param {import('./env').Env} env
* @param {import('./index').Ctx} ctx
* @return {Promise<JSONResponse>}
*/
export async function userPinDelete (request, env, ctx) {
// @ts-ignore
const requestId = request.params?.requestId
if (!requestId) {
throw new PSAErrorRequiredData(REQUIRED_REQUEST_ID)
}
if (typeof requestId !== 'string') {
throw new PSAErrorInvalidData(INVALID_REQUEST_ID)
}
// TODO: Improve me, it is un-optimal to get the tokens in a separate request to the db.
const tokens = (await env.db.listKeys(request.auth.user._id, { includeDeleted: true })).map((key) => key._id)
try {
// Update deleted_at (and updated_at) timestamp for the pin request.
await env.db.deletePsaPinRequest(requestId, tokens)
} catch (e) {
console.error(e)
throw new PSAErrorResourceNotFound()
}
return new JSONResponse({}, { status: 202 })
}
/**
* @param {string} userProposalForm
* @param {string} tagName
* @param {string} requestedTagValue
*/
const notifySlack = async (
user,
tagName,
requestedTagValue,
userProposalForm,
env
) => {
const webhookUrl = env.SLACK_USER_REQUEST_WEBHOOK_URL
if (!webhookUrl) {
return
}
let form
try {
form = JSON.parse(userProposalForm)
} catch (e) {
console.error('Failed to parse user request form: ', e)
return
}
globalThis.fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
text: `
>*Username*
>${user.name}
>
>*Email*
>${user.email}
>
>*User Id*
>${user._id}
>
>*Requested Tag Name*
>${tagName}
>
>*Requested Tag Value*
>${tagName === 'StorageLimitBytes' && requestedTagValue === '' ? '1TiB' : requestedTagValue}
>${form
.map(
({ label, value }) => `
>*${label}*
>${value}
>`
)
.join('')}
`
})
})
}
/**
* Get a user's payment settings.
*
* @param {AuthenticatedRequest} request
* @param {Pick<BillingEnv, 'billing'|'customers'|'subscriptions'>} env
*/
export async function userPaymentGet (request, env) {
const userPaymentSettings = await getPaymentSettings({
billing: env.billing,
customers: env.customers,
subscriptions: env.subscriptions,
user: { ...request.auth.user, id: request.auth.user._id }
})
if (userPaymentSettings instanceof Error) {
switch (userPaymentSettings.code) {
case (new CustomerNotFound().code):
return new JSONResponse({
message: `Unexpected error fetching payment settings: ${userPaymentSettings.code}`
}, { status: 500 })
default: // unexpected error
throw userPaymentSettings
}
}
return new JSONResponse({
...userPaymentSettings,
subscription: userPaymentSettings.subscription
})
}
/**
* @typedef {import('./utils/billing-types.js').BillingEnv} BillingEnv
*/
/**
* Save a user's payment settings.
*
* @param {AuthenticatedRequest} request
* @param {Pick<BillingEnv, 'billing'|'customers'|'subscriptions'>} env
*/
export async function userPaymentPut (request, env) {
const requestBody = await request.json()
const paymentMethodId = requestBody?.paymentMethod?.id
if (typeof paymentMethodId !== 'string') {
throw Object.assign(new Error('Invalid payment method'), { status: 400 })
}
const subscriptionInput = requestBody?.subscription
if (typeof subscriptionInput !== 'object') {
throw Object.assign(new Error(`subscription must be an object, but got ${typeof subscriptionInput}`), { status: 400 })
}
const subscriptionStorageInput = subscriptionInput?.storage
if (!(typeof subscriptionStorageInput === 'object' || subscriptionStorageInput === null)) {
throw Object.assign(new Error('subscription.storage must be an object or null'), { status: 400 })
}
if (subscriptionStorageInput && typeof subscriptionStorageInput.price !== 'string') {
throw Object.assign(new Error('subscription.storage.price must be a string'), { status: 400 })
}
const storagePrice = subscriptionStorageInput?.price
if (storagePrice && !isStoragePriceName(storagePrice)) {
return new JSONResponse(new Error('invalid .subscription.storage.price'), {
status: 400
})
}
const subscriptionStorage = storagePrice
? { price: storagePrice }
: null
const paymentMethod = { id: paymentMethodId }
await savePaymentSettings(
{
billing: env.billing,
customers: env.customers,
user: { ...request.auth.user, id: request.auth.user._id },
subscriptions: env.subscriptions
},
{
paymentMethod,
subscription: {
storage: subscriptionStorage
}
},
{
name: request.auth.user.name,
email: request.auth.user.email
}
)
const userPaymentSettingsUrl = '/user/payment'
const savePaymentSettingsResponse = {
location: userPaymentSettingsUrl
}
return new JSONResponse(savePaymentSettingsResponse, {
status: 202,
headers: {
location: userPaymentSettingsUrl
}
})
}