@airgap/beacon-sdk
Advanced tools
Comparing version 0.0.3-beta.6 to 0.0.3-beta.7
@@ -0,3 +1,4 @@ | ||
import * as sodium from 'libsodium-wrappers'; | ||
import { ExposedPromise } from '../utils/exposed-promise'; | ||
import { Serializer, Transport, TransportType, Storage, AccountInfo, BeaconBaseMessage, Network } from '..'; | ||
import { Serializer, Transport, TransportType, Storage, AccountInfo, Network, BeaconMessages } from '..'; | ||
export declare class BaseClient { | ||
@@ -10,3 +11,5 @@ protected requestCounter: number[]; | ||
protected readonly serializer: Serializer; | ||
protected handleResponse: (_event: BeaconBaseMessage, connectionInfo: any) => void; | ||
protected handleResponse: (_event: BeaconMessages, connectionInfo: any) => void; | ||
protected _keyPair: ExposedPromise<sodium.KeyPair>; | ||
protected get keyPair(): Promise<sodium.KeyPair>; | ||
protected storage: Storage | undefined; | ||
@@ -16,2 +19,3 @@ protected transport: Transport | undefined; | ||
constructor(name: string); | ||
static getAccountIdentifier(pubkey: string, network: Network): Promise<string>; | ||
addRequestAndCheckIfRateLimited(): Promise<boolean>; | ||
@@ -30,4 +34,3 @@ init(isDapp?: boolean, transport?: Transport): Promise<TransportType>; | ||
protected _connect(): Promise<boolean>; | ||
protected getAccountIdentifier(pubkey: string, network: Network): Promise<string>; | ||
private getOrCreateBeaconId; | ||
private loadOrCreateBeaconSecret; | ||
} |
@@ -6,2 +6,3 @@ "use strict"; | ||
const generate_uuid_1 = require("../utils/generate-uuid"); | ||
const crypto_1 = require("../utils/crypto"); | ||
const __1 = require(".."); | ||
@@ -15,8 +16,21 @@ // const logger = new Logger('BaseClient') | ||
this.serializer = new __1.Serializer(); | ||
this._keyPair = exposed_promise_1.exposedPromise(); | ||
this._isConnected = exposed_promise_1.exposedPromise(); | ||
this.name = name; | ||
this.handleResponse = (_event) => { | ||
this.handleResponse = (_event, _connectionInfo) => { | ||
throw new Error('not overwritten'); | ||
}; | ||
this.loadOrCreateBeaconSecret().catch(console.error); | ||
this.keyPair | ||
.then((keyPair) => { | ||
this.beaconId = crypto_1.toHex(keyPair.publicKey); | ||
}) | ||
.catch(console.error); | ||
} | ||
get keyPair() { | ||
return this._keyPair.promise; | ||
} | ||
static async getAccountIdentifier(pubkey, network) { | ||
return `${pubkey}-${network.type}-${network.name}`; | ||
} | ||
async addRequestAndCheckIfRateLimited() { | ||
@@ -35,3 +49,2 @@ const now = new Date().getTime(); | ||
} | ||
this.beaconId = await this.getOrCreateBeaconId(); | ||
if (transport) { | ||
@@ -44,3 +57,3 @@ this.transport = transport; // Let users define their own transport | ||
else if (await __1.P2PTransport.isAvailable()) { | ||
this.transport = new __1.P2PTransport(this.name, this.storage, isDapp); // Establish our own connection with the wallet | ||
this.transport = new __1.P2PTransport(this.name, await this.keyPair, this.storage, isDapp); // Establish our own connection with the wallet | ||
} | ||
@@ -122,3 +135,3 @@ else { | ||
if (typeof message === 'string') { | ||
const deserializedMessage = (await this.serializer.deserialize(message)); // TODO: Check type | ||
const deserializedMessage = (await this.serializer.deserialize(message)); | ||
this.handleResponse(deserializedMessage, connectionInfo); | ||
@@ -135,17 +148,14 @@ } | ||
} | ||
async getAccountIdentifier(pubkey, network) { | ||
return `${pubkey}-${network.type}-${network.name}`; | ||
} | ||
async getOrCreateBeaconId() { | ||
async loadOrCreateBeaconSecret() { | ||
if (!this.storage) { | ||
throw new Error('no storage'); | ||
} | ||
const storageValue = await this.storage.get(__1.StorageKey.BEACON_SDK_ID); | ||
const storageValue = await this.storage.get(__1.StorageKey.BEACON_SDK_SECRET_SEED); | ||
if (storageValue && typeof storageValue === 'string') { | ||
return storageValue; | ||
this._keyPair.resolve(crypto_1.getKeypairFromSeed(storageValue)); | ||
} | ||
else { | ||
const key = generate_uuid_1.generateGUID(); | ||
await this.storage.set(__1.StorageKey.BEACON_SDK_ID, key); | ||
return key; | ||
await this.storage.set(__1.StorageKey.BEACON_SDK_SECRET_SEED, key); | ||
this._keyPair.resolve(crypto_1.getKeypairFromSeed(key)); | ||
} | ||
@@ -152,0 +162,0 @@ } |
import { ExposedPromise } from '../utils/exposed-promise'; | ||
import { AccountInfo, AccountIdentifier, BaseClient, TransportType, Transport, BeaconMessageType, PermissionResponse, SignPayloadResponse, OperationResponse, BroadcastResponse, BeaconMessages, RequestPermissionInput, RequestSignPayloadInput, RequestOperationInput, RequestBroadcastInput } from '..'; | ||
import { IgnoredInputProperties } from '../types/beacon/IgnoredInputProperties'; | ||
import { ConnectionContext } from '../types/ConnectionContext'; | ||
import { AccountInfo, BaseClient, TransportType, Transport, BeaconMessageType, PermissionResponse, SignPayloadResponse, SignPayloadRequest, OperationResponse, OperationRequest, BroadcastResponse, BroadcastRequest, BeaconErrorMessage, BeaconMessages, RequestPermissionInput, RequestSignPayloadInput, RequestOperationInput, RequestBroadcastInput, PermissionRequest, AppMetadata } from '..'; | ||
export declare type PermissionRequestInput = Omit<PermissionRequest, IgnoredInputProperties>; | ||
export declare type OperationRequestInput = Omit<OperationRequest, IgnoredInputProperties>; | ||
export declare type SignPayloadRequestInput = Omit<SignPayloadRequest, IgnoredInputProperties>; | ||
export declare type BroadcastRequestInput = Omit<BroadcastRequest, IgnoredInputProperties>; | ||
export declare type BeaconMessagesInput = PermissionRequestInput | OperationRequestInput | SignPayloadRequestInput | BroadcastRequestInput; | ||
export declare type IgnoredOutputProperties = 'id' | 'version' | 'type'; | ||
export declare type PermissionResponseOutput = Omit<Omit<PermissionResponse, IgnoredOutputProperties>, 'accountIdentifier' | 'pubkey'> & { | ||
address?: string; | ||
}; | ||
export declare type OperationResponseOutput = Omit<OperationResponse, IgnoredOutputProperties>; | ||
export declare type SignPayloadResponseOutput = Omit<SignPayloadResponse, IgnoredOutputProperties>; | ||
export declare type BroadcastResponseOutput = Omit<BroadcastResponse, IgnoredOutputProperties>; | ||
export declare type BeaconMessagesOutput = PermissionResponseOutput | OperationResponseOutput | SignPayloadResponseOutput | BroadcastResponseOutput; | ||
export declare class DAppClient extends BaseClient { | ||
private readonly events; | ||
private readonly openRequests; | ||
private readonly iconUrl?; | ||
private activeAccount; | ||
get isConnected(): Promise<boolean>; | ||
constructor(name: string); | ||
addOpenRequest(id: string, promise: ExposedPromise<BeaconMessages>): void; | ||
constructor(name: string, iconUrl?: string); | ||
addOpenRequest(id: string, promise: ExposedPromise<{ | ||
message: BeaconMessages; | ||
connectionInfo: ConnectionContext; | ||
}, BeaconErrorMessage>): void; | ||
init(_isDapp?: boolean, transport?: Transport): Promise<TransportType>; | ||
getActiveAccount(): Promise<AccountInfo | undefined>; | ||
makeRequest<T extends BeaconMessages>(request: BeaconMessages): Promise<T>; | ||
getAppMetadata(): Promise<AppMetadata>; | ||
connect(): Promise<boolean>; | ||
checkPermissions(type: BeaconMessageType, identifier: AccountIdentifier): Promise<boolean>; | ||
requestPermissions(request?: RequestPermissionInput): Promise<PermissionResponse>; | ||
requestSignPayload(request: RequestSignPayloadInput): Promise<SignPayloadResponse>; | ||
requestOperation(request: RequestOperationInput): Promise<OperationResponse>; | ||
requestBroadcast(request: RequestBroadcastInput): Promise<BroadcastResponse>; | ||
checkPermissions(type: BeaconMessageType): Promise<boolean>; | ||
requestPermissions(input?: RequestPermissionInput): Promise<PermissionResponseOutput>; | ||
requestSignPayload(input: RequestSignPayloadInput): Promise<SignPayloadResponseOutput>; | ||
requestOperation(input: RequestOperationInput): Promise<OperationResponseOutput>; | ||
requestBroadcast(input: RequestBroadcastInput): Promise<BroadcastResponseOutput>; | ||
private handleRequestError; | ||
private handleBeaconError; | ||
private makeRequest; | ||
private setActiveAccount; | ||
} |
@@ -7,10 +7,47 @@ "use strict"; | ||
const events_1 = require("../events"); | ||
const constants_1 = require("../constants"); | ||
const crypto_1 = require("../utils/crypto"); | ||
const __1 = require(".."); | ||
const logger = new Logger_1.Logger('DAppClient'); | ||
const messageEvents = { | ||
[__1.BeaconMessageType.PermissionRequest]: { | ||
success: events_1.InternalEvent.PERMISSION_REQUEST_SENT, | ||
error: events_1.InternalEvent.PERMISSION_REQUEST_ERROR | ||
}, | ||
[__1.BeaconMessageType.PermissionResponse]: { | ||
success: events_1.InternalEvent.UNKNOWN, | ||
error: events_1.InternalEvent.UNKNOWN | ||
}, | ||
[__1.BeaconMessageType.OperationRequest]: { | ||
success: events_1.InternalEvent.OPERATION_REQUEST_SENT, | ||
error: events_1.InternalEvent.OPERATION_REQUEST_ERROR | ||
}, | ||
[__1.BeaconMessageType.OperationResponse]: { | ||
success: events_1.InternalEvent.UNKNOWN, | ||
error: events_1.InternalEvent.UNKNOWN | ||
}, | ||
[__1.BeaconMessageType.SignPayloadRequest]: { | ||
success: events_1.InternalEvent.SIGN_REQUEST_SENT, | ||
error: events_1.InternalEvent.SIGN_REQUEST_ERROR | ||
}, | ||
[__1.BeaconMessageType.SignPayloadResponse]: { | ||
success: events_1.InternalEvent.UNKNOWN, | ||
error: events_1.InternalEvent.UNKNOWN | ||
}, | ||
[__1.BeaconMessageType.BroadcastRequest]: { | ||
success: events_1.InternalEvent.BROADCAST_REQUEST_SENT, | ||
error: events_1.InternalEvent.BROADCAST_REQUEST_ERROR | ||
}, | ||
[__1.BeaconMessageType.BroadcastResponse]: { | ||
success: events_1.InternalEvent.UNKNOWN, | ||
error: events_1.InternalEvent.UNKNOWN | ||
} | ||
}; | ||
class DAppClient extends __1.BaseClient { | ||
constructor(name) { | ||
constructor(name, iconUrl) { | ||
super(name); | ||
this.events = new events_1.InternalEventHandler(); | ||
this.openRequests = new Map(); | ||
this.handleResponse = (event) => { | ||
this.iconUrl = iconUrl; | ||
this.handleResponse = (event, connectionInfo) => { | ||
const openRequest = this.openRequests.get(event.id); | ||
@@ -20,9 +57,7 @@ if (openRequest) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
if (event.error) { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
if (event.errorType) { | ||
openRequest.reject(event); | ||
} | ||
else { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
openRequest.resolve(event); | ||
openRequest.resolve({ message: event, connectionInfo }); | ||
} | ||
@@ -63,15 +98,11 @@ this.openRequests.delete(event.id); | ||
} | ||
async makeRequest(request) { | ||
logger.log('makeRequest'); | ||
await this.init(); | ||
await this.connect(); | ||
logger.log('makeRequest', 'after connecting'); | ||
const payload = await this.serializer.serialize(request); | ||
const exposed = exposed_promise_1.exposedPromise(); | ||
this.addOpenRequest(request.id, exposed); | ||
if (!this.transport) { | ||
throw new Error('No transport'); | ||
async getAppMetadata() { | ||
if (!this.beaconId) { | ||
throw new Error('BeaconID not defined'); | ||
} | ||
await this.transport.send(payload, {}); | ||
return exposed.promise; | ||
return { | ||
beaconId: this.beaconId, | ||
name: this.name, | ||
icon: this.iconUrl | ||
}; | ||
} | ||
@@ -81,6 +112,6 @@ async connect() { | ||
} | ||
async checkPermissions(type, identifier) { | ||
const accountInfo = await this.getAccount(identifier); | ||
async checkPermissions(type) { | ||
const accountInfo = this.activeAccount; | ||
if (!accountInfo) { | ||
return false; | ||
throw new Error('No active account set!'); | ||
} | ||
@@ -92,2 +123,3 @@ switch (type) { | ||
return accountInfo.scopes.some((permission) => permission === __1.PermissionScope.SIGN); | ||
case __1.BeaconMessageType.PermissionRequest: | ||
case __1.BeaconMessageType.BroadcastRequest: | ||
@@ -99,106 +131,103 @@ return true; | ||
} | ||
async requestPermissions(request) { | ||
if (!this.beaconId) { | ||
throw new Error('BeaconID not defined'); | ||
} | ||
if (await this.addRequestAndCheckIfRateLimited()) { | ||
this.events | ||
.emit(events_1.InternalEvent.LOCAL_RATE_LIMIT_REACHED) | ||
.catch((emitError) => console.warn(emitError)); | ||
throw new Error('rate limit reached'); | ||
} | ||
this.events | ||
.emit(events_1.InternalEvent.PERMISSION_REQUEST_SENT) | ||
.catch((emitError) => console.warn(emitError)); | ||
return this.makeRequest({ | ||
id: generate_uuid_1.generateGUID(), | ||
beaconId: this.beaconId, | ||
appMetadata: { | ||
name: this.name | ||
}, | ||
async requestPermissions(input) { | ||
const request = { | ||
appMetadata: await this.getAppMetadata(), | ||
type: __1.BeaconMessageType.PermissionRequest, | ||
network: request && request.network ? request.network : { type: __1.NetworkType.MAINNET }, | ||
scopes: request && request.scopes | ||
? request.scopes | ||
network: input && input.network ? input.network : { type: __1.NetworkType.MAINNET }, | ||
scopes: input && input.scopes | ||
? input.scopes | ||
: [__1.PermissionScope.READ_ADDRESS, __1.PermissionScope.OPERATION_REQUEST, __1.PermissionScope.SIGN] | ||
}) | ||
.catch((error) => { | ||
console.log('error', error); | ||
throw new Error(error); | ||
}) | ||
.then(async (response) => { | ||
if (response.errorType) { | ||
console.log('error', response.errorType); | ||
throw new Error(response.errorType); | ||
} | ||
const accountInfo = { | ||
accountIdentifier: response.accountIdentifier, | ||
beaconId: response.beaconId, | ||
origin: { | ||
type: __1.Origin.P2P, | ||
id: response.beaconId | ||
}, | ||
pubkey: response.pubkey, | ||
network: response.network, | ||
scopes: response.scopes, | ||
connectedAt: new Date() | ||
}; | ||
this.activeAccount = accountInfo; | ||
await this.addAccount(accountInfo); | ||
console.log('permissions interception', response); | ||
return response; | ||
}; | ||
const response = await this.makeRequest(request).catch(async (requestError) => { | ||
throw this.handleRequestError(request, requestError); | ||
}); | ||
const { message, connectionInfo } = response; | ||
await this.handleBeaconError(message); | ||
const address = message.pubkey ? await crypto_1.getAddressFromPublicKey(message.pubkey) : undefined; | ||
const accountInfo = { | ||
accountIdentifier: message.accountIdentifier, | ||
beaconId: message.beaconId, | ||
origin: { | ||
type: connectionInfo.origin, | ||
id: connectionInfo.id | ||
}, | ||
address, | ||
pubkey: message.pubkey, | ||
network: message.network, | ||
scopes: message.scopes, | ||
connectedAt: new Date() | ||
}; | ||
this.activeAccount = accountInfo; | ||
await this.addAccount(accountInfo); | ||
console.log('permissions interception', response); | ||
const { beaconId, network, scopes } = message; | ||
return { beaconId, address, network, scopes }; | ||
} | ||
async requestSignPayload(request) { | ||
if (!this.beaconId) { | ||
throw new Error('BeaconID not defined'); | ||
} | ||
if (!request.payload) { | ||
async requestSignPayload(input) { | ||
if (!input.payload) { | ||
throw new Error('Payload must be provided'); | ||
} | ||
if (!this.activeAccount) { | ||
throw new Error('No account is active'); | ||
} | ||
if (await this.addRequestAndCheckIfRateLimited()) { | ||
this.events | ||
.emit(events_1.InternalEvent.LOCAL_RATE_LIMIT_REACHED) | ||
.catch((emitError) => console.warn(emitError)); | ||
throw new Error('rate limit reached'); | ||
} | ||
const req = { | ||
id: generate_uuid_1.generateGUID(), | ||
beaconId: this.beaconId, | ||
const request = { | ||
type: __1.BeaconMessageType.SignPayloadRequest, | ||
payload: request.payload, | ||
sourceAddress: request.sourceAddress || '' | ||
payload: input.payload, | ||
sourceAddress: input.sourceAddress || '' | ||
}; | ||
if (await this.checkPermissions(req.type, this.activeAccount.accountIdentifier)) { | ||
this.events | ||
.emit(events_1.InternalEvent.SIGN_REQUEST_SENT) | ||
.catch((emitError) => console.warn(emitError)); | ||
this.events | ||
.emit(events_1.InternalEvent.OPERATION_REQUEST_SENT) | ||
.catch((emitError) => console.warn(emitError)); | ||
return this.makeRequest(req).catch((error) => { | ||
console.log('error', error); | ||
throw new Error(error); | ||
}); | ||
const response = await this.makeRequest(request).catch(async (requestError) => { | ||
throw this.handleRequestError(request, requestError); | ||
}); | ||
await this.handleBeaconError(response.message); | ||
const { beaconId, signature } = response.message; | ||
return { beaconId, signature }; | ||
} | ||
async requestOperation(input) { | ||
if (!input.operationDetails) { | ||
throw new Error('Operation details must be provided'); | ||
} | ||
else { | ||
this.events | ||
.emit(events_1.InternalEvent.SIGN_REQUEST_ERROR) | ||
.catch((emitError) => console.warn(emitError)); | ||
throw new Error('No permissions to send this request to wallet!'); | ||
const request = { | ||
type: __1.BeaconMessageType.OperationRequest, | ||
network: input.network || { type: __1.NetworkType.MAINNET }, | ||
operationDetails: input.operationDetails // TODO: Fix type | ||
}; | ||
const response = await this.makeRequest(request).catch(async (requestError) => { | ||
throw this.handleRequestError(request, requestError); | ||
}); | ||
await this.handleBeaconError(response.message); | ||
const { beaconId, transactionHash } = response.message; | ||
return { beaconId, transactionHash }; | ||
} | ||
async requestBroadcast(input) { | ||
if (!input.signedTransaction) { | ||
throw new Error('Signed transaction must be provided'); | ||
} | ||
const request = { | ||
type: __1.BeaconMessageType.BroadcastRequest, | ||
network: input.network || { type: __1.NetworkType.MAINNET }, | ||
signedTransaction: input.signedTransaction | ||
}; | ||
const response = await this.makeRequest(request).catch(async (requestError) => { | ||
throw this.handleRequestError(request, requestError); | ||
}); | ||
await this.handleBeaconError(response.message); | ||
const { beaconId, transactionHash } = response.message; | ||
return { beaconId, transactionHash }; | ||
} | ||
async requestOperation(request) { | ||
if (!this.beaconId) { | ||
throw new Error('BeaconID not defined'); | ||
async handleRequestError(request, error) { | ||
console.error('requestError', error); | ||
this.events | ||
.emit(messageEvents[request.type].error) | ||
.catch((emitError) => console.warn(emitError)); | ||
throw error; | ||
} | ||
async handleBeaconError(message) { | ||
const errorMessage = message; | ||
if (errorMessage.errorType) { | ||
console.log('error', errorMessage.errorType); | ||
throw new Error(errorMessage.errorType); | ||
} | ||
if (!request.operationDetails) { | ||
throw new Error('Operation details must be provided'); | ||
} | ||
if (!this.activeAccount) { | ||
throw new Error('No account is active'); | ||
} | ||
} | ||
async makeRequest(requestInput) { | ||
logger.log('makeRequest'); | ||
await this.init(); | ||
await this.connect(); | ||
logger.log('makeRequest', 'after connecting'); | ||
if (await this.addRequestAndCheckIfRateLimited()) { | ||
@@ -210,63 +239,26 @@ this.events | ||
} | ||
const req = { | ||
id: generate_uuid_1.generateGUID(), | ||
beaconId: this.beaconId, | ||
type: __1.BeaconMessageType.OperationRequest, | ||
network: request.network || { type: __1.NetworkType.MAINNET }, | ||
operationDetails: request.operationDetails // TODO: Fix type | ||
}; | ||
if (await this.checkPermissions(req.type, this.activeAccount.accountIdentifier)) { | ||
this.events | ||
.emit(events_1.InternalEvent.OPERATION_REQUEST_SENT) | ||
.catch((emitError) => console.warn(emitError)); | ||
return this.makeRequest(req).catch((error) => { | ||
console.log('error', error); | ||
throw new Error(error); | ||
}); | ||
} | ||
else { | ||
this.events | ||
.emit(events_1.InternalEvent.OPERATION_REQUEST_ERROR) | ||
.catch((emitError) => console.warn(emitError)); | ||
if (!(await this.checkPermissions(requestInput.type))) { | ||
this.events.emit(events_1.InternalEvent.NO_PERMISSIONS).catch((emitError) => console.warn(emitError)); | ||
throw new Error('No permissions to send this request to wallet!'); | ||
} | ||
} | ||
async requestBroadcast(request) { | ||
this.events | ||
.emit(messageEvents[requestInput.type].success) | ||
.catch((emitError) => console.warn(emitError)); | ||
const payload = await this.serializer.serialize(requestInput); | ||
if (!this.beaconId) { | ||
throw new Error('BeaconID not defined'); | ||
} | ||
if (!request.signedTransaction) { | ||
throw new Error('Signed transaction must be provided'); | ||
} | ||
if (!this.activeAccount) { | ||
throw new Error('No account is active'); | ||
} | ||
if (await this.addRequestAndCheckIfRateLimited()) { | ||
this.events | ||
.emit(events_1.InternalEvent.LOCAL_RATE_LIMIT_REACHED) | ||
.catch((emitError) => console.warn(emitError)); | ||
throw new Error('rate limit reached'); | ||
} | ||
const req = { | ||
const request = { | ||
id: generate_uuid_1.generateGUID(), | ||
version: constants_1.SDK_VERSION, | ||
beaconId: this.beaconId, | ||
type: __1.BeaconMessageType.BroadcastRequest, | ||
network: request.network || { type: __1.NetworkType.MAINNET }, | ||
signedTransaction: request.signedTransaction | ||
...requestInput | ||
}; | ||
if (await this.checkPermissions(req.type, this.activeAccount.accountIdentifier)) { | ||
this.events | ||
.emit(events_1.InternalEvent.BROADCAST_REQUEST_SENT) | ||
.catch((emitError) => console.warn(emitError)); | ||
return this.makeRequest(req).catch((error) => { | ||
console.log('error', error); | ||
throw new Error(error); | ||
}); | ||
const exposed = exposed_promise_1.exposedPromise(); | ||
this.addOpenRequest(request.id, exposed); | ||
if (!this.transport) { | ||
throw new Error('No transport'); | ||
} | ||
else { | ||
this.events | ||
.emit(events_1.InternalEvent.BROADCAST_REQUEST_ERROR) | ||
.catch((emitError) => console.warn(emitError)); | ||
throw new Error('No permissions to send this request to wallet!'); | ||
} | ||
await this.transport.send(payload); | ||
return exposed.promise; | ||
} | ||
@@ -273,0 +265,0 @@ async setActiveAccount(account) { |
@@ -1,7 +0,31 @@ | ||
import { BaseClient, BeaconBaseMessage, TransportType } from '..'; | ||
import { ConnectionContext } from '../types/ConnectionContext'; | ||
import { BaseClient, TransportType, PermissionRequest, OperationRequest, SignPayloadRequest, BroadcastRequest, PermissionResponse, OperationResponse, SignPayloadResponse, BroadcastResponse, AppMetadata, BeaconMessageType, PermissionScope } from '..'; | ||
declare type IgnoredResponseOutputProperties = 'version'; | ||
interface ExtraResponseOutputProperties { | ||
appMetadata: AppMetadata; | ||
} | ||
export declare type PermissionRequestOutput = Omit<PermissionRequest, IgnoredResponseOutputProperties> & ExtraResponseOutputProperties; | ||
export declare type OperationRequestOutput = Omit<OperationRequest, IgnoredResponseOutputProperties> & ExtraResponseOutputProperties; | ||
export declare type SignPayloadRequestOutput = Omit<SignPayloadRequest, IgnoredResponseOutputProperties> & ExtraResponseOutputProperties; | ||
export declare type BroadcastRequestOutput = Omit<BroadcastRequest, IgnoredResponseOutputProperties> & ExtraResponseOutputProperties; | ||
declare type BeaconMessagesOutput = PermissionRequestOutput | OperationRequestOutput | SignPayloadRequestOutput | BroadcastRequestOutput; | ||
declare type IgnoredResponseInputProperties = 'beaconId' | 'version'; | ||
export declare type PermissionResponseInput = Omit<PermissionResponse, IgnoredResponseInputProperties>; | ||
export declare type OperationResponseInput = Omit<OperationResponse, IgnoredResponseInputProperties>; | ||
export declare type SignPayloadResponseInput = Omit<SignPayloadResponse, IgnoredResponseInputProperties>; | ||
export declare type BroadcastResponseInput = Omit<BroadcastResponse, IgnoredResponseInputProperties>; | ||
declare type BeaconMessagesInput = PermissionResponseInput | OperationResponseInput | SignPayloadResponseInput | BroadcastResponseInput; | ||
export declare class WalletClient extends BaseClient { | ||
private pendingRequests; | ||
init(): Promise<TransportType>; | ||
connect(newMessageCallback: (message: BeaconBaseMessage, connectionInfo: any) => void): Promise<boolean>; | ||
respond(message: BeaconBaseMessage): Promise<void>; | ||
getAppMetadata(beaconId: string): Promise<{ | ||
appMetadata: AppMetadata; | ||
connectionContext: ConnectionContext; | ||
}>; | ||
saveAppMetadata(message: PermissionRequest, connectionInfo: ConnectionContext): Promise<void>; | ||
checkPermissions(type: BeaconMessageType, permissions: PermissionScope[]): Promise<boolean>; | ||
connect(newMessageCallback: (message: BeaconMessagesOutput, connectionInfo: ConnectionContext) => void): Promise<boolean>; | ||
respond(message: BeaconMessagesInput): Promise<void>; | ||
private respondToMessage; | ||
} | ||
export {}; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const constants_1 = require("../constants"); | ||
const __1 = require(".."); | ||
@@ -12,8 +13,76 @@ class WalletClient extends __1.BaseClient { | ||
} | ||
async getAppMetadata(beaconId) { | ||
console.log(beaconId); | ||
return { | ||
appMetadata: { | ||
beaconId: 'placeholder_from_sdk', | ||
name: 'placeholder_from_sdk' | ||
}, | ||
connectionContext: { origin: __1.Origin.EXTENSION, id: 'placeholder_from_sdk' } | ||
}; | ||
} | ||
async saveAppMetadata(message, connectionInfo) { | ||
console.log(message, connectionInfo); | ||
} | ||
// public async getPermission(_beaconId: string) {} | ||
// public async savePermission() {} | ||
async checkPermissions(type, permissions) { | ||
switch (type) { | ||
case __1.BeaconMessageType.OperationRequest: | ||
return permissions.some((permission) => permission === __1.PermissionScope.OPERATION_REQUEST); | ||
case __1.BeaconMessageType.SignPayloadRequest: | ||
return permissions.some((permission) => permission === __1.PermissionScope.SIGN); | ||
case __1.BeaconMessageType.PermissionRequest: | ||
case __1.BeaconMessageType.BroadcastRequest: | ||
return true; | ||
default: | ||
return false; | ||
} | ||
} | ||
async connect(newMessageCallback) { | ||
this.handleResponse = (message, connectionInfo) => { | ||
this.handleResponse = async (message, connectionInfo) => { | ||
if (!this.pendingRequests.some((request) => request.id === message.id)) { | ||
this.pendingRequests.push(message); | ||
console.log('PUSHING NEW REQUEST', message, connectionInfo); | ||
newMessageCallback(message, connectionInfo); | ||
switch (message.type) { | ||
case __1.BeaconMessageType.PermissionRequest: | ||
{ | ||
await this.saveAppMetadata(message, connectionInfo); | ||
const request = message; | ||
newMessageCallback(request, connectionInfo); | ||
} | ||
break; | ||
case __1.BeaconMessageType.OperationRequest: | ||
{ | ||
const appMetadata = await this.getAppMetadata(message.beaconId); | ||
const request = { | ||
appMetadata: appMetadata.appMetadata, | ||
...message | ||
}; | ||
newMessageCallback(request, connectionInfo); | ||
} | ||
break; | ||
case __1.BeaconMessageType.SignPayloadRequest: | ||
{ | ||
const appMetadata = await this.getAppMetadata(message.beaconId); | ||
const request = { | ||
appMetadata: appMetadata.appMetadata, | ||
...message | ||
}; | ||
newMessageCallback(request, connectionInfo); | ||
} | ||
break; | ||
case __1.BeaconMessageType.BroadcastRequest: | ||
{ | ||
const appMetadata = await this.getAppMetadata(message.beaconId); | ||
const request = { | ||
appMetadata: appMetadata.appMetadata, | ||
...message | ||
}; | ||
newMessageCallback(request, connectionInfo); | ||
} | ||
break; | ||
default: | ||
console.log('Message not handled'); | ||
} | ||
} | ||
@@ -24,12 +93,61 @@ }; | ||
async respond(message) { | ||
const serializedMessage = await this.serializer.serialize(message); | ||
console.log('responding to message', message); | ||
const request = this.pendingRequests.find((pendingRequest) => pendingRequest.id === message.id); | ||
if (request) { | ||
this.pendingRequests = this.pendingRequests.filter((pendingRequest) => pendingRequest.id !== message.id); | ||
if (!request) { | ||
throw new Error('No matching request found!'); | ||
} | ||
this.pendingRequests = this.pendingRequests.filter((pendingRequest) => pendingRequest.id !== message.id); | ||
const beaconId = this.beaconId ? this.beaconId : ''; | ||
const version = constants_1.SDK_VERSION; | ||
switch (message.type) { | ||
case __1.BeaconMessageType.PermissionResponse: { | ||
const response = { | ||
beaconId, | ||
version, | ||
...message | ||
}; | ||
// this.savePermission(response.) | ||
await this.respondToMessage(response); | ||
break; | ||
} | ||
case __1.BeaconMessageType.OperationResponse: | ||
{ | ||
const response = { | ||
beaconId, | ||
version, | ||
...message | ||
}; | ||
await this.respondToMessage(response); | ||
} | ||
break; | ||
case __1.BeaconMessageType.SignPayloadResponse: | ||
{ | ||
const response = { | ||
beaconId, | ||
version, | ||
...message | ||
}; | ||
await this.respondToMessage(response); | ||
} | ||
break; | ||
case __1.BeaconMessageType.BroadcastResponse: | ||
{ | ||
const response = { | ||
beaconId, | ||
version, | ||
...message | ||
}; | ||
await this.respondToMessage(response); | ||
} | ||
break; | ||
default: | ||
console.log('Message not handled'); | ||
} | ||
} | ||
async respondToMessage(message) { | ||
if (!this.transport) { | ||
throw new Error('no transport defined'); | ||
} | ||
this.transport.send(serializedMessage, {}); | ||
const serializedMessage = await this.serializer.serialize(message); | ||
await this.transport.send(serializedMessage); | ||
} | ||
@@ -36,0 +154,0 @@ } |
@@ -10,3 +10,5 @@ export declare enum InternalEvent { | ||
BROADCAST_REQUEST_ERROR = "BROADCAST_REQUEST_ERROR", | ||
LOCAL_RATE_LIMIT_REACHED = "LOCAL_RATE_LIMIT_REACHED" | ||
LOCAL_RATE_LIMIT_REACHED = "LOCAL_RATE_LIMIT_REACHED", | ||
NO_PERMISSIONS = "NO_PERMISSIONS", | ||
UNKNOWN = "UNKNOWN" | ||
} | ||
@@ -13,0 +15,0 @@ export declare class InternalEventHandler { |
@@ -16,2 +16,4 @@ "use strict"; | ||
InternalEvent["LOCAL_RATE_LIMIT_REACHED"] = "LOCAL_RATE_LIMIT_REACHED"; | ||
InternalEvent["NO_PERMISSIONS"] = "NO_PERMISSIONS"; | ||
InternalEvent["UNKNOWN"] = "UNKNOWN"; | ||
})(InternalEvent = exports.InternalEvent || (exports.InternalEvent = {})); | ||
@@ -62,2 +64,11 @@ const listenerFallback = async (data) => { | ||
}).catch((toastError) => console.error(toastError)); | ||
}, | ||
[InternalEvent.NO_PERMISSIONS]: async (_data) => { | ||
Toast_1.openToast({ | ||
body: 'No permissions!', | ||
timer: 3000 | ||
}).catch((toastError) => console.error(toastError)); | ||
}, | ||
[InternalEvent.UNKNOWN]: async (_data) => { | ||
/* Do nothing */ | ||
} | ||
@@ -74,3 +85,5 @@ }; | ||
[InternalEvent.BROADCAST_REQUEST_ERROR]: [], | ||
[InternalEvent.LOCAL_RATE_LIMIT_REACHED]: [] | ||
[InternalEvent.LOCAL_RATE_LIMIT_REACHED]: [], | ||
[InternalEvent.NO_PERMISSIONS]: [], | ||
[InternalEvent.UNKNOWN]: [] | ||
}; | ||
@@ -77,0 +90,0 @@ } |
@@ -39,3 +39,3 @@ import { WalletCommunicationClient } from './WalletCommunicationClient'; | ||
import { WalletClient } from './clients/WalletClient'; | ||
import { DAppClient } from './clients/DAppClient'; | ||
import { DAppClient, PermissionResponseOutput, SignPayloadResponseOutput, OperationResponseOutput, BroadcastResponseOutput } from './clients/DAppClient'; | ||
import { BeaconError } from './errors/BeaconError'; | ||
@@ -79,6 +79,6 @@ import { BeaconErrorType } from './types/BeaconErrorType'; | ||
export { BaseClient, DAppClient, WalletClient }; | ||
export { AccountIdentifier, AppMetadata, Network, NetworkType, BeaconMessages, PermissionRequest, PermissionResponse, OperationRequest, OperationResponse, SignPayloadRequest, SignPayloadResponse, BroadcastRequest, BroadcastResponse, BeaconBaseMessage, BeaconMessageType, PermissionScope, Origin, AccountInfo, ExtensionMessageTarget, ExtensionMessage, RequestPermissionInput, RequestSignPayloadInput, RequestOperationInput, RequestBroadcastInput }; | ||
export { AccountIdentifier, AppMetadata, Network, NetworkType, BeaconMessages, PermissionRequest, PermissionResponse, OperationRequest, OperationResponse, SignPayloadRequest, SignPayloadResponse, BroadcastRequest, BroadcastResponse, BeaconBaseMessage, BeaconMessageType, PermissionScope, Origin, AccountInfo, ExtensionMessageTarget, ExtensionMessage, RequestPermissionInput, RequestSignPayloadInput, RequestOperationInput, RequestBroadcastInput, PermissionResponseOutput, SignPayloadResponseOutput, OperationResponseOutput, BroadcastResponseOutput }; | ||
export { BeaconError, BeaconErrorType, BeaconErrorMessage, BroadcastBeaconError, NetworkNotSupportedBeaconError, NoAddressBeaconError, NoPrivateKeyBeaconError, NotGrantedBeaconError, ParametersInvalidBeaconError, TooManyOperationsBeaconError, TransactionInvalidBeaconError, UnknownBeaconError }; | ||
export { TransportStatus, TransportType, Transport, PostMessageTransport, P2PTransport, LocalTransport, ChromeMessageTransport }; | ||
export { Storage, StorageKey, StorageKeyReturnDefaults, StorageKeyReturnType, ChromeStorage, FileStorage, LocalStorage, getStorage }; | ||
export { P2PPairInfo as ICommunicationPair, Serializer }; | ||
export { P2PPairInfo, Serializer }; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const Storage_1 = require("./Storage"); | ||
const StorageKeyReturnDefaults_1 = require("../types/storage/StorageKeyReturnDefaults"); | ||
class ChromeStorage { | ||
@@ -19,3 +19,3 @@ static async isSupported() { | ||
else { | ||
resolve(Storage_1.defaultValues[key]); | ||
resolve(StorageKeyReturnDefaults_1.defaultValues[key]); | ||
} | ||
@@ -22,0 +22,0 @@ }); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const fs_1 = require("fs"); | ||
const Storage_1 = require("./Storage"); | ||
const StorageKeyReturnDefaults_1 = require("../types/storage/StorageKeyReturnDefaults"); | ||
const file = './storage.json'; | ||
@@ -46,3 +46,3 @@ /* eslint-disable prefer-arrow/prefer-arrow-functions */ | ||
else { | ||
return Storage_1.defaultValues[key]; | ||
return StorageKeyReturnDefaults_1.defaultValues[key]; | ||
} | ||
@@ -49,0 +49,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const Storage_1 = require("./Storage"); | ||
const StorageKeyReturnDefaults_1 = require("../types/storage/StorageKeyReturnDefaults"); | ||
class LocalStorage { | ||
@@ -11,3 +11,3 @@ static async isSupported() { | ||
if (!value) { | ||
return Storage_1.defaultValues[key]; | ||
return StorageKeyReturnDefaults_1.defaultValues[key]; | ||
} | ||
@@ -14,0 +14,0 @@ else { |
@@ -1,5 +0,3 @@ | ||
import { StorageKeyReturnDefaults } from '../types/storage/StorageKeyReturnDefaults'; | ||
import { StorageKey } from '../types/storage/StorageKey'; | ||
import { StorageKeyReturnType } from '../types/storage/StorageKeyReturnType'; | ||
export declare const defaultValues: StorageKeyReturnDefaults; | ||
export declare abstract class Storage { | ||
@@ -6,0 +4,0 @@ static isSupported(): Promise<boolean>; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const StorageKey_1 = require("../types/storage/StorageKey"); | ||
exports.defaultValues = { | ||
[StorageKey_1.StorageKey.TRANSPORT_P2P_SECRET_KEY]: undefined, | ||
[StorageKey_1.StorageKey.TRANSPORT_P2P_PEERS]: [], | ||
[StorageKey_1.StorageKey.ACCOUNTS]: [], | ||
[StorageKey_1.StorageKey.ACTIVE_ACCOUNT]: undefined, | ||
[StorageKey_1.StorageKey.BEACON_SDK_ID]: undefined | ||
}; | ||
class Storage { | ||
@@ -12,0 +4,0 @@ static isSupported() { |
@@ -28,3 +28,7 @@ "use strict"; | ||
logger.log('init', 'receiving chrome message', message, sender); | ||
const connectionContext = { sender, sendResponse }; | ||
const connectionContext = { | ||
origin: __1.Origin.EXTENSION, | ||
id: sender.id ? sender.id : '', | ||
extras: { sender, sendResponse } | ||
}; | ||
this.notifyListeners(message, connectionContext).catch((error) => logger.error(error)); | ||
@@ -31,0 +35,0 @@ // return true from the event listener to indicate you wish to send a response asynchronously |
@@ -0,1 +1,2 @@ | ||
import * as sodium from 'libsodium-wrappers'; | ||
import { Storage, Transport, TransportType } from '..'; | ||
@@ -6,4 +7,5 @@ export declare class P2PTransport extends Transport { | ||
private readonly storage; | ||
private readonly keyPair; | ||
private client; | ||
constructor(name: string, storage: Storage, isDapp: boolean); | ||
constructor(name: string, keyPair: sodium.KeyPair, storage: Storage, isDapp: boolean); | ||
static isAvailable(): Promise<boolean>; | ||
@@ -17,4 +19,3 @@ connect(): Promise<void>; | ||
send(message: string): Promise<void>; | ||
private getOrCreateKey; | ||
private listen; | ||
} |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const Alert_1 = require("../alert/Alert"); | ||
const generate_uuid_1 = require("../utils/generate-uuid"); | ||
const Logger_1 = require("../utils/Logger"); | ||
@@ -9,6 +8,7 @@ const __1 = require(".."); | ||
class P2PTransport extends __1.Transport { | ||
constructor(name, storage, isDapp) { | ||
constructor(name, keyPair, storage, isDapp) { | ||
super(name); | ||
this.type = __1.TransportType.P2P; | ||
this.isDapp = true; | ||
this.keyPair = keyPair; | ||
this.storage = storage; | ||
@@ -23,4 +23,3 @@ this.isDapp = isDapp; | ||
this._isConnected = __1.TransportStatus.CONNECTING; | ||
const key = await this.getOrCreateKey(); | ||
this.client = new __1.WalletCommunicationClient(this.name, key, 1, false); | ||
this.client = new __1.WalletCommunicationClient(this.name, this.keyPair, 1, false); | ||
await this.client.start(); | ||
@@ -126,16 +125,2 @@ const knownPeers = await this.storage.get(__1.StorageKey.TRANSPORT_P2P_PEERS); | ||
} | ||
async getOrCreateKey() { | ||
if (!this.storage) { | ||
throw new Error('no storage'); | ||
} | ||
const storageValue = await this.storage.get(__1.StorageKey.TRANSPORT_P2P_SECRET_KEY); | ||
if (storageValue && typeof storageValue === 'string') { | ||
return storageValue; | ||
} | ||
else { | ||
const key = generate_uuid_1.generateGUID(); | ||
await this.storage.set(__1.StorageKey.TRANSPORT_P2P_SECRET_KEY, key); | ||
return key; | ||
} | ||
} | ||
async listen(pubKey) { | ||
@@ -147,3 +132,7 @@ if (!this.client) { | ||
.listenForEncryptedMessage(pubKey, (message) => { | ||
this.notifyListeners(message, { pubKey }).catch((error) => { | ||
const connectionContext = { | ||
origin: __1.Origin.P2P, | ||
id: pubKey | ||
}; | ||
this.notifyListeners(message, connectionContext).catch((error) => { | ||
throw error; | ||
@@ -150,0 +139,0 @@ }); |
@@ -0,1 +1,2 @@ | ||
import { ConnectionContext } from '../types/ConnectionContext'; | ||
import { TransportType, TransportStatus } from '..'; | ||
@@ -16,6 +17,6 @@ export declare abstract class Transport { | ||
connect(): Promise<void>; | ||
send(message: string, connectionInfo: any): Promise<void>; | ||
addListener(listener: (message: unknown, connectionInfo: any) => void): Promise<void>; | ||
removeListener(listener: (message: string, connectionInfo: any) => void): Promise<void>; | ||
protected notifyListeners(message: unknown, connectionInfo: any): Promise<void>; | ||
send(message: string): Promise<void>; | ||
addListener(listener: (message: unknown, connectionInfo: ConnectionContext) => void): Promise<void>; | ||
removeListener(listener: (message: string, connectionInfo: ConnectionContext) => void): Promise<void>; | ||
protected notifyListeners(message: unknown, connectionInfo: ConnectionContext): Promise<void>; | ||
} |
@@ -43,5 +43,4 @@ "use strict"; | ||
} | ||
async send(message, connectionInfo) { | ||
logger.log('send', message, connectionInfo); | ||
await this.notifyListeners(message, connectionInfo); | ||
async send(message) { | ||
logger.log('send', message); | ||
return; | ||
@@ -48,0 +47,0 @@ } |
@@ -10,2 +10,3 @@ import { Origin, Network, PermissionScope } from '..'; | ||
}; | ||
address?: string; | ||
pubkey?: string; | ||
@@ -12,0 +13,0 @@ network: Network; |
export interface AppMetadata { | ||
beaconId: string; | ||
name: string; | ||
icon?: string; | ||
} |
import { BeaconMessageType } from '../..'; | ||
export interface BeaconBaseMessage { | ||
type: BeaconMessageType; | ||
version: string; | ||
id: string; | ||
beaconId: string; | ||
} |
export declare enum StorageKey { | ||
TRANSPORT_P2P_SECRET_KEY = "beacon:communication-secret-key", | ||
TRANSPORT_P2P_PEERS = "beacon:communication-peers", | ||
ACCOUNTS = "beacon:accounts", | ||
ACTIVE_ACCOUNT = "beacon:active-account", | ||
BEACON_SDK_ID = "beacon:sdk-id" | ||
BEACON_SDK_SECRET_SEED = "beacon:sdk-secret-seed" | ||
} |
@@ -5,8 +5,7 @@ "use strict"; | ||
(function (StorageKey) { | ||
StorageKey["TRANSPORT_P2P_SECRET_KEY"] = "beacon:communication-secret-key"; | ||
StorageKey["TRANSPORT_P2P_PEERS"] = "beacon:communication-peers"; | ||
StorageKey["ACCOUNTS"] = "beacon:accounts"; | ||
StorageKey["ACTIVE_ACCOUNT"] = "beacon:active-account"; | ||
StorageKey["BEACON_SDK_ID"] = "beacon:sdk-id"; | ||
StorageKey["BEACON_SDK_SECRET_SEED"] = "beacon:sdk-secret-seed"; | ||
})(StorageKey = exports.StorageKey || (exports.StorageKey = {})); | ||
//# sourceMappingURL=StorageKey.js.map |
@@ -5,1 +5,2 @@ import { StorageKey, StorageKeyReturnType } from '../..'; | ||
}; | ||
export declare const defaultValues: StorageKeyReturnDefaults; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const __1 = require("../.."); | ||
exports.defaultValues = { | ||
[__1.StorageKey.TRANSPORT_P2P_PEERS]: [], | ||
[__1.StorageKey.ACCOUNTS]: [], | ||
[__1.StorageKey.ACTIVE_ACCOUNT]: undefined, | ||
[__1.StorageKey.BEACON_SDK_SECRET_SEED]: undefined | ||
}; | ||
//# sourceMappingURL=StorageKeyReturnDefaults.js.map |
@@ -1,8 +0,7 @@ | ||
import { StorageKey, AccountInfo, AccountIdentifier, ICommunicationPair } from '../..'; | ||
import { StorageKey, AccountInfo, AccountIdentifier, P2PPairInfo } from '../..'; | ||
export interface StorageKeyReturnType { | ||
[StorageKey.TRANSPORT_P2P_SECRET_KEY]: string | undefined; | ||
[StorageKey.TRANSPORT_P2P_PEERS]: ICommunicationPair[]; | ||
[StorageKey.TRANSPORT_P2P_PEERS]: P2PPairInfo[]; | ||
[StorageKey.ACCOUNTS]: AccountInfo[]; | ||
[StorageKey.ACTIVE_ACCOUNT]: AccountIdentifier | undefined; | ||
[StorageKey.BEACON_SDK_ID]: string | undefined; | ||
[StorageKey.BEACON_SDK_SECRET_SEED]: string | undefined; | ||
} |
@@ -5,3 +5,3 @@ /// <reference types="node" /> | ||
export declare function getHexHash(key: string | Buffer | Uint8Array): string; | ||
export declare function getKeypairFromSeed(seed: string): sodium.KeyPair; | ||
export declare function getKeypairFromSeed(seed: string): Promise<sodium.KeyPair>; | ||
export declare function encryptCryptoboxPayload(message: string, sharedKey: Uint8Array): string; | ||
@@ -11,2 +11,3 @@ export declare function decryptCryptoboxPayload(payload: Uint8Array, sharedKey: Uint8Array): string; | ||
export declare function openCryptobox(encryptedPayload: string | Buffer, publicKey: Uint8Array, privateKey: Uint8Array): string; | ||
export declare function getAddressFromPublicKey(publicKey: string): Promise<string>; | ||
export declare function recipientString(recipientHash: string, relayServer: string): string; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const sodium = require("libsodium-wrappers"); | ||
const bs58check = require("bs58check"); | ||
/* eslint-disable prefer-arrow/prefer-arrow-functions */ | ||
@@ -14,3 +15,4 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
exports.getHexHash = getHexHash; | ||
function getKeypairFromSeed(seed) { | ||
async function getKeypairFromSeed(seed) { | ||
await sodium.ready; | ||
return sodium.crypto_sign_seed_keypair(sodium.crypto_generichash(32, sodium.from_string(seed))); | ||
@@ -47,2 +49,9 @@ } | ||
exports.openCryptobox = openCryptobox; | ||
async function getAddressFromPublicKey(publicKey) { | ||
await sodium.ready; | ||
const payload = sodium.crypto_generichash(20, Buffer.from(publicKey, 'hex')); | ||
const tz1Prefix = Buffer.from(new Uint8Array([6, 161, 159])); | ||
return bs58check.encode(Buffer.concat([tz1Prefix, Buffer.from(payload)])); | ||
} | ||
exports.getAddressFromPublicKey = getAddressFromPublicKey; | ||
function recipientString(recipientHash, relayServer) { | ||
@@ -49,0 +58,0 @@ return `@${recipientHash}:${relayServer}`; |
@@ -7,3 +7,3 @@ export declare enum ExposedPromiseStatus { | ||
} | ||
export interface ExposedPromise<T> { | ||
export interface ExposedPromise<T, U = unknown> { | ||
promise: Promise<T>; | ||
@@ -14,4 +14,4 @@ status: ExposedPromiseStatus; | ||
resolve(value?: T | PromiseLike<T>): void; | ||
reject(reason?: unknown): void; | ||
reject(reason?: U): void; | ||
} | ||
export declare function exposedPromise<T>(): ExposedPromise<T>; |
@@ -0,12 +1,12 @@ | ||
import * as sodium from 'libsodium-wrappers'; | ||
import { MatrixEvent } from './interfaces'; | ||
export declare class WalletCommunicationClient { | ||
private readonly name; | ||
private readonly privateSeed; | ||
private readonly keyPair; | ||
readonly replicationCount: number; | ||
private readonly debug; | ||
private keyPair; | ||
private readonly clients; | ||
private readonly KNOWN_RELAY_SERVERS; | ||
private readonly activeListeners; | ||
constructor(name: string, privateSeed: string, replicationCount: number, debug?: boolean); | ||
constructor(name: string, keyPair: sodium.KeyPair, replicationCount: number, debug?: boolean); | ||
getHandshakeInfo(): { | ||
@@ -13,0 +13,0 @@ name: string; |
@@ -8,5 +8,5 @@ "use strict"; | ||
class WalletCommunicationClient { | ||
constructor(name, privateSeed, replicationCount, debug = false) { | ||
constructor(name, keyPair, replicationCount, debug = false) { | ||
this.name = name; | ||
this.privateSeed = privateSeed; | ||
this.keyPair = keyPair; | ||
this.replicationCount = replicationCount; | ||
@@ -89,4 +89,2 @@ this.debug = debug; | ||
await sodium.ready; | ||
const keyPair = crypto_1.getKeypairFromSeed(this.privateSeed); | ||
this.keyPair = keyPair; | ||
const loginRawDigest = sodium.crypto_generichash(32, sodium.from_string(`login:${Math.floor(Date.now() / 1000 / (5 * 60))}`)); | ||
@@ -93,0 +91,0 @@ const rawSignature = sodium.crypto_sign_detached(loginRawDigest, this.keyPair.privateKey); |
{ | ||
"name": "@airgap/beacon-sdk", | ||
"version": "0.0.3-beta.6", | ||
"version": "0.0.3-beta.7", | ||
"description": "The beacon-sdk is setup in a way to allow for p2p communication between wallets and dapps", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
227798
287
3452