/
grants.js
1169 lines (1003 loc) · 33.3 KB
/
grants.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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const Joi = require('joi')
const Netmask = require('netmask').Netmask
const l10nparser = require('accept-language-parser')
const boom = require('boom')
const bson = require('bson')
const underscore = require('underscore')
const uuidV4 = require('uuid/v4')
const wreck = require('wreck')
const {
cooldownOffset
} = require('../lib/grants')
const utils = require('bat-utils')
const braveJoi = utils.extras.joi
const braveHapi = utils.extras.hapi
const braveUtils = utils.extras.utils
const whitelist = utils.hapi.auth.whitelist
const rateLimitEnabled = process.env.NODE_ENV === 'production'
const qalist = { addresses: process.env.IP_QA_WHITELIST && process.env.IP_QA_WHITELIST.split(',') }
const claimRate = {
limit: process.env.GRANT_CLAIM_RATE ? Number(process.env.GRANT_CLAIM_RATE) : 50,
window: process.env.GRANT_CLAIM_WINDOW ? Number(process.env.GRANT_CLAIM_WINDOW) : 3 * 60 * 60
}
const captchaRate = {
limit: process.env.GRANT_CLAIM_RATE ? Number(process.env.GRANT_CLAIM_RATE) : 50,
window: process.env.GRANT_CLAIM_WINDOW ? Number(process.env.GRANT_CLAIM_WINDOW) : 3 * 60 * 60
}
if (qalist.addresses) {
qalist.authorizedAddrs = []
qalist.authorizedBlocks = []
qalist.addresses.forEach((entry) => {
if ((entry.indexOf('/') === -1) && (entry.split('.').length === 4)) return qalist.authorizedAddrs.push(entry)
qalist.authorizedBlocks.push(new Netmask(entry))
})
}
const qaOnlyP = (request) => {
const ipaddr = whitelist.ipaddr(request)
return (qalist.authorizedAddrs) && (qalist.authorizedAddrs.indexOf(ipaddr) === -1) &&
(!underscore.find(qalist.authorizedBlocks, (block) => { return block.contains(ipaddr) }))
}
const rateLimitPlugin = {
enabled: rateLimitEnabled && !qalist.addresses,
rate: (request) => captchaRate
}
const priorityValidator = Joi.number().integer().min(0).description('the promotion priority (lower is better)')
const activeValidator = Joi.boolean().optional().default(true).description('the promotion status')
const protocolVersionValidator = Joi.number().integer().min(2).description('the protocol version that the promotion will follow')
const grantTypeValidator = Joi.string().allow(['ugp', 'ads']).default('ugp').description('the type of grant to use')
const paymentIdValidator = Joi.string().guid().description('identity of the wallet')
const promotionIdValidator = Joi.string().guid().description('the promotion-identifier')
const altcurrencyValidator = braveJoi.string().altcurrencyCode().description('the grant altcurrency')
const probiValidator = braveJoi.string().numeric().description('the grant amount in probi')
const minimumReconcileTimestampValidator = Joi.number().description('time when the promotion can be reconciled')
const encodedGrantValidator = Joi.string().description('the jws encoded grant')
const grantsValidator = Joi.array().min(0).items(encodedGrantValidator).description('grants for bulk upload')
const expiryTimeValidator = Joi.number().positive().description('the time the grant expires')
const grantProviderIdValidator = Joi.string().guid().when('type', {
is: 'ads',
then: Joi.required(),
otherwise: Joi.forbidden()
})
const braveProductEnumValidator = Joi.string().valid(['browser-laptop', 'brave-core']).description('the brave product requesting the captcha')
const captchaResponseValidator = Joi.object().keys({
x: Joi.number().required(),
y: Joi.number().required()
})
const grantContentValidator = Joi.object().keys({
grantId: Joi.string().guid().required().description('the grant-identifier'),
promotionId: promotionIdValidator.required(),
altcurrency: altcurrencyValidator.required(),
probi: probiValidator.required(),
maturityTime: Joi.number().positive().required().description('the time the grant becomes redeemable'),
expiryTime: expiryTimeValidator.required()
})
const grantContentTypedValidator = grantContentValidator.keys({
type: grantTypeValidator,
providerId: grantProviderIdValidator
})
const publicGrantValidator = Joi.object().keys({
altcurrency: altcurrencyValidator.optional().default('BAT'),
expiryTime: expiryTimeValidator.optional(),
probi: probiValidator.optional()
}).unknown(true).description('grant properties')
const publicGrantTypedValidator = publicGrantValidator.keys({
type: grantTypeValidator,
providerId: grantProviderIdValidator
})
const promotionValidator = Joi.object().keys({
promotionId: promotionIdValidator.required(),
priority: priorityValidator.required(),
active: activeValidator
}).unknown(true).description('promotions for bulk upload')
const promotionsValidator = Joi.array().min(0).items(promotionValidator)
const grantsUploadValidator = Joi.object().keys({
grants: grantsValidator,
promotions: promotionsValidator
}).required().description('data for bulk upload')
const typedPromotionValidator = promotionValidator.keys({
protocolVersion: protocolVersionValidator.required(),
minimumReconcileTimestamp: minimumReconcileTimestampValidator.optional()
})
const promotionsTypedValidator = Joi.array().min(0).items(typedPromotionValidator)
const grantsUploadTypedValidator = grantsUploadValidator.keys({
grants: grantsValidator,
promotions: promotionsTypedValidator
})
const captchaHeadersValidator = Joi.object().keys({
'brave-product': braveProductEnumValidator.optional().default('browser-laptop')
}).unknown(true).description('headers')
const v2 = {}
const v3 = {}
const v4 = {}
/*
GET /v2/promotions
*/
const getPromotions = (protocolVersion) => (runtime) => async (request, reply) => {
const debug = braveHapi.debug(module, request)
const promotions = runtime.database.get('promotions', debug)
let entries, where, projection
if (qaOnlyP(request)) {
return reply(boom.notFound())
}
where = {
protocolVersion,
promotionId: { $ne: '' }
}
projection = {
sort: { priority: 1 },
fields: {
_id: 0,
batchId: 0,
timestamp: 0
}
}
entries = await promotions.find(where, projection)
reply(entries)
}
/*
GET /v3/promotions
*/
const safetynetPassthrough = (handler) => (runtime) => async (request, reply) => {
const endpoint = '/v1/attestations/safetynet'
const {
config
} = runtime
const {
captcha
} = config
const url = captcha.url + endpoint
const headers = {
'Authorization': 'Bearer ' + captcha.access_token,
'Content-Type': 'application/json'
}
const body = JSON.stringify({
token: request.headers['safetynet-token']
})
try {
await braveHapi.wreck.post(url, {
headers,
payload: body
})
await handler(runtime)(request, reply)
} catch (ex) {
try {
const errPayload = JSON.parse(ex.data.payload.toString())
return reply(boom.notFound(errPayload.message))
} catch (ex) {
runtime.captureException(ex, { req: request })
}
return reply(boom.notFound())
}
}
const promotionsGetResponseSchema = Joi.array().min(0).items(Joi.object().keys({
promotionId: Joi.string().required().description('the promotion-identifier')
}).unknown(true).description('promotion properties'))
v2.all = {
handler: getPromotions(2),
description: 'See if a v2 promotion is available',
tags: [ 'api' ],
validate: { query: {} },
response: {
schema: promotionsGetResponseSchema
}
}
v3.all = {
handler: getPromotions(3),
description: 'See if a v3 promotion is available',
tags: [ 'api' ],
validate: {},
response: {
schema: promotionsGetResponseSchema
}
}
v4.all = {
handler: getPromotions(4),
description: 'See if a v4 promotion is available',
tags: [ 'api' ],
validate: {},
response: {
schema: promotionsGetResponseSchema
}
}
/*
GET /v2/grants
GET /v3/grants
*/
// from https://github.com/opentable/accept-language-parser/blob/master/index.js#L1
const localeRegExp = /((([a-zA-Z]+(-[a-zA-Z0-9]+){0,2})|\*)(;q=[0-1](\.[0-9]+)?)?)*/g
const getGrant = (protocolVersion) => (runtime) => {
return async (request, reply) => {
// Only support requests from Chrome versions > 70
if (protocolVersion === 2) {
let userAgent = request.headers['user-agent']
let userAgentIsChrome = userAgent.split('Chrome/').length > 1
if (userAgentIsChrome) {
let chromeVersion = parseInt(userAgent.split('Chrome/')[1].substring(0, 2))
if (chromeVersion < 70) {
return reply(boom.notFound('promotion not available for browser-laptop.'))
}
}
}
const lang = request.query.lang
const paymentId = request.query.paymentId
const languages = l10nparser.parse(lang)
const query = {
active: true,
count: { $gt: 0 },
protocolVersion
}
const debug = braveHapi.debug(module, request)
const grants = runtime.database.get('grants', debug)
const promotions = runtime.database.get('promotions', debug)
const wallets = runtime.database.get('wallets', debug)
let entries, promotionIds, wallet
let walletTooYoung = false
if (qaOnlyP(request)) return reply(boom.notFound())
if (paymentId) {
promotionIds = []
wallet = await wallets.findOne({ paymentId: paymentId })
if (!wallet) return reply(boom.notFound('no such wallet: ' + paymentId))
if (wallet.grants) {
wallet.grants.forEach((grant) => { promotionIds.push(grant.promotionId) })
}
underscore.extend(query, { promotionId: { $nin: promotionIds } })
const offset = cooldownOffset()
walletTooYoung = braveUtils.createdTimestamp(wallet._id) > (new Date() - offset)
debug('offset', { offset, walletTooYoung })
}
if (protocolVersion === 4 && !paymentId) {
underscore.extend(query, { type: 'ugp' })
}
entries = await promotions.find(query)
if ((!entries) || (!entries[0])) return reply(boom.notFound('no promotions available'))
if (protocolVersion < 4) {
entries = [entries[0]]
}
const filteredPromotions = []
for (let { promotionId, type } of entries) {
const query = { promotionId }
if (type === 'ads') {
if (!wallet) {
continue
}
underscore.extend(query, { providerId: wallet.addresses.CARD_ID })
}
const counted = await grants.count(query)
if (counted !== 0 && !walletTooYoung) {
filteredPromotions.push({ promotionId, type })
}
}
if (filteredPromotions.length === 0) {
return reply(boom.notFound('promotion not available'))
}
if (protocolVersion < 4) {
return reply(filteredPromotions[0])
}
reply({ grants: filteredPromotions })
debug('grants', { languages: languages })
}
}
v2.read = {
handler: getGrant(2),
description: 'See if a v2 promotion is available',
tags: [ 'api' ],
validate: {
headers: Joi.object().keys({
'user-agent': Joi.string().required().description('the browser user agent')
}).unknown(true),
query: {
lang: Joi.string().regex(localeRegExp).optional().default('en').description('the l10n language'),
paymentId: Joi.string().guid().optional().description('identity of the wallet')
}
},
response: {
schema: Joi.object().keys({
promotionId: Joi.string().required().description('the promotion-identifier')
}).unknown(true).description('promotion properties')
}
}
v3.read = {
handler: safetynetPassthrough(getGrant(3)),
description: 'See if a v3 promotion is available',
tags: [ 'api' ],
validate: {
headers: Joi.object().keys({
'safetynet-token': Joi.string().required().description('the safetynet token created by the android device')
}).unknown(true),
query: {
lang: Joi.string().regex(localeRegExp).optional().default('en').description('the l10n language'),
paymentId: Joi.string().guid().optional().description('identity of the wallet')
}
},
response: {
schema: Joi.object().keys({
promotionId: Joi.string().required().description('the promotion-identifier')
}).unknown(true).description('promotion properties')
}
}
/*
GET /v4/grants
*/
v4.read = {
handler: getGrant(4),
description: 'See if a v4 promotion is available',
tags: [ 'api' ],
validate: {
query: {
lang: Joi.string().regex(localeRegExp).optional().default('en').description('the l10n language'),
paymentId: Joi.string().guid().optional().description('identity of the wallet')
}
},
response: {
schema: Joi.object().keys({
grants: Joi.array().items(Joi.object().keys({
promotionId: Joi.string().required().description('the promotion-identifier')
}).unknown(true).description('promotion properties'))
})
}
}
const checkBounds = (v1, v2, tol) => {
if (v1 > v2) {
return (v1 - v2) <= tol
} else {
return (v2 - v1) <= tol
}
}
/*
PUT /v2/grants/{paymentId}
*/
v2.claimGrant = {
handler: claimGrant(captchaCheck),
description: 'Request a grant for a wallet',
tags: [ 'api' ],
plugins: {
rateLimit: {
enabled: rateLimitEnabled,
rate: (request) => claimRate
}
},
validate: {
params: { paymentId: Joi.string().guid().required().description('identity of the wallet') },
payload: Joi.object().keys({
promotionId: Joi.string().required().description('the promotion-identifier'),
captchaResponse: Joi.object().optional().keys({
x: Joi.number().required(),
y: Joi.number().required()
})
}).required().description('promotion derails')
},
response: {
schema: publicGrantValidator
}
}
/*
PUT /v3/grants/{paymentId}
*/
v3.claimGrant = {
handler: claimGrant(safetynetCheck),
description: 'Request a grant for a wallet',
tags: [ 'api' ],
plugins: {
rateLimit: {
enabled: rateLimitEnabled,
rate: (request) => claimRate
}
},
validate: {
params: {
paymentId: Joi.string().guid().required().description('identity of the wallet')
},
headers: Joi.object().keys({
'safetynet-token': Joi.string().required().description('the safetynet token created by the android device')
}).unknown(true),
payload: Joi.object().keys({
promotionId: Joi.string().required().description('the promotion-identifier')
}).required().description('promotion details')
},
response: {
schema: publicGrantTypedValidator
}
}
/*
PUT /v4/grants/{paymentId}
*/
v4.claimGrant = {
handler: claimGrant(captchaCheck, v4CreateGrantQuery),
description: 'Request a grant for a wallet',
tags: [ 'api' ],
plugins: {
rateLimit: rateLimitPlugin
},
validate: {
params: Joi.object().keys({
paymentId: paymentIdValidator.required()
}),
payload: Joi.object().keys({
promotionId: promotionIdValidator.required(),
captchaResponse: captchaResponseValidator.optional()
}).required().description('promotion details')
},
response: {
schema: publicGrantTypedValidator
}
}
function claimGrant (validate, createGrantQuery = defaultCreateGrantQuery) {
return (runtime) => async (request, reply) => {
const {
params,
payload
} = request
let { paymentId } = params
paymentId = paymentId.toLowerCase()
const { promotionId } = payload
const debug = braveHapi.debug(module, request)
const grants = runtime.database.get('grants', debug)
const promotions = runtime.database.get('promotions', debug)
const wallets = runtime.database.get('wallets', debug)
let grant, result, state, wallet
if (!runtime.config.redeemer) return reply(boom.badGateway('not configured for promotions'))
const promotion = await promotions.findOne({ promotionId: promotionId })
if (!promotion) return reply(boom.notFound('no such promotion: ' + promotionId))
if (!promotion.active) return reply(boom.notFound('promotion is not active: ' + promotionId))
wallet = await wallets.findOne({ paymentId: paymentId })
if (!wallet) return reply(boom.notFound('no such wallet: ' + paymentId))
const validationError = await validate(debug, runtime, request, promotion, wallet)
if (validationError) {
return reply(validationError)
}
if (wallet.grants && wallet.grants.some(x => x.promotionId === promotionId)) {
// promotion already applied to wallet
return reply(boom.conflict())
}
// pop off one grant
const grantQuery = createGrantQuery(promotion, wallet)
grant = await grants.findOneAndDelete(grantQuery)
if (!grant) return reply(boom.resourceGone('promotion no longer available'))
const grantProperties = ['token', 'grantId', 'promotionId', 'status', 'type', 'paymentId']
const grantSubset = underscore.pick(grant, grantProperties)
const currentProperties = {
claimTimestamp: Date.now(),
claimIP: whitelist.ipaddr(request)
}
const grantInfo = underscore.extend(grantSubset, currentProperties)
// atomic find & update, only one request is able to add a grant for the given promotion to this wallet
wallet = await wallets.findOneAndUpdate({ 'paymentId': paymentId, 'grants.promotionId': { '$ne': promotionId } },
{ $push: { grants: grantInfo } }
)
if (!wallet) {
// reinsert grant, another request already added a grant for this promotion to the wallet
await grants.insert(grant)
// promotion already applied to wallet
return reply(boom.conflict())
}
// register the users claim to the grant with the redemption server
const walletPayload = { wallet: underscore.pick(wallet, ['altcurrency', 'provider', 'providerId']) }
try {
result = await braveHapi.wreck.put(runtime.config.redeemer.url + '/v1/grants/' + grant.grantId, {
headers: {
'Authorization': 'Bearer ' + runtime.config.redeemer.access_token,
'Content-Type': 'application/json',
// Only pass "trusted" IP, not previous value of X-Forwarded-For
'X-Forwarded-For': whitelist.ipaddr(request),
'User-Agent': request.headers['user-agent']
},
payload: JSON.stringify(walletPayload),
useProxyP: true
})
} catch (ex) {
runtime.captureException(ex, { req: request })
}
if (runtime.config.balance) {
// invalidate any cached balance
try {
await braveHapi.wreck.delete(runtime.config.balance.url + '/v2/wallet/' + paymentId + '/balance',
{
headers: {
authorization: 'Bearer ' + runtime.config.balance.access_token,
'content-type': 'application/json'
},
useProxyP: true
})
} catch (ex) {
runtime.captureException(ex, { req: request })
}
}
state = {
$currentDate: { timestamp: { $type: 'timestamp' } },
$inc: { count: -1 }
}
await promotions.update({ promotionId: promotionId }, state, { upsert: true })
const grantContent = braveUtils.extractJws(grant.token)
result = underscore.pick(grantContent, [ 'altcurrency', 'probi', 'expiryTime', 'type', 'providerId' ])
await runtime.queue.send(debug, 'grant-report', underscore.extend({
grantId: grantContent.grantId,
paymentId: paymentId,
promotionId: promotionId
}, result))
return reply(result)
}
}
async function safetynetCheck (debug, runtime, request, promotion, wallet) {
const {
config,
database
} = runtime
const {
captcha
} = config
const {
headers
} = request
const {
paymentId
} = wallet
const url = `${captcha.url}/v1/attestations/safetynet`
const captchaHeaders = {
'Authorization': 'Bearer ' + captcha.access_token,
'Content-Type': 'application/json'
}
const wallets = database.get('wallets', debug)
const body = JSON.stringify({
token: headers['safetynet-token']
})
const payload = await braveHapi.wreck.post(url, {
headers: captchaHeaders,
payload: body
})
const data = JSON.parse(payload.toString())
let validNonce = wallet.nonce === data.nonce
const updates = {
$unset: { nonce: {} }
}
if (validNonce) {
updates.$set = {
cohort: 'safetynet'
}
}
await wallets.findOneAndUpdate({
paymentId
}, updates)
if (!validNonce) {
return boom.forbidden('safetynet nonce does not match')
}
}
async function captchaCheck (debug, runtime, request, promotion, wallet) {
const { captchaResponse } = request.payload
const { paymentId } = wallet
const wallets = runtime.database.get('wallets', debug)
const configCaptcha = runtime.config.captcha
if (configCaptcha) {
if (!wallet.captcha) return boom.forbidden('must first request captcha')
if (!captchaResponse) return boom.badData()
await wallets.findOneAndUpdate({ 'paymentId': paymentId }, { $unset: { captcha: {} } })
if (wallet.captcha.version) {
if (wallet.captcha.version !== promotion.protocolVersion) {
return boom.forbidden('must first request correct captcha version')
}
} else {
if (promotion.protocolVersion !== 2) {
return boom.forbidden('must first request correct captcha version')
}
}
if (!(checkBounds(wallet.captcha.x, captchaResponse.x, 5) && checkBounds(wallet.captcha.y, captchaResponse.y, 5))) {
return boom.forbidden()
}
}
}
/*
POST /v2/grants
*/
const uploadGrants = (protocolVersion) => (runtime) => {
return async (request, reply) => {
const batchId = uuidV4().toLowerCase()
const debug = braveHapi.debug(module, request)
const grants = runtime.database.get('grants', debug)
const promotions = runtime.database.get('promotions', debug)
let state
let payload = request.payload
if (payload.file) {
payload = payload.file
const validity = Joi.validate(payload, grantsUploadValidator)
if (validity.error) {
return reply(boom.badData(validity.error))
}
}
const grantsToInsert = []
const promotionCounts = {}
for (let entry of payload.grants) {
const grantContent = braveUtils.extractJws(entry)
const validity = Joi.validate(grantContent, grantContentValidator)
if (validity.error) {
return reply(boom.badData(validity.error))
}
grantsToInsert.push({ grantId: grantContent.grantId, token: entry, promotionId: grantContent.promotionId, status: 'active', batchId: batchId })
if (!promotionCounts[grantContent.promotionId]) {
promotionCounts[grantContent.promotionId] = 0
}
promotionCounts[grantContent.promotionId]++
}
await grants.insert(grantsToInsert)
for (let entry of payload.promotions) {
let $set = underscore.assign({
protocolVersion
}, underscore.omit(entry, ['promotionId']))
let { promotionId } = entry
state = {
$set,
$currentDate: { timestamp: { $type: 'timestamp' } },
$inc: { count: promotionCounts[promotionId] }
}
await promotions.update({
promotionId
}, state, { upsert: true })
}
reply({})
}
}
v2.create =
{ handler: uploadGrants(2),
auth: {
strategy: 'session',
scope: [ 'ledger' ],
mode: 'required'
},
description: 'Create one or more grants via file upload',
tags: [ 'api' ],
plugins: {
'hapi-swagger': {
payloadType: 'form',
validate: {
payload: {
file: Joi.any()
.meta({ swaggerType: 'file' })
.description('json file')
}
}
}
},
validate: { headers: Joi.object({ authorization: Joi.string().optional() }).unknown() },
payload: { output: 'data', maxBytes: 1024 * 1024 * 20 },
response:
{ schema: Joi.object().length(0) }
}
/*
POST /v4/grants
*/
v4.create =
{ handler: uploadTypedGrants(4, grantsUploadTypedValidator, grantContentTypedValidator),
auth: {
strategy: 'session',
scope: [ 'ledger' ],
mode: 'required'
},
description: 'Create one or more grants via file upload',
tags: [ 'api' ],
plugins: {
'hapi-swagger': {
payloadType: 'form',
validate: {
payload: {
file: Joi.any()
.meta({ swaggerType: 'file' })
.description('json file')
}
}
}
},
validate: { headers: Joi.object({ authorization: Joi.string().optional() }).unknown() },
payload: { output: 'data', maxBytes: 1024 * 1024 * 20 },
response:
{ schema: Joi.object().length(0) }
}
const cohortsAssignmentSchema = Joi.array().min(0).items(Joi.object().keys({
paymentId: Joi.string().guid().required().description('identity of the wallet'),
cohort: Joi.string().required().description('cohort to assign')
}).unknown(true).description('grant cohorts'))
/*
PUT /v2/grants/cohorts
*/
v2.cohorts = { handler: (runtime) => {
return async (request, reply) => {
const debug = braveHapi.debug(module, request)
const wallets = runtime.database.get('wallets', debug)
let payload = request.payload
if (payload.file) {
payload = payload.file
const validity = Joi.validate(payload, cohortsAssignmentSchema)
if (validity.error) {
return reply(boom.badData(validity.error))
}
}
for (let entry of payload) {
await wallets.update({ 'paymentId': entry.paymentId }, { $set: { 'cohort': entry.cohort } })
}
return reply({})
}
},
description: 'Set cohort associated with grants on a wallet for testing',
tags: [ 'api' ],
auth: {
strategy: 'session',
scope: [ 'ledger' ],
mode: 'required'
},
plugins: {
'hapi-swagger': {
payloadType: 'form',
validate: {
payload: {
file: Joi.any()
.meta({ swaggerType: 'file' })
.description('json file')
}
}
}
},
validate: { headers: Joi.object({ authorization: Joi.string().optional() }).unknown() },
payload: { output: 'data', maxBytes: 1024 * 1024 * 20 },
response: { schema: Joi.object().length(0) }
}
/*
GET /v2/captchas/{paymentId}
GET /v4/captchas/{paymentId}
*/
const getCaptcha = (protocolVersion) => (runtime) => {
return async (request, reply) => {
const type = request.headers['promotion-type'] || 'ugp'
const paymentId = request.params.paymentId.toLowerCase()
const debug = braveHapi.debug(module, request)
const wallets = runtime.database.get('wallets', debug)
if (!runtime.config.captcha) return reply(boom.notFound())
if (qaOnlyP(request)) return reply(boom.notFound())
const wallet = await wallets.findOne({ 'paymentId': paymentId })
if (!wallet) return reply(boom.notFound('no such wallet: ' + paymentId))
const braveProduct = request.headers['brave-product'] || 'browser-laptop'
if (protocolVersion === 2 && braveProduct !== 'brave-core') {
return reply(boom.notFound('no captcha endpoints'))
}
const captchaEndpoints = {
2: '/v2/captchas/variableshapetarget',
4: '/v2/captchas/variableshapetarget'
}
const endpoint = captchaEndpoints[protocolVersion]
if (!endpoint) {
return reply(boom.notFound('no protocol version'))
}
const { res, payload } = await wreck.get(runtime.config.captcha.url + endpoint, {
headers: {
'Promotion-Type': type,
'Authorization': 'Bearer ' + runtime.config.captcha.access_token,
'Content-Type': 'application/json',
'X-Forwarded-For': whitelist.ipaddr(request)
}
})
const { headers } = res
const solution = JSON.parse(headers['captcha-solution'])
const captcha = underscore.extend(solution, {
version: protocolVersion
})
await wallets.findOneAndUpdate({ 'paymentId': paymentId }, { $set: { captcha } })
return reply(payload).header('Content-Type', headers['content-type']).header('Captcha-Hint', headers['captcha-hint'])
}
}
v2.getCaptcha = {
handler: getCaptcha(2),
description: 'Get a claim time captcha',
tags: [ 'api' ],
plugins: {
rateLimit: rateLimitPlugin
},
validate: {
params: {
paymentId: paymentIdValidator.required()
},
headers: captchaHeadersValidator
}
}
v4.getCaptcha = {
handler: getCaptcha(4),
description: 'Get a claim time v4 captcha',
tags: [ 'api' ],
plugins: {
rateLimit: rateLimitPlugin
},
validate: {
params: {
paymentId: paymentIdValidator.required()
},
headers: captchaHeadersValidator
}
}
/*
GET /v1/attestations/{paymentId}
*/
v3.attestations = {
description: 'Retrieve nonce for android attestation',
tags: [ 'api' ],
response: {
schema: Joi.object().keys({
nonce: Joi.string().required().description('Nonce for wallet')
}).required().description('Response payload')
},
validate: {
params: Joi.object().keys({
paymentId: Joi.string().guid().required().description('Wallet payment id')
}).required().description('Request parameters')
},
handler: (runtime) => async (request, reply) => {
const { paymentId } = request.params
const { database } = runtime
const debug = braveHapi.debug(module, request)
const wallets = database.get('wallets', debug)
const nonce = uuidV4()
const $set = {
nonce: Buffer.from(nonce).toString('base64')
}
await wallets.update({
paymentId
}, {
$set
})
reply({
nonce
})
}
}
module.exports.routes = [
braveHapi.routes.async().path('/v2/promotions').config(v2.all),
braveHapi.routes.async().path('/v3/promotions').config(v3.all),
braveHapi.routes.async().path('/v2/grants').config(v2.read),
braveHapi.routes.async().path('/v3/grants').config(v3.read),