-
Notifications
You must be signed in to change notification settings - Fork 66
/
httpScram.ts
139 lines (126 loc) · 3.56 KB
/
httpScram.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
import {ProtocolError} from "./errors";
import {
decodeB64,
encodeB64,
utf8Decoder,
utf8Encoder
} from "./primitives/buffer";
import {
bufferEquals,
buildClientFinalMessage,
buildClientFirstMessage,
generateNonce,
parseServerFinalMessage,
parseServerFirstMessage
} from "./scram";
const AUTH_ENDPOINT = "/auth/token";
function utf8ToB64(str: string): string {
return encodeB64(utf8Encoder.encode(str));
}
function b64ToUtf8(str: string): string {
return utf8Decoder.decode(decodeB64(str));
}
export async function HTTPSCRAMAuth(
baseUrl: string,
username: string,
password: string
): Promise<string> {
const authUrl = baseUrl + AUTH_ENDPOINT;
const clientNonce = await generateNonce();
const [clientFirst, clientFirstBare] = buildClientFirstMessage(
clientNonce,
username
);
// @ts-ignore
const FETCH = typeof fetch === "undefined" ? require("node-fetch") : fetch;
const serverFirstRes = await FETCH(authUrl, {
headers: {
Authorization: `SCRAM-SHA-256 data=${utf8ToB64(clientFirst)}`
}
});
if (serverFirstRes.status === 403) {
// tslint:disable-next-line:no-console
console.log(serverFirstRes);
throw new Error(`Server doesn't support HTTP SCRAM authentication`);
}
const firstAttrs = parseHeaders(serverFirstRes.headers, "WWW-Authenticate");
if (firstAttrs.size === 0) {
throw new Error("Invalid credentials");
}
if (!firstAttrs.has("sid") || !firstAttrs.has("data")) {
throw new ProtocolError(
`server response doesn't contain '${
!firstAttrs.has("sid") ? "sid" : "data"
}' attribute`
);
}
const sid = firstAttrs.get("sid")!;
const serverFirst = b64ToUtf8(firstAttrs.get("data")!);
const [serverNonce, salt, iterCount] = parseServerFirstMessage(serverFirst);
const [clientFinal, expectedServerSig] = await buildClientFinalMessage(
password,
salt,
iterCount,
clientFirstBare,
serverFirst,
serverNonce
);
const serverFinalRes = await FETCH(authUrl, {
headers: {
Authorization: `SCRAM-SHA-256 sid=${sid}, data=${utf8ToB64(clientFinal)}`
}
});
if (!serverFinalRes.ok) {
throw new Error("Invalid credentials");
}
const finalAttrs = parseHeaders(
serverFinalRes.headers,
"Authentication-Info",
false
);
if (!firstAttrs.has("sid") || !firstAttrs.has("data")) {
throw new ProtocolError(
`server response doesn't contain '${
!firstAttrs.has("sid") ? "sid" : "data"
}' attribute`
);
}
if (finalAttrs.get("sid") !== sid) {
throw new ProtocolError("SCRAM session id does not match");
}
const serverFinal = b64ToUtf8(finalAttrs.get("data")!);
const serverSig = parseServerFinalMessage(serverFinal);
if (!bufferEquals(serverSig, expectedServerSig)) {
throw new ProtocolError("server SCRAM proof does not match");
}
const authToken = await serverFinalRes.text();
return authToken;
}
function parseHeaders(
headers: Headers,
headerName: string,
checkAlgo: boolean = true
) {
const header = headers.get(headerName);
if (!header) {
throw new ProtocolError(`response doesn't contain '${headerName}' header`);
}
let rawAttrs: string;
if (checkAlgo) {
const [algo, ..._rawAttrs] = header.split(" ");
if (algo !== "SCRAM-SHA-256") {
throw new ProtocolError(`invalid scram algo '${algo}'`);
}
rawAttrs = _rawAttrs.join(" ");
} else {
rawAttrs = header;
}
return new Map(
rawAttrs
? rawAttrs.split(",").map(attr => {
const [key, val] = attr.split("=", 2);
return [key.trim(), val.trim()];
})
: []
);
}