doipjs/src/claims.js

338 lines
8.2 KiB
JavaScript
Raw Normal View History

2020-11-16 16:50:26 -07:00
/*
2021-01-13 05:20:33 -07:00
Copyright 2021 Yarmo Mackenbach
2020-11-16 16:50:26 -07:00
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const mergeOptions = require('merge-options')
const validUrl = require('valid-url')
2020-12-09 17:56:34 -07:00
const openpgp = require('openpgp')
2020-11-16 16:50:26 -07:00
const serviceproviders = require('./serviceproviders')
const keys = require('./keys')
const utils = require('./utils')
2021-01-26 13:44:17 -07:00
// Promise.allSettled polyfill
2021-03-01 10:27:29 -07:00
Promise.allSettled =
Promise.allSettled ||
((promises) =>
Promise.all(
promises.map((p) =>
p
.then((v) => ({
status: 'fulfilled',
value: v,
}))
.catch((e) => ({
status: 'rejected',
reason: e,
}))
)
))
2021-01-26 13:44:17 -07:00
2020-11-16 17:20:00 -07:00
const runVerificationJson = (
res,
proofData,
checkPath,
checkClaim,
checkRelation
) => {
let re
if (res.isVerified || !proofData) {
return res
}
if (Array.isArray(proofData)) {
proofData.forEach((item, i) => {
res = runVerificationJson(res, item, checkPath, checkClaim, checkRelation)
})
return res
}
if (checkPath.length == 0) {
switch (checkRelation) {
default:
2021-04-15 02:21:18 -06:00
case E.ClaimRelation.CONTAINS:
2020-11-20 11:40:20 -07:00
re = new RegExp(checkClaim, 'gi')
res.isVerified = re.test(proofData.replace(/\r?\n|\r|\\/g, ''))
break
2021-04-15 02:21:18 -06:00
case E.ClaimRelation.EQUALS:
res.isVerified =
2020-11-20 11:40:20 -07:00
proofData.replace(/\r?\n|\r|\\/g, '').toLowerCase() ==
checkClaim.toLowerCase()
break
2021-04-15 02:21:18 -06:00
case E.ClaimRelation.ONEOF:
re = new RegExp(checkClaim, 'gi')
res.isVerified = re.test(proofData.join('|'))
break
}
return res
}
try {
checkPath[0] in proofData
} catch (e) {
res.errors.push('err_data_structure_incorrect')
return res
}
res = runVerificationJson(
res,
proofData[checkPath[0]],
checkPath.slice(1),
checkClaim,
checkRelation
)
return res
}
const runVerification = (proofData, spData) => {
let res = {
isVerified: false,
errors: [],
}
switch (spData.proof.format) {
2021-04-15 02:21:18 -06:00
case E.ProofFormat.JSON:
res = runVerificationJson(
res,
proofData,
spData.claim.path,
utils.generateClaim(spData.claim.fingerprint, spData.claim.format),
spData.claim.relation
)
break
2021-04-15 02:21:18 -06:00
case E.ProofFormat.TEXT:
re = new RegExp(
utils
.generateClaim(spData.claim.fingerprint, spData.claim.format)
.replace('[', '\\[')
.replace(']', '\\]'),
'gi'
)
2020-11-16 18:17:40 -07:00
res.isVerified = re.test(proofData.replace(/\r?\n|\r/, ''))
break
}
return res
}
2020-11-16 16:50:26 -07:00
const verify = async (input, fingerprint, opts) => {
if (input instanceof openpgp.key.Key) {
const fingerprintFromKey = await keys.getFingerprint(input)
const userData = await keys.getUserData(input)
const promises = userData.map(async (user, i) => {
return new Promise(async (resolve, reject) => {
try {
const res = await verify(user.notations, fingerprintFromKey, opts)
resolve(res)
} catch (e) {
reject(e)
}
})
})
return Promise.allSettled(promises).then((values) => {
return values.map((obj, i) => {
if (obj.status == 'fulfilled') {
return obj.value
} else {
return obj.reason
}
})
})
}
if (input instanceof Array) {
const promises = input.map(async (uri, i) => {
return new Promise(async (resolve, reject) => {
try {
const res = await verify(uri, fingerprint, opts)
resolve(res)
} catch (e) {
reject(e)
}
})
})
return Promise.allSettled(promises).then((values) => {
return values.map((obj, i) => {
if (obj.status == 'fulfilled') {
return obj.value
} else {
return obj.reason
}
})
})
}
const promiseClaim = new Promise(async (resolve, reject) => {
let objResult = {
2020-12-20 15:02:59 -07:00
isVerified: false,
errors: [],
2020-12-20 15:02:59 -07:00
serviceproviderData: undefined,
}
2020-12-20 15:02:59 -07:00
const uri = input.replace(/^\s+|\s+$/g, '')
if (!fingerprint) {
fingerprint = null
}
2020-11-16 16:50:26 -07:00
const defaultOpts = {
returnMatchesOnly: false,
proxyPolicy: 'adaptive',
doipProxyHostname: 'proxy.keyoxide.org',
2021-03-01 09:56:31 -07:00
twitterBearerToken: null,
nitterInstance: null,
}
opts = mergeOptions(defaultOpts, opts ? opts : {})
2020-11-16 16:50:26 -07:00
if (!validUrl.isUri(uri)) {
objResult.errors.push('invalid_uri')
reject(objResult)
2020-12-20 15:02:59 -07:00
return
}
2020-11-16 16:50:26 -07:00
const spMatches = serviceproviders.match(uri, opts)
2020-11-16 16:50:26 -07:00
if ('returnMatchesOnly' in opts && opts.returnMatchesOnly) {
resolve(spMatches)
2020-12-20 15:02:59 -07:00
return
}
let claimVerificationDone = false,
claimVerificationResult,
sp,
iSp = 0,
res,
proofData,
spData
while (!claimVerificationDone && iSp < spMatches.length) {
spData = spMatches[iSp]
spData.claim.fingerprint = fingerprint
2020-11-16 16:50:26 -07:00
res = null
2020-11-16 16:50:26 -07:00
if (spData.customRequestHandler instanceof Function) {
try {
proofData = await spData.customRequestHandler(spData, opts)
} catch (e) {
objResult.errors.push('custom_request_handler_failed')
}
} else {
switch (opts.proxyPolicy) {
case 'adaptive':
if (spData.proof.useProxy) {
try {
2020-12-20 15:19:07 -07:00
proofData = await serviceproviders.proxyRequestHandler(
spData,
opts
)
} catch (er) {}
} else {
try {
2020-12-20 15:19:07 -07:00
proofData = await serviceproviders.directRequestHandler(
spData,
opts
)
} catch (er) {}
if (!proofData) {
try {
2020-12-20 15:19:07 -07:00
proofData = await serviceproviders.proxyRequestHandler(
spData,
opts
)
} catch (er) {}
}
}
2020-12-20 15:19:07 -07:00
break
case 'fallback':
try {
2020-12-20 15:19:07 -07:00
proofData = await serviceproviders.directRequestHandler(
spData,
opts
)
} catch (er) {}
if (!proofData) {
try {
2020-12-20 15:19:07 -07:00
proofData = await serviceproviders.proxyRequestHandler(
spData,
opts
)
} catch (er) {}
}
2020-12-20 15:19:07 -07:00
break
case 'always':
try {
2020-12-20 15:19:07 -07:00
proofData = await serviceproviders.proxyRequestHandler(
spData,
opts
)
} catch (er) {}
break
case 'never':
try {
2020-12-20 15:19:07 -07:00
proofData = await serviceproviders.directRequestHandler(
spData,
opts
)
} catch (er) {}
break
default:
objResult.errors.push('invalid_proxy_policy')
}
}
2020-11-16 16:50:26 -07:00
if (proofData) {
claimVerificationResult = runVerification(proofData, spData)
2020-11-16 16:50:26 -07:00
if (claimVerificationResult.errors.length == 0) {
claimVerificationDone = true
}
} else {
objResult.errors.push('unsuccessful_claim_verification')
2020-11-16 16:50:26 -07:00
}
iSp++
2020-11-16 16:50:26 -07:00
}
if (!claimVerificationResult) {
claimVerificationResult = {
isVerified: false,
}
}
objResult.isVerified = claimVerificationResult.isVerified
objResult.serviceproviderData = spData
resolve(objResult)
2020-12-20 15:02:59 -07:00
return
})
2020-11-16 16:50:26 -07:00
2020-12-20 15:02:59 -07:00
const promiseTimeout = new Promise((resolve) => {
const objResult = {
isVerified: false,
errors: ['verification_timed_out'],
serviceproviderData: undefined,
2020-11-16 16:50:26 -07:00
}
2020-12-20 15:02:59 -07:00
setTimeout(() => {
resolve(objResult)
return
2021-03-05 07:41:53 -07:00
}, 10000)
})
2020-11-16 16:50:26 -07:00
return await Promise.race([promiseClaim, promiseTimeout])
2020-11-16 16:50:26 -07:00
}
exports.verify = verify