forked from m-keller/private-access-tokens-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (71 loc) · 2.28 KB
/
index.js
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
import http from "http";
import fs from "fs";
import * as dotenv from "dotenv";
dotenv.config();
import IssuerDataFetcher from "./lib/IssuerDataFetcher.js";
import TokenRequestCreator from "./lib/TokenRequestCreator.js";
import TokenRedemption from "./lib/TokenRedemption.js";
const issuerDataFetcher = new IssuerDataFetcher();
const tokenRequestCreator = new TokenRequestCreator();
const tokenRedemption = new TokenRedemption();
if (!process.env.TOKEN_DICT_URL) {
console.error("Please create a .env file from .env.sample.");
process.exit(1);
}
issuerDataFetcher.fetchFastlyIssuerData().then((issuerInfo) => {
http
.createServer(function (req, res) {
if (
"authorization" in req.headers &&
tokenRedemption.validateAuthToken(
issuerInfo,
req.headers["authorization"]
)
) {
console.log(
"200 - Authenticated request, path=" +
req.url +
", headers=" +
JSON.stringify(req.headers)
);
res.writeHead(200, { "Content-Type": "text/html" });
res.write(
fs
.readFileSync("html/success200.html", "utf8")
.replace("AUTH_HEADER", req.headers["authorization"])
);
res.end();
} else {
console.log(
"401 - Unauthenticated request, path=" +
req.url +
", headers=" +
JSON.stringify(req.headers)
);
var tokenRequests = [];
for (var i = 0; i < 1; i++) {
var tokenRequest = tokenRequestCreator.createTokenRequest(
issuerInfo.issuer_name,
process.env.INCLUDE_RANDOM_NONCE || true,
process.env.ORIGIN_SCOPE
);
tokenRedemption.registerTokenRequestForRedemption(
Buffer.from(tokenRequest, "base64")
);
tokenRequests.push(
"PrivateToken challenge=" +
tokenRequest +
", token-key=" +
issuerInfo.issuer_public_key_base64
);
}
res.writeHead(401, {
"Content-Type": "text/html",
"WWW-Authenticate": tokenRequests.join(", "),
});
res.write(fs.readFileSync("html/challenge401.html", "utf8"));
res.end();
}
})
.listen(process.env.NODE_PORT);
});