doipjs/src/index.js

76 lines
2 KiB
JavaScript
Raw Normal View History

2020-10-24 03:57:27 -06:00
/*
2020-10-24 07:11:14 -06:00
Copyright 2020 Yarmo Mackenbach
2020-10-24 03:57:27 -06:00
2020-10-24 07:11:14 -06: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
2020-10-24 03:57:27 -06:00
2020-10-24 07:11:14 -06:00
http://www.apache.org/licenses/LICENSE-2.0
2020-10-24 03:57:27 -06:00
2020-10-24 07:11:14 -06:00
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.
2020-10-24 03:57:27 -06:00
*/
2020-10-24 03:19:35 -06:00
const validUrl = require('valid-url')
2020-10-24 10:43:41 -06:00
const bent = require('bent')
const req = bent('GET')
const { serviceprovidersList, serviceproviders } = require('./serviceproviders')
2020-10-24 09:13:14 -06:00
const matchServiceproviders = (uri) => {
let matches = [], sp
serviceprovidersList.forEach((spName, i) => {
sp = serviceproviders[spName]
if (sp.reURI.test(uri)) {
matches.push(sp.processURI(uri))
}
})
return matches
}
2020-10-23 14:35:53 -06:00
2020-10-24 10:43:41 -06:00
const verify = async (uri, fingerprint, opts) => {
2020-10-24 06:36:22 -06:00
if (!opts) { opts = {} }
if (!validUrl.isUri(uri)) {
2020-10-24 03:56:30 -06:00
throw new Error('Not a valid URI')
2020-10-24 03:19:35 -06:00
}
2020-10-24 09:13:14 -06:00
const spMatches = matchServiceproviders(uri)
2020-10-24 06:36:22 -06:00
if ('returnMatchesOnly' in opts && opts.returnMatchesOnly) {
return spMatches
}
2020-10-24 10:43:41 -06:00
let claimHasBeenVerified = false, sp, iSp = 0, res, proofData
while (!claimHasBeenVerified && iSp < spMatches.length) {
sp = spMatches[iSp]
res = null
if (!sp.proof.useProxy || 'forceDirectRequest' in opts && opts.forceDirectRequest) {
res = await req(sp.proof.fetch ? sp.proof.fetch : sp.proof.uri)
switch (sp.proof.format) {
case 'json':
proofData = await res.json()
break
case 'text':
proofData = await res.text()
break
default:
throw new Error('No specified proof data format')
break
}
}
iSp++
}
2020-10-23 14:35:53 -06:00
}
2020-10-23 17:25:01 -06:00
exports.verify = verify
exports.serviceproviders = serviceproviders
2020-10-24 03:19:35 -06:00
exports.serviceprovidersList = serviceprovidersList