Merge branch 'master' into spencer/transaction-list

# Conflicts:
#	README.md
#	angular.json
#	package-lock.json
#	package.json
#	src/app/_helpers/custom-error-state-matcher.spec.ts
#	src/app/_helpers/index.ts
#	src/app/_services/index.ts
#	src/app/app-routing.module.ts
#	src/app/app.component.html
#	src/app/app.component.spec.ts
#	src/app/app.component.ts
#	src/app/app.module.ts
#	src/environments/environment.prod.ts
#	src/environments/environment.ts
#	src/index.html
#	src/styles.scss
This commit is contained in:
Spencer Ofwiti 2021-02-17 14:52:42 +03:00
commit 63c5a63d81
41 changed files with 2306 additions and 5502 deletions

View File

@ -1,4 +1,6 @@
# CIC Staff Client
# CICADA
Angular web client for managing users and transactions in the CIC network.
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 10.2.0.
@ -10,6 +12,10 @@ Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app w
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Lazy-loading feature modules
Run `ng generate module module-name --route module-name --module app.module` to generate a new module on route `/module-name` in the app module.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.

6739
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -12,12 +12,12 @@
"private": true,
"dependencies": {
"@angular/animations": "~10.2.0",
"@angular/cdk": "^10.2.7",
"@angular/cdk": "~10.2.7",
"@angular/common": "~10.2.0",
"@angular/compiler": "~10.2.0",
"@angular/core": "~10.2.0",
"@angular/forms": "~10.2.0",
"@angular/material": "^10.2.7",
"@angular/material": "~10.2.7",
"@angular/platform-browser": "~10.2.0",
"@angular/platform-browser-dynamic": "~10.2.0",
"@angular/router": "~10.2.0",
@ -49,8 +49,8 @@
"@types/datatables.net": "^1.10.19",
"@types/jasmine": "~3.5.0",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.19.14",
"@types/jquery": "^3.5.4",
"@types/node": "^12.11.1",
"codelyzer": "^6.0.0",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthGuard } from '@app/_guards/auth.guard';
describe('AuthGuard', () => {
let guard: AuthGuard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(AuthGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});

View File

@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (localStorage.getItem(atob('CICADA_USER'))) {
return true;
}
this.router.navigate(['/auth'], { queryParams: { returnUrl: state.url }});
return false;
}
}

2
src/app/_guards/index.ts Normal file
View File

@ -0,0 +1,2 @@
export * from '@app/_guards/auth.guard';
export * from '@app/_guards/role.guard';

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { RoleGuard } from '@app/_guards/role.guard';
describe('RoleGuard', () => {
let guard: RoleGuard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(RoleGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});

View File

@ -0,0 +1,28 @@
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RoleGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const currentUser = JSON.parse(localStorage.getItem(atob('CICADA_USER')));
if (currentUser) {
if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
this.router.navigate(['/']);
return false;
}
return true;
}
this.router.navigate(['/auth'], { queryParams: { returnUrl: state.url }});
return false;
}
}

View File

@ -1,4 +1,4 @@
import { CustomErrorStateMatcher } from './custom-error-state-matcher';
import { CustomErrorStateMatcher } from '@app/_helpers/custom-error-state-matcher';
describe('CustomErrorStateMatcher', () => {
it('should create an instance', () => {

View File

@ -0,0 +1,7 @@
import { CustomValidator } from '@app/_helpers/custom.validator';
describe('Custom.Validator', () => {
it('should create an instance', () => {
expect(new CustomValidator()).toBeTruthy();
});
});

View File

@ -0,0 +1,22 @@
import {AbstractControl, ValidationErrors} from '@angular/forms';
export class CustomValidator {
static passwordMatchValidator(control: AbstractControl): void {
const password: string = control.get('password').value;
const confirmPassword: string = control.get('confirmPassword').value;
if (password !== confirmPassword) {
control.get('confirmPassword').setErrors({ NoPasswordMatch: true });
}
}
static patternValidator(regex: RegExp, error: ValidationErrors): ValidationErrors | null {
return (control: AbstractControl): { [key: string]: any } => {
if (!control.value) {
return null;
}
const valid = regex.test(control.value);
return valid ? null : error;
};
}
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ErrorInterceptor } from '@app/_helpers/error.interceptor';
describe('ErrorInterceptor', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
ErrorInterceptor
]
}));
it('should be created', () => {
const interceptor: ErrorInterceptor = TestBed.inject(ErrorInterceptor);
expect(interceptor).toBeTruthy();
});
});

View File

@ -0,0 +1,25 @@
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(catchError(err => {
if ([401, 403].indexOf(err.status) !== -1) {
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}));
}
}

View File

@ -1,7 +1,10 @@
export * from '@app/_helpers/custom.validator';
export * from '@app/_helpers/error.interceptor';
export * from '@app/_helpers/custom-error-state-matcher';
export * from '@app/_helpers/pgp-key-store';
export * from './mock-backend';
export * from './array-sum';
export * from './accountIndex';
export * from './custom-error-state-matcher';
export * from './http-getter';
export * from './pgp-signer';

View File

@ -0,0 +1,7 @@
import { MutablePgpKeyStore } from '@app/_helpers/pgp-key-store';
describe('PgpKeyStore', () => {
it('should create an instance', () => {
expect(new MutablePgpKeyStore()).toBeTruthy();
});
});

View File

@ -0,0 +1,150 @@
const openpgp = require('openpgp');
const keyring = new openpgp.Keyring();
import { KeyStore } from '@src/assets/js/cic-meta/auth';
interface MutableKeyStore extends KeyStore {
loadKeyring(): Promise<void>;
importKeyPair(publicKey: any, privateKey: any): Promise<void>;
importPublicKey(publicKey: any): Promise<void>;
importPrivateKey(privateKey: any): Promise<void>;
getPublicKeys(): Array<any>;
getTrustedKeys(): Array<any>;
getTrustedActiveKeys(): Array<any>;
getEncryptKeys(): Array<any>;
getPrivateKeys(): Array<any>;
getPrivateKey(): any;
isValidKey(key: any): boolean;
getFingerprint(): string;
getKeyId(key: any): string;
getPrivateKeyId(): string;
getKeysForId(keyId: string): Array<any>;
getPublicKeyForId(keyId: string): any;
getPrivateKeyForId(keyId: string): any;
getPublicKeyForSubkeyId(subkeyId: string): any;
getPublicKeysForAddress(address: string): Array<any>;
removeKeysForId(keyId: string): Array<any>;
removePublicKeyForId(keyId: string): any;
removePublicKey(publicKey: any): any;
clearKeysInKeyring(): void;
sign(plainText: string): Promise<any>;
}
class MutablePgpKeyStore implements MutableKeyStore{
async loadKeyring(): Promise<void> {
await keyring.load();
// clear any keys already in the keychain
// keyring.clear();
await keyring.store();
}
async importKeyPair(publicKey: any, privateKey: any): Promise<void> {
await keyring.publicKeys.importKey(publicKey);
await keyring.privateKeys.importKey(privateKey);
}
async importPublicKey(publicKey: any): Promise<void> {
await keyring.publicKeys.importKey(publicKey);
}
async importPrivateKey(privateKey: any): Promise<void> {
await keyring.privateKeys.importKey(privateKey);
}
getPublicKeys(): Array<any> {
return keyring.publicKeys.keys;
}
getTrustedKeys(): Array<any> {
return keyring.publicKeys.keys;
}
getTrustedActiveKeys(): Array<any> {
return keyring.publicKeys.keys;
}
getEncryptKeys(): Array<any> {
return [];
}
getPrivateKeys(): Array<any> {
return keyring.privateKeys.keys;
}
getPrivateKey(): any {
return keyring.privateKeys.keys[0];
}
isValidKey(key): boolean {
return typeof key === openpgp.Key;
}
getFingerprint(): string {
return keyring.privateKeys.keys[0].keyPacket.fingerprint;
}
getKeyId(key: any): string {
return key.getKeyId().toHex();
}
getPrivateKeyId(): string {
return keyring.privateKeys.keys[0].getKeyId().toHex();
}
getKeysForId(keyId: string): Array<any> {
return keyring.getKeysForId(keyId);
}
getPublicKeyForId(keyId): any {
return keyring.publicKeys.getForId(keyId);
}
getPrivateKeyForId(keyId): any {
return keyring.privateKeys.getForId(keyId);
}
getPublicKeyForSubkeyId(subkeyId): any {
return keyring.publicKeys.getForId(subkeyId, true);
}
getPublicKeysForAddress(address): Array<any> {
return keyring.publicKeys.getForAddress(address);
}
removeKeysForId(keyId): Array<any> {
return keyring.removeKeysForId(keyId);
}
removePublicKeyForId(keyId): any {
return keyring.publicKeys.removeForId(keyId);
}
removePublicKey(publicKey: any): any {
const keyId = publicKey.getKeyId().toHex();
return keyring.publicKeys.removeForId(keyId);
}
clearKeysInKeyring(): void {
keyring.clear();
}
async sign(plainText): Promise<any> {
const privateKey = this.getPrivateKey();
if (!privateKey.isDecrypted()) {
const password = window.prompt('password');
await privateKey.decrypt(password);
}
const opts = {
message: openpgp.message.fromText(plainText),
privateKeys: [privateKey],
detached: true,
};
const signatureObject = await openpgp.sign(opts);
return signatureObject.signature;
}
}
export {
MutablePgpKeyStore,
MutableKeyStore
};

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthService } from '@app/_services/auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AuthService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,148 @@
import { Injectable } from '@angular/core';
import {MutableKeyStore, MutablePgpKeyStore} from '@app/_helpers';
import { hobaParseChallengeHeader } from '@src/assets/js/hoba.js';
import { signChallenge } from '@src/assets/js/hoba-pgp.js';
import {environment} from '@src/environments/environment';
import {HttpClient} from '@angular/common/http';
const origin = 'http://localhost:4444';
@Injectable({
providedIn: 'root'
})
export class AuthService {
sessionToken: any;
sessionLoginCount = 0;
privateKey: any;
mutableKeyStore: MutableKeyStore = new MutablePgpKeyStore();
constructor(
private http: HttpClient
) {
if (sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'))) {
this.sessionToken = sessionStorage.getItem(btoa('CICADA_SESSION_TOKEN'));
}
if (localStorage.getItem(btoa('CICADA_PRIVATE_KEY'))) {
this.privateKey = localStorage.getItem(btoa('CICADA_PRIVATE_KEY'));
}
}
setState(s): void {
(document.getElementById('state') as HTMLInputElement).value = s;
}
getWithToken(): void {
const xhr = new XMLHttpRequest();
xhr.responseType = 'text';
xhr.open('GET', origin + window.location.search.substring(1));
xhr.setRequestHeader('Authorization', 'Bearer ' + this.sessionToken);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('x-cic-automerge', 'none');
xhr.addEventListener('load', (e) => {
if (xhr.status === 401) {
throw new Error('login rejected');
}
this.sessionLoginCount++;
this.setState('click to perform login ' + this.sessionLoginCount + ' with token ' + this.sessionToken);
console.log('received', xhr.responseText);
return;
});
xhr.send();
}
sendResponse(hobaResponseEncoded): void {
const xhr = new XMLHttpRequest();
xhr.responseType = 'text';
xhr.open('GET', origin + window.location.search.substring(1));
xhr.setRequestHeader('Authorization', 'HOBA ' + hobaResponseEncoded);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('x-cic-automerge', 'none');
xhr.addEventListener('load', (e) => {
if (xhr.status === 401) {
throw new Error('login rejected');
}
this.sessionToken = xhr.getResponseHeader('Token');
sessionStorage.setItem(btoa('CICADA_SESSION_TOKEN'), this.sessionToken);
this.sessionLoginCount++;
this.setState('click to perform login ' + this.sessionLoginCount + ' with token ' + this.sessionToken);
console.log('received', xhr.responseText);
return;
});
xhr.send();
}
getChallenge(): void {
const xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.open('GET', origin + window.location.search.substring(1));
xhr.onload = (e) => {
if (xhr.status === 401) {
const authHeader = xhr.getResponseHeader('WWW-Authenticate');
const o = hobaParseChallengeHeader(authHeader);
this.loginResponse(o).then();
}
};
xhr.send();
}
login(): boolean {
if (this.sessionToken !== undefined) {
try {
this.getWithToken();
return true;
} catch (e) {
console.error('login token failed', e);
}
} else {
try {
const o = this.getChallenge();
return true;
} catch (e) {
console.error('login challenge failed', e);
}
}
return false;
}
async loginResponse(o): Promise<any> {
const r = await signChallenge(o.challenge, o.realm, origin, this.mutableKeyStore);
this.sendResponse(r);
}
loginView(): void {
document.getElementById('one').style.display = 'none';
document.getElementById('two').style.display = 'block';
this.setState('click to log in with PGP key ' + this.mutableKeyStore.getPrivateKeyId());
}
async setKey(privateKeyArmored): Promise<boolean> {
console.log('settings pk' + privateKeyArmored);
try {
await this.mutableKeyStore.importPrivateKey(privateKeyArmored);
localStorage.setItem(btoa('CICADA_PRIVATE_KEY'), privateKeyArmored);
} catch (e) {
console.error('failed setting key', e);
return false;
}
this.loginView();
return true;
}
logout(): void {
sessionStorage.removeItem(btoa('CICADA_SESSION_TOKEN'));
window.location.reload(true);
}
async getPublicKeys(): Promise<void> {
this.http.get(`${environment.publicKeysUrl}/keys.asc`).subscribe(async res => {
await this.mutableKeyStore.importPublicKey(res);
}, error => {
console.error('There was an error!', error);
});
if (this.privateKey !== undefined) {
await this.mutableKeyStore.importPrivateKey(this.privateKey);
}
}
}

View File

@ -1,3 +1,4 @@
export * from '@app/_services/auth.service';
export * from './transaction.service';
export * from './user.service';
export * from './token.service';

View File

@ -2,7 +2,9 @@ import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{ path: '', loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) }
{ path: '', loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) },
{ path: 'auth', loadChildren: () => import('@app/auth/auth.module').then(m => m.AuthModule) },
{ path: '**', redirectTo: '', pathMatch: 'full' }
];
@NgModule({

View File

@ -1,5 +1,6 @@
import {Component, HostListener, OnInit} from '@angular/core';
import {BlockSyncService, TransactionService} from './_services';
import {AuthService} from '@app/_services';
@Component({
selector: 'app-root',
@ -7,15 +8,17 @@ import {BlockSyncService, TransactionService} from './_services';
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'cic-staff-client';
title = 'CICADA';
readyStateTarget: number = 3;
readyState: number = 0;
mediaQuery = window.matchMedia('(max-width: 768px)');
constructor(
private authService: AuthService,
private transactionService: TransactionService,
private blockSyncService: BlockSyncService
) {
this.authService.mutableKeyStore.loadKeyring().then(r => this.authService.getPublicKeys().then());
this.blockSyncService.blockSync();
}

View File

@ -1,12 +1,13 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AppRoutingModule } from '@app/app-routing.module';
import { AppComponent } from '@app/app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {HttpClientModule} from '@angular/common/http';
import {MutablePgpKeyStore} from '@app/_helpers';
import {DataTablesModule} from 'angular-datatables';
import {SharedModule} from './shared/shared.module';
import {HttpClientModule} from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MatTableModule} from '@angular/material/table';
import {MockBackendProvider} from './_helpers';
@ -17,13 +18,14 @@ import {MockBackendProvider} from './_helpers';
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
HttpClientModule,
DataTablesModule,
SharedModule,
BrowserAnimationsModule,
MatTableModule
],
providers: [
MutablePgpKeyStore,
MockBackendProvider
],
bootstrap: [AppComponent]

View File

View File

@ -0,0 +1,12 @@
import { PasswordToggleDirective } from '@app/auth/_directives/password-toggle.directive';
import {ElementRef, Renderer2} from '@angular/core';
let elementRef: ElementRef;
let renderer: Renderer2;
describe('PasswordToggleDirective', () => {
it('should create an instance', () => {
const directive = new PasswordToggleDirective(elementRef, renderer);
expect(directive).toBeTruthy();
});
});

View File

@ -0,0 +1,38 @@
import {Directive, ElementRef, Input, Renderer2} from '@angular/core';
@Directive({
selector: '[appPasswordToggle]'
})
export class PasswordToggleDirective {
@Input()
id: string;
@Input()
iconId: string;
constructor(
private elementRef: ElementRef,
private renderer: Renderer2,
) {
this.renderer.listen(this.elementRef.nativeElement, 'click', () => {
this.togglePasswordVisibility();
});
}
togglePasswordVisibility(): void {
const password = document.getElementById(this.id);
const icon = document.getElementById(this.iconId);
// @ts-ignore
if (password.type === 'password') {
// @ts-ignore
password.type = 'text';
icon.classList.remove('fa-eye');
icon.classList.add('fa-eye-slash');
} else {
// @ts-ignore
password.type = 'password';
icon.classList.remove('fa-eye-slash');
icon.classList.add('fa-eye');
}
}
}

View File

@ -0,0 +1,15 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthComponent } from '@app/auth/auth.component';
const routes: Routes = [
{ path: '', component: AuthComponent },
{ path: '**', redirectTo: '', pathMatch: 'full'},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AuthRoutingModule { }

View File

@ -0,0 +1,69 @@
<div class="container">
<div class="row justify-content-center mt-5 mb-5">
<div class="col-lg-6 col-md-8 col-sm-10">
<div class="card">
<mat-card-title class="card-header pt-4 pb-4 text-center bg-dark">
<a routerLink="/">
<h1 class="text-white">CICADA</h1>
</a>
</mat-card-title>
<div id="one" style="display: block" class="card-body p-4">
<div class="text-center w-75 m-auto">
<h4 class="text-dark-50 text-center font-weight-bold">Add Private Key</h4>
</div>
<form [formGroup]="keyForm" (ngSubmit)="onSubmit()">
<mat-form-field appearance="outline" class="full-width">
<mat-label>Private Key</mat-label>
<textarea matInput style="height: 30rem" name="privateKeyAsc" id="privateKeyAsc" formControlName="key"
placeholder="Enter your private key..." [errorStateMatcher]="matcher"></textarea>
<div *ngIf="submitted && keyFormStub.key.errors" class="invalid-feedback">
<mat-error *ngIf="keyFormStub.key.errors.required">Private Key is required.</mat-error>
</div>
</mat-form-field>
<button mat-raised-button matRipple color="primary" type="submit" [disabled]="loading">
<span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
Add Key
</button>
</form>
</div>
<div id="two" style="display: none" class="card-body p-4 align-items-center">
<div class="text-center w-75 m-auto">
<h4 class="text-dark-50 text-center font-weight-bold">Enter Passphrase</h4>
</div>
<form [formGroup]="passphraseForm" (ngSubmit)="login()">
<mat-form-field appearance="outline" class="full-width">
<mat-label>Passphrase</mat-label>
<input matInput name="state" id="state" formControlName="passphrase"
placeholder="Enter your passphrase..." [errorStateMatcher]="matcher">
<div *ngIf="submitted && passphraseFormStub.passphrase.errors" class="invalid-feedback">
<mat-error *ngIf="passphraseFormStub.passphrase.errors.required">Passphrase is required.</mat-error>
</div>
</mat-form-field>
<div class="form-group mb-0 text-center">
<button mat-raised-button matRipple color="primary" type="submit">
<!-- <span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>-->
Login
</button>
</div>
</form>
<div class="row mt-3">
<div class="col-12 text-center">
<p class="text-muted">Change private key? <a (click)="switchWindows()" class="text-muted ml-1"><b>Enter private key</b></a></p>
</div> <!-- end col-->
</div>
<!-- end row -->
</div>
</div>
</div>
</div>
</div>

View File

View File

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AuthComponent } from '@app/auth/auth.component';
describe('AuthComponent', () => {
let component: AuthComponent;
let fixture: ComponentFixture<AuthComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AuthComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AuthComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,89 @@
import {AfterViewInit, Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CustomErrorStateMatcher} from '@app/_helpers';
import {AuthService} from '@app/_services';
@Component({
selector: 'app-auth',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit, AfterViewInit {
keyForm: FormGroup;
passphraseForm: FormGroup;
submitted: boolean = false;
loading: boolean = false;
matcher = new CustomErrorStateMatcher();
constructor(
private authService: AuthService,
private formBuilder: FormBuilder,
) { }
ngOnInit(): void {
this.keyForm = this.formBuilder.group({
key: ['', Validators.required],
});
this.passphraseForm = this.formBuilder.group({
passphrase: ['', Validators.required],
});
if (this.authService.privateKey !== undefined ) {
this.authService.setKey(this.authService.privateKey).then(r => {
if (this.authService.sessionToken !== undefined) {
this.authService.setState(
'click to perform login ' + this.authService.sessionLoginCount + ' with token ' + this.authService.sessionToken);
}
});
}
}
ngAfterViewInit(): void {
console.log(window.location);
const xhr = new XMLHttpRequest();
xhr.responseType = 'text';
xhr.open('GET', window.location.origin + '/privatekey.asc');
xhr.onload = (e) => {
if (xhr.status !== 200) {
console.warn('failed to autoload private key ciphertext');
return;
}
(document.getElementById('privateKeyAsc') as HTMLInputElement).value = xhr.responseText;
};
xhr.send();
}
get keyFormStub(): any { return this.keyForm.controls; }
get passphraseFormStub(): any { return this.passphraseForm.controls; }
onSubmit(): void {
this.submitted = true;
if (this.keyForm.invalid) { return; }
this.loading = true;
this.authService.setKey(this.keyFormStub.key.value).then();
this.loading = false;
}
login(): void {
// if (this.passphraseForm.invalid) { return; }
this.authService.login();
}
switchWindows(): void {
this.authService.sessionToken = undefined;
const divOne = document.getElementById('one');
const divTwo = document.getElementById('two');
this.toggleDisplay(divOne);
this.toggleDisplay(divTwo);
}
toggleDisplay(element: any): void {
const style = window.getComputedStyle(element).display;
if (style === 'block') {
element.style.display = 'none';
} else {
element.style.display = 'block';
}
}
}

View File

@ -0,0 +1,28 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthRoutingModule } from '@app/auth/auth-routing.module';
import { AuthComponent } from '@app/auth/auth.component';
import {ReactiveFormsModule} from '@angular/forms';
import {PasswordToggleDirective} from '@app/auth/_directives/password-toggle.directive';
import {MatCardModule} from '@angular/material/card';
import {MatSelectModule} from '@angular/material/select';
import {MatInputModule} from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import {MatRippleModule} from '@angular/material/core';
@NgModule({
declarations: [AuthComponent, PasswordToggleDirective],
imports: [
CommonModule,
AuthRoutingModule,
ReactiveFormsModule,
MatCardModule,
MatSelectModule,
MatInputModule,
MatButtonModule,
MatRippleModule,
]
})
export class AuthModule { }

View File

@ -0,0 +1,199 @@
import * as pgp from 'openpgp';
import * as crypto from 'crypto';
interface Signable {
digest(): string;
}
type KeyGetter = () => any;
type Signature = {
engine: string
algo: string
data: string
digest: string
};
interface Signer {
prepare(Signable): boolean;
onsign(Signature): void;
onverify(bool): void;
sign(digest: string): void;
verify(digest: string, signature: Signature): void;
fingerprint(): string;
}
interface Authoritative {
}
interface KeyStore {
getPrivateKey: KeyGetter;
getFingerprint: () => string;
getTrustedKeys: () => Array<any>;
getTrustedActiveKeys: () => Array<any>;
getEncryptKeys: () => Array<any>;
}
class PGPKeyStore implements KeyStore {
fingerprint: string;
pk: any;
pubk = {
active: [],
trusted: [],
encrypt: [],
};
loads = 0x00;
loadsTarget = 0x0f;
onload: (k: KeyStore) => void;
constructor(passphrase: string, pkArmor: string, pubkActiveArmor: string, pubkTrustedArmor: string, pubkEncryptArmor: string,
onload = (ks: KeyStore) => {
}) {
this._readKey(pkArmor, undefined, 1, passphrase);
this._readKey(pubkActiveArmor, 'active', 2);
this._readKey(pubkTrustedArmor, 'trusted', 4);
this._readKey(pubkEncryptArmor, 'encrypt', 8);
this.onload = onload;
}
private _readKey(a: string, x: any, n: number, pass?: string): void {
pgp.key.readArmored(a).then((k) => {
if (pass !== undefined) {
this.pk = k.keys[0];
this.pk.decrypt(pass).then(() => {
this.fingerprint = this.pk.getFingerprint();
console.log('private key (sign)', this.fingerprint);
this._registerLoad(n);
});
} else {
this.pubk[x] = k.keys;
k.keys.forEach((pubk) => {
console.log('public key (' + x + ')', pubk.getFingerprint());
});
this._registerLoad(n);
}
});
}
private _registerLoad(b: number): void {
this.loads |= b;
if (this.loads == this.loadsTarget) {
this.onload(this);
}
}
public getTrustedKeys(): Array<any> {
return this.pubk.trusted;
}
public getTrustedActiveKeys(): Array<any> {
return this.pubk.active;
}
public getEncryptKeys(): Array<any> {
return this.pubk.encrypt;
}
public getPrivateKey(): any {
return this.pk;
}
public getFingerprint(): string {
return this.fingerprint;
}
}
class PGPSigner implements Signer {
engine = 'pgp';
algo = 'sha256';
dgst: string;
signature: Signature;
keyStore: KeyStore;
onsign: (Signature) => void;
onverify: (bool) => void;
constructor(keyStore: KeyStore) {
this.keyStore = keyStore;
this.onsign = (string) => {
};
this.onverify = (boolean) => {
};
}
public fingerprint(): string {
return this.keyStore.getFingerprint();
}
public prepare(material: Signable): boolean {
this.dgst = material.digest();
return true;
}
public verify(digest: string, signature: Signature): void {
pgp.signature.readArmored(signature.data).then((s) => {
const opts = {
message: pgp.cleartext.fromText(digest),
publicKeys: this.keyStore.getTrustedKeys(),
signature: s,
};
pgp.verify(opts).then((v) => {
let i = 0;
for (i = 0; i < v.signatures.length; i++) {
const s = v.signatures[i];
if (s.valid) {
this.onverify(s);
return;
}
}
console.error('checked ' + i + ' signature(s) but none valid');
this.onverify(false);
});
}).catch((e) => {
console.error(e);
this.onverify(false);
});
}
public sign(digest: string): void {
const m = pgp.cleartext.fromText(digest);
const pk = this.keyStore.getPrivateKey();
const opts = {
message: m,
privateKeys: [pk],
detached: true,
};
pgp.sign(opts).then((s) => {
this.signature = {
engine: this.engine,
algo: this.algo,
data: s.signature,
// TODO: fix for browser later
digest: digest,
};
this.onsign(this.signature);
}).catch((e) => {
console.error(e);
this.onsign(undefined);
});
}
}
export {
Signature,
Authoritative,
Signer,
KeyGetter,
Signable,
KeyStore,
PGPSigner,
PGPKeyStore,
};

24
src/assets/js/hoba-pgp.js Normal file
View File

@ -0,0 +1,24 @@
import {hobaResult, hobaToSign} from "@src/assets/js/hoba.js";
const alg = '969';
export async function signChallenge(challenge, realm, origin, keyStore) {
const fingerprint = keyStore.getFingerprint();
const nonce_array = new Uint8Array(32);
crypto.getRandomValues(nonce_array);
const kid_array = fingerprint;
const a_kid = btoa(String.fromCharCode.apply(null, kid_array));
const a_nonce = btoa(String.fromCharCode.apply(null, nonce_array));
const a_challenge = btoa(challenge);
const message = hobaToSign(a_nonce, a_kid, a_challenge, realm, origin, alg);
console.debug('message to sign', challenge, realm, origin, message);
const signature = await keyStore.sign(message);
const a_signature = btoa(signature);
const result = hobaResult(a_nonce, a_kid, a_challenge, a_signature);
console.debug('result', result);
return result;
}

30
src/assets/js/hoba.js Normal file
View File

@ -0,0 +1,30 @@
export function hobaResult(nonce, kid, challenge, signature) {
return nonce + '.' + kid + '.' + challenge + '.' + signature;
}
export function hobaToSign(nonce, kid, challenge, realm, origin, alg) {
var s = '';
var params = [nonce, alg, origin, realm, kid, challenge];
for (var i = 0; i < params.length; i++) {
s += params[i].length + ':' + params[i];
}
return s
}
export function hobaParseChallengeHeader(s) {
const auth_parts = s.split(" ");
const auth_pairs = auth_parts[1].split(",");
let auth_values = {}
for (var i = 0; i < auth_pairs.length; i++) {
var auth_kv = auth_pairs[i].split(/^([^=]+)="(.+)"/);
auth_values[auth_kv[1]] = auth_kv[2];
}
console.debug('challenge b64', auth_values['challenge']);
const challenge_bytes = atob(auth_values['challenge']);
console.debug('challenge bytes', challenge_bytes);
return {
challenge: challenge_bytes,
realm: auth_values['realm'],
};
}

2
src/assets/js/openpgp.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,8 +1,9 @@
export const environment = {
production: true,
cicMetaUrl: 'http://localhost:63380',
publicKeysUrl: 'http://localhost:8000',
cicCacheUrl: 'http://localhost:63313',
cicScriptsUrl: 'http://localhost:9999',
cicMetaUrl: 'http://localhost:63380',
web3Provider: 'ws://localhost:8546',
cicUssdUrl: 'http://localhost:63315',
cicEthUrl: 'http://localhost:63314',

View File

@ -4,9 +4,10 @@
export const environment = {
production: false,
cicMetaUrl: 'http://localhost:63380',
publicKeysUrl: 'http://localhost:8000',
cicCacheUrl: 'http://localhost:63313',
cicScriptsUrl: 'http://localhost:9999',
cicMetaUrl: 'http://localhost:63380',
web3Provider: 'ws://localhost:8546',
cicUssdUrl: 'http://localhost:63315',
cicEthUrl: 'http://localhost:63314',

View File

@ -18,5 +18,6 @@
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script async src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script async src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
<script async src="assets/js/openpgp.min.js"></script>
</body>
</html>

View File

@ -348,3 +348,7 @@ button {
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
.full-width {
width: 100%;
}

View File

@ -3,7 +3,9 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
"types": [
"node",
]
},
"files": [
"src/main.ts",

View File

@ -3,6 +3,10 @@
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@src/*": ["src/*"],
"@app/*": ["src/app/*"]
},
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,