-
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathauthMetadata.ts
More file actions
48 lines (37 loc) · 1.47 KB
/
authMetadata.ts
File metadata and controls
48 lines (37 loc) · 1.47 KB
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
import { IAuthMetadata, secp256k1, StringifiedType, stripHexPrefix, toPrivKeyEC } from "@tkey/common-types";
import { keccak256 } from "@toruslabs/torus.js";
import BN from "bn.js";
import stringify from "json-stable-stringify";
import CoreError from "./errors";
import Metadata, { createMetadataFromJson } from "./metadata";
class AuthMetadata implements IAuthMetadata {
metadata: Metadata;
privKey: BN;
constructor(metadata: Metadata, privKey?: BN) {
this.metadata = metadata;
this.privKey = privKey;
}
static fromJSON(value: StringifiedType): AuthMetadata {
// need to inject legacyMetadata flag
const { data, sig, legacyMetadataFlag } = value;
if (!data) throw CoreError.metadataUndefined();
const m = createMetadataFromJson(legacyMetadataFlag, data);
if (!m.pubKey) throw CoreError.metadataPubKeyUnavailable();
const keyPair = secp256k1.keyFromPublic(m.pubKey.toSEC1(secp256k1));
if (!keyPair.verify(stripHexPrefix(keccak256(Buffer.from(stringify(data), "utf8"))), sig)) {
throw CoreError.default("Signature not valid for returning metadata");
}
return new AuthMetadata(m);
}
toJSON(): StringifiedType {
const data = this.metadata;
if (!this.privKey) throw CoreError.privKeyUnavailable();
const k = toPrivKeyEC(this.privKey);
const sig = k.sign(stripHexPrefix(keccak256(Buffer.from(stringify(data), "utf8"))));
return {
data,
sig: sig.toDER("hex"),
};
}
}
export default AuthMetadata;