-
Notifications
You must be signed in to change notification settings - Fork 1
/
session.ts
216 lines (184 loc) · 6.11 KB
/
session.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { preprocess, z } from "zod";
import { nanoid } from "nanoid";
import { kv } from "./kv";
import type { ResponseCookie } from "next/dist/compiled/@edge-runtime/cookies";
const sessionSchema = z.object({
id: z.string(),
signature: z.string(),
expiry: preprocess((arg) => new Date(arg as any), z.date()),
isBot: z.boolean().optional().default(false),
user: z
.object({
id: z.string(),
})
.nullish(),
flashMessages: z.record(z.enum(["success", "error"]), z.string()).optional(),
formData: z
.object({
data: z.record(z.string(), z.any()).nullish(),
errors: z.record(z.string(), z.array(z.string())).nullish(),
})
.nullish(),
extras: z.record(z.string(), z.any()).nullish(),
});
export type SerializedSession = z.TypeOf<typeof sessionSchema>;
type RequiredSession = Required<SerializedSession>;
type FlashMessageTypes = keyof RequiredSession["flashMessages"];
export type SessionFlash = {
type: FlashMessageTypes;
message: Required<RequiredSession["flashMessages"]>[FlashMessageTypes];
};
export class Session {
#_session: SerializedSession;
static LOGGED_OUT_SESSION_TTL = 1 * 24 * 60 * 60; // 1 day in seconds
static LOGGED_IN_SESSION_TTL = 2 * 24 * 60 * 60; // 2 days in seconds
static SESSION_COOKIE_KEY = "__session";
private constructor(serializedPayload: SerializedSession) {
this.#_session = serializedPayload;
}
public static async get(sessionCookieID: string) {
try {
const verifiedSessionId = await this.#verifySessionId(sessionCookieID);
const sessionObject = await kv.get(`session:${verifiedSessionId}`);
if (sessionObject) {
return Session.#fromPayload(sessionSchema.parse(sessionObject));
} else {
return null;
}
} catch (error) {
// In case of invalid Session ID, consider as if the session has not been found
return null;
}
}
public static async create(isBot: boolean = false) {
return await Session.#create({
isBot,
});
}
public async extendValidity() {
this.#_session.expiry = new Date(
Date.now() +
(this.#_session.user
? Session.LOGGED_IN_SESSION_TTL
: Session.LOGGED_OUT_SESSION_TTL) *
1000
);
// saving the session in the storage will reset the TTL
await Session.#save(this.#_session);
}
public getCookie(): ResponseCookie {
return {
name: Session.SESSION_COOKIE_KEY,
value: `${this.#_session.id}.${this.#_session.signature}`,
expires: this.#_session.expiry,
httpOnly: true,
sameSite: "lax",
// when testing on local, the cookies should not be set to secure
secure: process.env.NODE_ENV === "development" ? true : undefined,
};
}
public async addFlash(flash: SessionFlash) {
if (this.#_session.flashMessages) {
this.#_session.flashMessages[flash.type] = flash.message;
} else {
this.#_session.flashMessages = { [flash.type]: flash.message };
}
await Session.#save(this.#_session);
}
public async getFlash() {
const flashes = this.#_session.flashMessages;
if (!flashes) {
return [];
}
// delete flashes
this.#_session.flashMessages = {};
await Session.#save(this.#_session);
const flash = Object.entries(flashes).map(
([key, value]) =>
({
type: key,
message: value,
} as SessionFlash)
);
return flash;
}
static #fromPayload(serializedPayload: SerializedSession) {
return new Session(serializedPayload);
}
static async #create(options?: {
init?: Pick<SerializedSession, "flashMessages" | "extras" | "user">;
isBot?: boolean;
}) {
const { sessionId, signature } = await Session.#generateSessionId();
const sessionObject = {
id: sessionId,
expiry: options?.isBot
? new Date(Date.now() + 5 * 1000) // only five seconds for temporary session
: options?.init?.user
? new Date(Date.now() + Session.LOGGED_IN_SESSION_TTL * 1000)
: new Date(Date.now() + Session.LOGGED_OUT_SESSION_TTL * 1000),
signature,
flashMessages: options?.init?.flashMessages,
extras: options?.init?.extras,
isBot: Boolean(options?.isBot),
user: options?.init?.user,
} satisfies SerializedSession;
await Session.#save(sessionObject);
return Session.#fromPayload(sessionObject);
}
static async #generateSessionId() {
const sessionId = nanoid();
const signature = await this.#sign(sessionId, process.env.SESSION_SECRET!);
return {
sessionId,
signature,
};
}
static async #sign(data: string, secret: string) {
const encoder = new TextEncoder();
const keyData = encoder.encode(secret);
const dataToSign = encoder.encode(data);
const importedKey = await crypto.subtle.importKey(
"raw",
keyData,
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const signature = await crypto.subtle.sign("HMAC", importedKey, dataToSign);
return this.#arrayBufferToBase64(signature);
}
static #arrayBufferToBase64(buffer: ArrayBuffer) {
let binary = "";
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
static async #save(session: SerializedSession) {
await Session.#verifySessionId(`${session.id}.${session.signature}`);
// don't store expiry as a date, but a timestamp instead
const expiry = session.expiry.getTime();
let sessionTTL = session.user
? Session.LOGGED_IN_SESSION_TTL
: Session.LOGGED_OUT_SESSION_TTL;
if (session.isBot) {
sessionTTL = 5; // only 5 seconds for bot sessions
}
await kv.set(`session:${session.id}`, { ...session, expiry }, sessionTTL);
}
static async #verifySessionId(signedSessionId: string) {
const [sessionId, signature] = signedSessionId.split(".");
const expectedSignature = await this.#sign(
sessionId,
process.env.SESSION_SECRET!
);
if (signature === expectedSignature) {
return sessionId;
} else {
throw new Error("Invalid session ID");
}
}
}