-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
executable file
·145 lines (130 loc) · 3.82 KB
/
index.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
export class SafeToken<
TimeWindow extends Record<string, number> = { access: number }
> {
private timeWindow: TimeWindow;
private secret: string;
constructor(init: { timeWindows?: TimeWindow; secret: string }) {
if (!init.secret) {
throw new Error("Please provide safetoken secret");
}
this.secret = init.secret;
this.timeWindow =
init.timeWindows ||
({ access: 3600000 /* 1 hour */ } as unknown as TimeWindow); // Default time window
}
async create(data: Record<string, string | number | boolean> = {}) {
return await createHmacSha256Signature(data, this.secret, timestamp());
}
async verify(token: string, timeWindowKey: keyof TimeWindow = "access") {
if (typeof token === "string") {
return await verifyToken(
token,
this.secret,
this.timeWindow[timeWindowKey]
);
}
throw new Error("Invalid token");
}
decode(token: string) {
const data = token.split(".")[2];
const decodedData = base64UrlDecode(data);
return JSON.parse(decodedData);
}
}
async function createHmacSha256Signature(
payload: Record<string, string | number | boolean>,
secret: string,
time: string
) {
const enc = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
enc.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const tbuf = base64UrlEncode(time);
const dataToSign = base64UrlEncode(JSON.stringify(payload));
const data = dataToSign;
const signatureBuffer = await crypto.subtle.sign(
"HMAC",
key,
enc.encode(dataToSign + tbuf)
);
const signature = base64UrlEncode(
String.fromCharCode(...new Uint8Array(signatureBuffer))
);
return `${time}.${signature}.${data}`;
}
async function verifyToken(token: string, secret: string, timeWindow: number) {
const [time, signature, data] = token.split(".");
if (!isIntime(timeWindow, time)) {
throw new Error("Token expired");
}
const enc = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
enc.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"]
);
const timeBase64 = base64UrlEncode(time);
const dataToSign = data + timeBase64;
const signatureBuffer = await crypto.subtle.sign(
"HMAC",
key,
enc.encode(dataToSign)
);
const expectedSignature = base64UrlEncode(
String.fromCharCode(...new Uint8Array(signatureBuffer))
);
if (timingSafeEqual(signature, expectedSignature)) {
const decodedData = base64UrlDecode(data);
return JSON.parse(decodedData) as Record<string, string | number | boolean>;
}
throw new Error("Invalid token");
}
const isIntime = (timeWindow: number, lastTime: string): boolean => {
if (!timeWindow) {
throw new Error("Invalid time window");
}
const lastTimeParsed = parseInt(lastTime, 16);
if (isNaN(lastTimeParsed)) {
return false;
}
const ms = Math.abs(Date.now() - lastTimeParsed * 1000);
return timeWindow > ms;
};
const timestamp = (): string => {
const time = Math.floor(Date.now() / 1000);
const buffer = new Uint8Array(4);
buffer[3] = time & 0xff;
buffer[2] = (time >> 8) & 0xff;
buffer[1] = (time >> 16) & 0xff;
buffer[0] = (time >> 24) & 0xff;
return Array.from(buffer)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
};
function timingSafeEqual(a: string, b: string): boolean {
if (a?.length !== b.length) {
return false;
}
let result = 0;
for (let i = 0; i < a.length; i++) {
result |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return result === 0;
}
function base64UrlEncode(str: string) {
return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function base64UrlDecode(str: string) {
str = str.replace(/-/g, "+").replace(/_/g, "/");
while (str.length % 4) {
str += "=";
}
return atob(str);
}