forked from Bitcoindefi/OpenAO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencrypted-payload.ts
More file actions
77 lines (63 loc) · 1.93 KB
/
Copy pathencrypted-payload.ts
File metadata and controls
77 lines (63 loc) · 1.93 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
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
import crypto from "crypto";
type EncryptedAuthPayload = {
v?: unknown;
n?: unknown;
d?: unknown;
};
const AUTH_PAYLOAD_CHANNEL_KEY = "aoweb:auth:v1:credentials-channel";
function fromBase64Url(value: string): Buffer {
const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
const padded = normalized.padEnd(
normalized.length + ((4 - (normalized.length % 4)) % 4),
"=",
);
return Buffer.from(padded, "base64");
}
function getAuthPayloadCryptoKey(): Buffer {
return crypto
.createHash("sha256")
.update(AUTH_PAYLOAD_CHANNEL_KEY)
.digest();
}
function decryptPayloadEnvelope(payload: EncryptedAuthPayload): unknown {
if (
payload.v !== "c1" ||
typeof payload.n !== "string" ||
typeof payload.d !== "string"
) {
return null;
}
try {
const iv = fromBase64Url(payload.n);
const encrypted = fromBase64Url(payload.d);
const tag = encrypted.subarray(encrypted.length - 16);
const ciphertext = encrypted.subarray(0, encrypted.length - 16);
const decipher = crypto.createDecipheriv(
"aes-256-gcm",
getAuthPayloadCryptoKey(),
iv,
);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([
decipher.update(ciphertext),
decipher.final(),
]).toString("utf8");
return JSON.parse(decrypted) as unknown;
} catch {
return null;
}
}
export async function readEncryptedAuthPayload(
request: Request,
): Promise<unknown | null> {
const rawPayload = (await request
.json()
.catch(() => null)) as EncryptedAuthPayload | null;
if (!rawPayload || typeof rawPayload !== "object") {
return null;
}
if (rawPayload.v === "c1") {
return decryptPayloadEnvelope(rawPayload);
}
return process.env.NODE_ENV !== "production" ? rawPayload : null;
}