-
Notifications
You must be signed in to change notification settings - Fork 620
/
crypto.ts
188 lines (164 loc) · 5.75 KB
/
crypto.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
import { generateChildLogger, getLoggerContext, Logger } from "@walletconnect/logger";
import { safeJsonParse, safeJsonStringify } from "@walletconnect/safe-json";
import { ICore, ICrypto, IKeyChain } from "@walletconnect/types";
import * as relayAuth from "@walletconnect/relay-auth";
import { fromString } from "uint8arrays/from-string";
import {
decrypt,
deriveSymKey,
encrypt,
generateKeyPair as generateKeyPairUtil,
hashKey,
getInternalError,
generateRandomBytes32,
validateEncoding,
validateDecoding,
isTypeOneEnvelope,
deserialize,
decodeTypeByte,
BASE16,
} from "@walletconnect/utils";
import { toString } from "uint8arrays";
import { CRYPTO_CONTEXT, CRYPTO_CLIENT_SEED, CRYPTO_JWT_TTL } from "../constants";
import { KeyChain } from "./keychain";
export class Crypto implements ICrypto {
public name = CRYPTO_CONTEXT;
public keychain: ICrypto["keychain"];
private initialized = false;
constructor(public core: ICore, public logger: Logger, keychain?: IKeyChain) {
this.core = core;
this.logger = generateChildLogger(logger, this.name);
this.keychain = keychain || new KeyChain(this.core, this.logger);
}
public init: ICrypto["init"] = async () => {
if (!this.initialized) {
await this.keychain.init();
this.initialized = true;
}
};
get context() {
return getLoggerContext(this.logger);
}
public hasKeys: ICrypto["hasKeys"] = (tag) => {
this.isInitialized();
return this.keychain.has(tag);
};
public getClientId: ICrypto["getClientId"] = async () => {
this.isInitialized();
const seed = await this.getClientSeed();
const keyPair = relayAuth.generateKeyPair(seed);
const clientId = relayAuth.encodeIss(keyPair.publicKey);
return clientId;
};
public generateKeyPair: ICrypto["generateKeyPair"] = () => {
this.isInitialized();
const keyPair = generateKeyPairUtil();
return this.setPrivateKey(keyPair.publicKey, keyPair.privateKey);
};
public signJWT: ICrypto["signJWT"] = async (aud) => {
this.isInitialized();
const seed = await this.getClientSeed();
const keyPair = relayAuth.generateKeyPair(seed);
const sub = generateRandomBytes32();
const ttl = CRYPTO_JWT_TTL;
const jwt = await relayAuth.signJWT(sub, aud, ttl, keyPair);
return jwt;
};
public generateSharedKey: ICrypto["generateSharedKey"] = (
selfPublicKey,
peerPublicKey,
overrideTopic,
) => {
this.isInitialized();
const selfPrivateKey = this.getPrivateKey(selfPublicKey);
const symKey = deriveSymKey(selfPrivateKey, peerPublicKey);
return this.setSymKey(symKey, overrideTopic);
};
public setSymKey: ICrypto["setSymKey"] = async (symKey, overrideTopic) => {
this.isInitialized();
const topic = overrideTopic || hashKey(symKey);
await this.keychain.set(topic, symKey);
return topic;
};
public deleteKeyPair: ICrypto["deleteKeyPair"] = async (publicKey: string) => {
this.isInitialized();
await this.keychain.del(publicKey);
};
public deleteSymKey: ICrypto["deleteSymKey"] = async (topic: string) => {
this.isInitialized();
await this.keychain.del(topic);
};
public encode: ICrypto["encode"] = async (topic, payload, opts) => {
this.isInitialized();
const params = validateEncoding(opts);
const message = safeJsonStringify(payload);
if (isTypeOneEnvelope(params)) {
const selfPublicKey = params.senderPublicKey;
const peerPublicKey = params.receiverPublicKey;
topic = await this.generateSharedKey(selfPublicKey, peerPublicKey);
}
const symKey = this.getSymKey(topic);
const { type, senderPublicKey } = params;
const result = encrypt({ type, symKey, message, senderPublicKey });
return result;
};
public decode: ICrypto["decode"] = async (topic, encoded, opts) => {
this.isInitialized();
const params = validateDecoding(encoded, opts);
if (isTypeOneEnvelope(params)) {
const selfPublicKey = params.receiverPublicKey;
const peerPublicKey = params.senderPublicKey;
topic = await this.generateSharedKey(selfPublicKey, peerPublicKey);
}
try {
const symKey = this.getSymKey(topic);
const message = decrypt({ symKey, encoded });
const payload = safeJsonParse(message);
return payload;
} catch (error) {
this.logger.error(
`Failed to decode message from topic: '${topic}', clientId: '${await this.getClientId()}'`,
);
this.logger.error(error);
}
};
public getPayloadType: ICrypto["getPayloadType"] = (encoded) => {
const deserialized = deserialize(encoded);
return decodeTypeByte(deserialized.type);
};
public getPayloadSenderPublicKey: ICrypto["getPayloadSenderPublicKey"] = (encoded) => {
const deserialized = deserialize(encoded);
return deserialized.senderPublicKey
? toString(deserialized.senderPublicKey, BASE16)
: undefined;
};
// ---------- Private ----------------------------------------------- //
private async setPrivateKey(publicKey: string, privateKey: string): Promise<string> {
await this.keychain.set(publicKey, privateKey);
return publicKey;
}
private getPrivateKey(publicKey: string) {
const privateKey = this.keychain.get(publicKey);
return privateKey;
}
private async getClientSeed(): Promise<Uint8Array> {
let seed = "";
try {
seed = this.keychain.get(CRYPTO_CLIENT_SEED);
} catch {
seed = generateRandomBytes32();
await this.keychain.set(CRYPTO_CLIENT_SEED, seed);
}
return fromString(seed, "base16");
}
private getSymKey(topic: string) {
const symKey = this.keychain.get(topic);
return symKey;
}
private isInitialized() {
if (!this.initialized) {
const { message } = getInternalError("NOT_INITIALIZED", this.name);
throw new Error(message);
}
}
}