Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial commit (extract from jsonld-signatures). #1

Merged
merged 18 commits into from
Mar 19, 2021
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

## Background

TBD
For use with https://github.com/digitalbazaar/jsonld-signatures v6.0 and above.
dmitrizagidulin marked this conversation as resolved.
Show resolved Hide resolved

## Security

Expand Down
6 changes: 0 additions & 6 deletions lib/Example.js

This file was deleted.

204 changes: 204 additions & 0 deletions lib/JwsLinkedDataSignature.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
/*!
* Copyright (c) 2020-2021 Digital Bazaar, Inc. All rights reserved.
*/
import jsonld from 'jsonld';
import jsigs from 'jsonld-signatures';
const {LinkedDataSignature} = jsigs.suites;
import {encode, decode} from 'base64url-universal';

export class JwsLinkedDataSignature extends LinkedDataSignature {
/**
* @param type {string} Provided by subclass.
* @param alg {string} JWS alg provided by subclass.
* @param [LDKeyClass] {LDKeyClass} provided by subclass or subclass
* overrides `getVerificationMethod`.
*
* @param [verificationMethod] {string} A key id URL to the paired public key.
*
* This parameter is required for signing:
*
* @param [signer] {function} an optional signer.
*
* Advanced optional parameters and overrides:
*
* @param [proof] {object} a JSON-LD document with options to use for
* the `proof` node (e.g. any other custom fields can be provided here
* using a context different from security-v2).
* @param [date] {string|Date} signing date to use if not passed.
* @param [key] {LDKeyPair} an optional crypto-ld KeyPair.
* @param [useNativeCanonize] {boolean} true to use a native canonize
* algorithm.
*/
constructor({
type, alg, LDKeyClass, verificationMethod, signer, key, proof,
date, useNativeCanonize
} = {}) {
super({type, verificationMethod, proof, date, useNativeCanonize});
this.alg = alg;
this.LDKeyClass = LDKeyClass;
this.signer = signer;
if(key) {
if(verificationMethod === undefined) {
const publicKey = key.export({publicKey: true});
this.verificationMethod = publicKey.id;
}
this.key = key;
if(typeof key.signer === 'function') {
this.signer = key.signer();
}
if(typeof key.verifier === 'function') {
this.verifier = key.verifier();
}
}
}

/**
* @param verifyData {Uint8Array}.
* @param proof {object}
*
* @returns {Promise<{object}>} the proof containing the signature value.
*/
async sign({verifyData, proof}) {
if(!(this.signer && typeof this.signer.sign === 'function')) {
throw new Error('A signer API has not been specified.');
}
// JWS header
const header = {
alg: this.alg,
b64: false,
crit: ['b64']
};

/*
+-------+-----------------------------------------------------------+
| "b64" | JWS Signing Input Formula |
+-------+-----------------------------------------------------------+
| true | ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' || |
| | BASE64URL(JWS Payload)) |
| | |
| false | ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.') || |
| | JWS Payload |
+-------+-----------------------------------------------------------+
*/

// create JWS data and sign
const encodedHeader = encode(JSON.stringify(header));

const data = _createJws({encodedHeader, verifyData});

const signature = await this.signer.sign({data});

// create detached content signature
const encodedSignature = encode(signature);
proof.jws = encodedHeader + '..' + encodedSignature;
return proof;
}

/**
* @param verifyData {Uint8Array}.
* @param verificationMethod {object}.
* @param document {object} the document the proof applies to.
* @param proof {object} the proof to be verified.
* @param purpose {ProofPurpose}
* @param documentLoader {function}
* @param expansionMap {function}
*
* @returns {Promise<{boolean}>} Resolves with the verification result.
*/
async verifySignature({verifyData, verificationMethod, proof}) {
if(!(proof.jws && typeof proof.jws === 'string' &&
proof.jws.includes('.'))) {
throw new TypeError('The proof does not include a valid "jws" property.');
}
// add payload into detached content signature
const [encodedHeader, /*payload*/, encodedSignature] = proof.jws.split('.');

let header;
try {
const utf8decoder = new TextDecoder();
header = JSON.parse(utf8decoder.decode(decode(encodedHeader)));
} catch(e) {
throw new Error('Could not parse JWS header; ' + e);
}
if(!(header && typeof header === 'object')) {
throw new Error('Invalid JWS header.');
}

// confirm header matches all expectations
if(!(header.alg === this.alg && header.b64 === false &&
Array.isArray(header.crit) && header.crit.length === 1 &&
header.crit[0] === 'b64') && Object.keys(header).length === 3) {
throw new Error(
`Invalid JWS header parameters for ${this.type}.`);
}

// do signature verification
const signature = decode(encodedSignature);

const data = _createJws({encodedHeader, verifyData});

let {verifier} = this;
if(!verifier) {
const key = await this.LDKeyClass.from(verificationMethod);
verifier = key.verifier();
}
return verifier.verify({data, signature});
}

async assertVerificationMethod({verificationMethod}) {
if(!jsonld.hasValue(verificationMethod, 'type', this.requiredKeyType)) {
throw new Error(
`Invalid key type. Key type must be "${this.requiredKeyType}".`);
}
}

async getVerificationMethod({proof, documentLoader}) {
if(this.key) {
return this.key.export({publicKey: true});
}

const verificationMethod = await super.getVerificationMethod(
{proof, documentLoader});
await this.assertVerificationMethod({verificationMethod});
return verificationMethod;
}

async matchProof({proof, document, purpose, documentLoader, expansionMap}) {
if(!await super.matchProof(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: Extending suites will need to check for their contexts here and in sign. We probably want a note about that somewhere.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a note - does that work?

{proof, document, purpose, documentLoader, expansionMap})) {
return false;
}
// NOTE: When subclassing this suite: Extending suites will need to check
// for the presence their contexts here and in sign()

if(!this.key) {
// no key specified, so assume this suite matches and it can be retrieved
return true;
}

const {verificationMethod} = proof;

// only match if the key specified matches the one in the proof
if(typeof verificationMethod === 'object') {
return verificationMethod.id === this.key.id;
}
return verificationMethod === this.key.id;
}
}

/**
* Creates the bytes ready for signing.
*
* @param {string} encodedHeader - base64url encoded JWT header.
* @param {Uint8Array} verifyData - Payload to sign/verify.
* @returns {Uint8Array} A combined byte array for signing.
*/
function _createJws({encodedHeader, verifyData}) {
const encodedHeaderBytes = new TextEncoder().encode(encodedHeader + '.');

// concatenate the two uint8arrays
const data = new Uint8Array(encodedHeaderBytes.length + verifyData.length);
data.set(encodedHeaderBytes, 0);
data.set(verifyData, encodedHeaderBytes.length);
return data;
}
8 changes: 0 additions & 8 deletions lib/env.js

This file was deleted.

2 changes: 1 addition & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*!
* Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved.
* Copyright (c) 2020-2021 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';

Expand Down
4 changes: 2 additions & 2 deletions lib/main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*!
* Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved.
* Copyright (c) 2020-2021 Digital Bazaar, Inc. All rights reserved.
*/
export {Example} from './Example.js';
export {JwsLinkedDataSignature} from './JwsLinkedDataSignature.js';
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@
],
"module": "lib/main.js",
"dependencies": {
"esm": "^3.2.25"
"base64url-universal": "^1.1.0",
"esm": "^3.2.25",
"jsonld": "^5.0.0",
"jsonld-signatures": "^8.0.0"
},
"devDependencies": {
"@babel/core": "^7.11.0",
Expand All @@ -37,7 +40,7 @@
"dirty-chai": "^2.0.1",
"eslint": "^7.6.0",
"eslint-config-digitalbazaar": "^2.5.0",
"eslint-plugin-jsdoc": "^30.2.0",
"eslint-plugin-jsdoc": "^32.3.0",
"karma": "^5.1.1",
"karma-babel-preprocessor": "^8.0.1",
davidlehn marked this conversation as resolved.
Show resolved Hide resolved
"karma-chai": "^0.1.0",
Expand All @@ -46,7 +49,7 @@
"karma-mocha-reporter": "^2.2.5",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^4.0.2",
"mocha": "^8.1.0",
"mocha": "^8.1.1",
"mocha-lcov-reporter": "^1.3.0",
"nyc": "^15.1.0",
"webpack": "^4.44.1"
Expand Down Expand Up @@ -74,8 +77,8 @@
],
"scripts": {
"test": "npm run lint && npm run test-node && npm run test-karma",
"test-node": "cross-env NODE_ENV=test mocha -r esm --preserve-symlinks -t 10000 tests/**/*.spec.js",
"test-karma": "karma start tests/karma.conf.js",
"test-node": "cross-env NODE_ENV=test mocha -r esm --preserve-symlinks -t 10000 test/**/*.spec.js",
"test-karma": "karma start test/karma.conf.js",
"coverage": "cross-env NODE_ENV=test nyc --reporter=lcov --reporter=text-summary npm run test-node",
"coverage-ci": "cross-env NODE_ENV=test nyc --reporter=text-lcov npm run test-node > coverage.lcov",
"coverage-report": "nyc report",
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion tests/karma.conf.js → test/karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ module.exports = function(config) {

singleRun: true,

// enable / disable watching file and executing tests whenever any
// enable / disable watching file and executing test whenever any
// file changes
autoWatch: false,

Expand Down
18 changes: 18 additions & 0 deletions test/unit/JwsLinkedDataSignature.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*!
* Copyright (c) 2020-2021 Digital Bazaar, Inc. All rights reserved.
*/
import chai from 'chai';
chai.should();
const {expect} = chai;

import {JwsLinkedDataSignature} from '../../';

describe('JwsLinkedDataSignature', () => {
describe('constructor', () => {
it('should exist', async () => {
const ex = new JwsLinkedDataSignature({type: 'ExampleType'});

expect(ex).to.exist;
});
});
});
davidlehn marked this conversation as resolved.
Show resolved Hide resolved
20 changes: 0 additions & 20 deletions tests/unit/Example.spec.js

This file was deleted.