Commit b5d93218 authored by Hidde-Jan Jongsma's avatar Hidde-Jan Jongsma

Initial commit

parents
module.exports = {
env: {
browser: true,
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"prettier",
"prettier/@typescript-eslint",
],
globals: {
Atomics: "readonly",
SharedArrayBuffer: "readonly",
},
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 11,
sourceType: "module",
},
plugins: ["@typescript-eslint"],
rules: {},
ignorePatterns: ["./dist"],
};
dist
coverage
node_modules/
module.exports = {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
}
This diff is collapsed.
{
"name": "ssi-client",
"version": "0.0.1",
"description": "A simple client for interacting with the SSI Service Provider.",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"./dist"
],
"scripts": {
"build": "tsc",
"prepare": "npm run build",
"test": "jest --coverage"
},
"keywords": [
"self-sovereign",
"identity",
"ssi"
],
"author": "Hidde-Jan Jongsma",
"license": "MIT",
"dependencies": {
"jsonwebtoken": "^8.5.1"
},
"devDependencies": {
"@types/jest": "^25.2.3",
"@types/jsonwebtoken": "^8.5.0",
"@typescript-eslint/eslint-plugin": "^3.0.0",
"@typescript-eslint/parser": "^3.0.0",
"eslint": "^7.1.0",
"eslint-config-prettier": "^6.11.0",
"jest": "^26.0.1",
"prettier": "^2.0.5",
"ts-jest": "^26.0.0",
"typescript": "^3.9.3"
}
}
// import scream, { addExclamationPoints } from "../src/index";
import SSIClient, { SSIClientOptions } from "../src/index";
import { sign } from "jsonwebtoken";
const ID = "my";
const SECRET = "secret";
function newClient(options?: SSIClientOptions) {
return new SSIClient(ID, SECRET, options);
}
test("It instantiates with an id and a secret", () => {
newClient();
});
test("It instantiates with the url option", () => {
newClient({
url: "http://localhost",
});
});
test("It instantiates with the name option", () => {
newClient({
name: "other-provider",
});
});
test("It constructs a verify request url", () => {
const client = newClient();
const url = client.verifyUrl("MyType", "12345");
expect(url).toBeDefined();
});
test("It constructs an issue request url", () => {
const client = newClient();
const url = client.issueUrl("MyType", { my: "data" }, "12345");
expect(url).toBeDefined();
});
test("It handles issue responses", () => {
const client = newClient();
const payload = {
type: "MyType",
requestId: "12345",
connector: "jolocom",
status: "success",
};
const token = sign(payload, SECRET, {
issuer: "ssi-service-provider",
audience: ID,
subject: "credential-issue-response",
});
const response = client.parseIssueResponse(token);
expect(response).toMatchObject(payload);
});
test("It handles malformed issue responses", () => {
const client = newClient();
const payload = { some: "body" };
const token = sign(payload, SECRET, {
issuer: "ssi-service-provider",
audience: ID,
subject: "wrong-subject",
});
expect(() => client.parseIssueResponse(token)).toThrow();
});
test("It handles verify responses", () => {
const client = newClient();
const payload = {
type: "MyType",
requestId: "12345",
connector: "jolocom",
status: "success",
data: {
my: "Data",
},
};
const token = sign(payload, SECRET, {
issuer: "ssi-service-provider",
audience: ID,
subject: "credential-verify-response",
});
const response = client.parseVerifyResponse(token);
expect(response).toMatchObject(payload);
});
test("It handles malformed verify responses", () => {
const client = newClient();
const payload = { some: "body" };
const token = sign(payload, SECRET, {
issuer: "ssi-service-provider",
audience: ID,
subject: "wrong-subject",
});
expect(() => client.parseVerifyResponse(token)).toThrow();
});
import { sign, verify, SignOptions, VerifyOptions } from "jsonwebtoken";
export interface SSIClientOptions {
url?: string;
name?: string;
}
export type SSIData = Record<string, string | number | boolean | null>;
export type SSIFunction = "verify" | "issue";
enum ResponseStatus {
success = "succes",
error = "error",
cancelled = "cancelled",
}
export interface CredentialResponse {
requestId: string;
type: string;
status: ResponseStatus;
connector: string;
}
export interface CredentialVerifyResponse extends CredentialResponse {
data: SSIData;
}
export type CredentialIssueResponse = CredentialResponse;
export default class SSIClient {
private url = "https://ssi-provider.sensorlab.tno.nl/";
private name = "ssi-service-provider";
constructor(
private clientId: string,
private clientSecret: string,
options?: SSIClientOptions
) {
if (!options) {
return;
}
if (options.url) {
this.url = options.url;
}
if (options.name) {
this.name = options.name;
}
}
verifyUrl(type: string, requestId: string): string {
const token = this.encodeJWT(
{ type },
{ subject: "credential-verify-request", jwtid: requestId }
);
return this.constructRequestUrl("verify", token);
}
issueUrl(type: string, data: SSIData, requestId: string): string {
const token = this.encodeJWT(
{ type, data },
{ subject: "credential-issue-request", jwtid: requestId }
);
return this.constructRequestUrl("issue", token);
}
parseVerifyResponse(token: string): CredentialVerifyResponse {
const response = this.decodeJWT(token, {
subject: "credential-verify-response",
}) as any;
return {
type: response.type,
data: response.data,
status: response.status,
connector: response.connector,
requestId: response.requestId,
};
}
parseIssueResponse(token: string): CredentialIssueResponse {
const response = this.decodeJWT(token, {
subject: "credential-issue-response",
}) as any;
return {
type: response.type,
status: response.status,
connector: response.connector,
requestId: response.requestId,
};
}
private constructRequestUrl(endpoint: SSIFunction, token: string) {
const url = new URL(endpoint, this.url);
url.search = `?token=${token}`;
return url.toString();
}
private encodeJWT(
payload: Record<string, unknown>,
signOptions?: SignOptions
) {
return sign(payload, this.clientSecret, {
issuer: this.clientId,
audience: this.name,
...signOptions,
});
}
private decodeJWT(token: string, verifyOptions?: VerifyOptions) {
// Payload cannot be a string due to the verify options passed.
const payload = verify(token, this.clientSecret, {
issuer: this.name,
audience: this.clientId,
...verifyOptions,
}) as Record<string, unknown>;
return payload;
}
}
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
"declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment