-
Notifications
You must be signed in to change notification settings - Fork 66
/
identity.service.ts
305 lines (254 loc) · 8.81 KB
/
identity.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import {Injectable} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {v4 as uuid} from 'uuid';
import {AccessLevel, PublicUserInfo} from '../types/identity';
import {CryptoService} from './crypto.service';
import {GlobalVarsService} from './global-vars.service';
import {CookieService} from 'ngx-cookie';
import {SigningService} from './signing.service';
import {
Transaction,
TransactionMetadataBasicTransfer,
TransactionMetadataBitcoinExchange,
TransactionMetadataCreatorCoin, TransactionMetadataCreatorCoinTransfer,
TransactionMetadataFollow,
TransactionMetadataLike,
TransactionMetadataPrivateMessage,
TransactionMetadataSubmitPost,
TransactionMetadataSwapIdentity,
TransactionMetadataUpdateBitcoinUSDExchangeRate,
TransactionMetadataUpdateGlobalParams,
TransactionMetadataUpdateProfile
} from '../lib/bitclout/transaction';
@Injectable({
providedIn: 'root'
})
export class IdentityService {
// All outbound request promises we still need to resolve
private outboundRequests: {[key: string]: any} = {};
// Opener can be null, parent is never null
private currentWindow = opener || parent;
// Embed component checks for browser support
browserSupported = true;
constructor(
private cryptoService: CryptoService,
private globalVars: GlobalVarsService,
private cookieService: CookieService,
private signingService: SigningService,
) {
window.addEventListener('message', (event) => this.handleMessage(event));
}
// Outgoing Messages
initialize(): Observable<any> {
return this.send('initialize', {});
}
storageGranted(): void {
this.cast('storageGranted');
}
login(payload: {
users: {[key: string]: PublicUserInfo},
publicKeyAdded?: string,
signedUp?: boolean
signedTransactionHex?: string,
}): void {
this.cast('login', payload);
}
import(): Observable<any> {
return this.send('import', {});
}
// Incoming Messages
private handleBurn(data: any): void {
if (!this.approve(data, AccessLevel.Full)) {
return;
}
const { id, payload: { encryptedSeedHex, unsignedHashes } } = data;
const seedHex = this.cryptoService.decryptSeedHex(encryptedSeedHex, this.globalVars.hostname);
const signedHashes = this.signingService.signBurn(seedHex, unsignedHashes);
this.respond(id, {
signedHashes,
});
}
private handleSign(data: any): void {
const { id, payload: { encryptedSeedHex, transactionHex } } = data;
const requiredAccessLevel = this.getRequiredAccessLevel(transactionHex);
if (!this.approve(data, requiredAccessLevel)) {
return;
}
const seedHex = this.cryptoService.decryptSeedHex(encryptedSeedHex, this.globalVars.hostname);
const signedTransactionHex = this.signingService.signTransaction(seedHex, transactionHex);
this.respond(id, {
signedTransactionHex,
});
}
private handleDecrypt(data: any): void {
if (!this.approve(data, AccessLevel.ApproveAll)) {
return;
}
const { id, payload: { encryptedSeedHex, encryptedHexes } } = data;
const seedHex = this.cryptoService.decryptSeedHex(encryptedSeedHex, this.globalVars.hostname);
const decryptedHexes = this.signingService.decryptMessages(seedHex, encryptedHexes);
this.respond(id, {
decryptedHexes
});
}
private handleJwt(data: any): void {
if (!this.approve(data, AccessLevel.ApproveAll)) {
return;
}
const { id, payload: { encryptedSeedHex } } = data;
const seedHex = this.cryptoService.decryptSeedHex(encryptedSeedHex, this.globalVars.hostname);
const jwt = this.signingService.signJWT(seedHex);
this.respond(id, {
jwt
});
}
private async handleInfo(event: MessageEvent): Promise<void> {
// check storage access API
let hasStorageAccess = true;
if (this.cryptoService.mustUseStorageAccess()) {
hasStorageAccess = await document.hasStorageAccess();
}
// check for localStorage access
let hasLocalStorageAccess;
try {
hasLocalStorageAccess = !!localStorage;
} catch (e) {
hasLocalStorageAccess = false;
}
// check for cookie access
this.cookieService.put('bitclout-test-access', 'true');
const hasCookieAccess = !!this.cookieService.get('bitclout-test-access');
// store if browser is supported or not
this.browserSupported = hasCookieAccess || hasLocalStorageAccess;
this.respond(event.data.id, {
hasStorageAccess,
browserSupported: this.browserSupported,
});
}
// Access levels
private getRequiredAccessLevel(transactionHex: string): AccessLevel {
const txBytes = new Buffer(transactionHex, 'hex');
const transaction = Transaction.fromBytes(txBytes)[0] as Transaction<any>;
switch (transaction.metadata.constructor) {
case TransactionMetadataBasicTransfer:
case TransactionMetadataBitcoinExchange:
case TransactionMetadataUpdateBitcoinUSDExchangeRate:
case TransactionMetadataCreatorCoin:
case TransactionMetadataCreatorCoinTransfer:
case TransactionMetadataSwapIdentity:
case TransactionMetadataUpdateGlobalParams:
return AccessLevel.Full;
case TransactionMetadataFollow:
case TransactionMetadataPrivateMessage:
case TransactionMetadataSubmitPost:
case TransactionMetadataUpdateProfile:
case TransactionMetadataLike:
return AccessLevel.ApproveLarge;
}
return AccessLevel.Full;
}
private hasAccessLevel(data: any, requiredAccessLevel: AccessLevel): boolean {
const { payload: { encryptedSeedHex, accessLevel, accessLevelHmac }} = data;
if (accessLevel < requiredAccessLevel) {
return false;
}
const seedHex = this.cryptoService.decryptSeedHex(encryptedSeedHex, this.globalVars.hostname);
return this.cryptoService.validAccessLevelHmac(accessLevel, seedHex, accessLevelHmac);
}
private approve(data: any, accessLevel: AccessLevel): boolean {
const hasAccess = this.hasAccessLevel(data, accessLevel);
const hasEncryptionKey = this.cryptoService.hasSeedHexEncryptionKey(this.globalVars.hostname);
if (!hasAccess || !hasEncryptionKey) {
this.respond(data.id, { approvalRequired: true });
return false;
}
return true;
}
// Message handling
private handleMessage(event: MessageEvent): void {
const { data } = event;
const { service, method } = data;
if (service !== 'identity') { return; }
// Methods are present on incoming requests but not responses
if (method) {
this.handleRequest(event);
} else {
this.handleResponse(event);
}
}
private handleRequest(event: MessageEvent): void {
const data = event.data;
const method = data.method;
if (method === 'burn') {
this.handleBurn(data);
} else if (method === 'decrypt') {
this.handleDecrypt(data);
} else if (method === 'sign') {
this.handleSign(data);
} else if (method === 'jwt') {
this.handleJwt(data);
} else if (method === 'info') {
this.handleInfo(event);
} else {
console.error('Unhandled identity request');
console.error(event);
}
}
private handleResponse(event: MessageEvent): void {
const { data: { id, payload }, origin } = event;
const hostname = new URL(origin).hostname;
const result = {
id,
payload,
hostname,
};
const req = this.outboundRequests[id];
req.next(result);
req.complete();
delete this.outboundRequests[id];
}
// Send a new message and expect a response
private send(method: string, payload: any): Subject<any> {
const id = uuid();
const subject = new Subject();
this.outboundRequests[id] = subject;
this.postMessage({
id,
service: 'identity',
method,
payload,
});
return subject;
}
// Respond to a received message
private respond(id: string, payload: any): void {
this.postMessage({
id,
service: 'identity',
payload
});
}
// Transmit a message without expecting a response
private cast(method: string, payload?: any): void {
this.postMessage({
id: null,
service: 'identity',
method,
payload,
});
}
// Post message to correct client
private postMessage(message: any): void {
if (this.globalVars.webview) {
if (this.currentWindow.webkit?.messageHandlers?.bitcloutIdentityAppInterface !== undefined) {
// iOS Webview with registered "bitcloutIdentityAppInterface" handler
this.currentWindow.webkit.messageHandlers.bitcloutIdentityAppInterface.postMessage(message, '*');
} else if (this.currentWindow.bitcloutIdentityAppInterface !== undefined) {
// Android Webview with registered "bitcloutIdentityAppInterface" handler
this.currentWindow.bitcloutIdentityAppInterface.postMessage(JSON.stringify(message), '*');
}
} else {
this.currentWindow.postMessage(message, '*');
}
}
}