-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
275 lines (243 loc) · 9.72 KB
/
Copy pathindex.ts
File metadata and controls
275 lines (243 loc) · 9.72 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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import { AdminForthPlugin } from "adminforth";
import type {
AdminForthComponentDeclarationFull,
AdminUser,
AdminUserAuthorizeFunction,
AfterSessionCreatedFunction,
BeforeLogoutFunction,
HttpExtra,
IAdminForth,
IHttpServer,
KeyValueAdapter,
} from "adminforth";
import { z } from "zod";
import type { PluginOptions, UserSessionListItem, UserSessionRecord } from "./types.js";
import { parseUserAgent } from "./userAgent.js";
const DEFAULT_COLLECTION = 'adminforth-user-sessions';
const DEFAULT_COUNTRY_HEADER = 'CF-IPCountry';
const DEFAULT_LAST_USED_THROTTLE_SECONDS = 60;
const ENDPOINTS_PREFIX = '/plugin/user-sessions';
// listing is done for one user only, so the limit is just a sanity cap
const SESSIONS_LIST_LIMIT = 500;
// real user agents are well under this; the header itself is client-controlled and can be ~16KB
const USER_AGENT_MAX_LENGTH = 512;
const COUNTRY_CODE_RE = /^[A-Z]{2}$/;
const listBodySchema = z.object({
userPk: z.string().optional(),
}).strict();
const revokeBodySchema = z.object({
sessionId: z.string(),
userPk: z.string().optional(),
}).strict();
export default class UserSessionsPlugin extends AdminForthPlugin {
options: PluginOptions;
pluginsScope: 'global' = 'global';
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
this.shouldHaveSingleInstancePerWholeApp = () => true;
}
instanceUniqueRepresentation(): string {
return 'single';
}
modifyGlobalConfig(adminforth: IAdminForth) {
super.modifyGlobalConfig(adminforth);
const auth = adminforth.config.auth!;
if (!auth.afterSessionCreated) {
throw new Error(
'User sessions plugin requires AdminForth which supports auth.afterSessionCreated hook, please update adminforth package'
);
}
(auth.afterSessionCreated as AfterSessionCreatedFunction[]).push(
async ({ pk, sessionId, expiresInSeconds, extra }) => {
await this.storeSession(pk, sessionId, expiresInSeconds, extra);
}
);
// unshifted: a revoked session must be rejected before any other hook lets it do work
(auth.adminUserAuthorize as AdminUserAuthorizeFunction[]).unshift(
// params are declared optional by AdminForth type, but are always passed
async (params) => this.authorizeSession(params!.adminUser)
);
(auth.beforeLogout as BeforeLogoutFunction[]).push(
async ({ adminUser }) => {
if (adminUser?.sessionId) {
await this.kv.delete(sessionKey(adminUser.pk, adminUser.sessionId), this.collection);
}
}
);
auth.userMenuSettingsPages ??= [];
auth.userMenuSettingsPages.push({
icon: 'flowbite:desktop-pc-outline',
pageLabel: 'Active sessions',
slug: 'user-sessions',
component: this.componentPath('UserSessions.vue'),
// page is dropped from /get_config when isVisible is not set
isVisible: () => true,
});
if (this.options.canManageOtherUsersSessions) {
this.showSessionsOnUsersResource(adminforth, auth.usersResourceId!);
}
}
/**
* Adds sessions block to the show page of the users resource, so privileged users can see and
* revoke sessions of the user they are looking at.
*/
private showSessionsOnUsersResource(adminforth: IAdminForth, usersResourceId: string) {
const usersResource = adminforth.config.resources.find(
(resource) => resource.resourceId === usersResourceId,
)!;
const pageInjections = (usersResource.options!.pageInjections ??= {});
const showInjections = (pageInjections.show ??= {});
showInjections.bottom ??= [];
(showInjections.bottom as AdminForthComponentDeclarationFull[]).push({
file: this.componentPath('UserSessionsOfUser.vue'),
meta: {
primaryKeyField: usersResource.columns.find((column) => column.primaryKey)!.name,
},
});
}
/**
* Own sessions are always managable, sessions of other users only when the app allows it.
*/
private async canManage(adminUser: AdminUser, userPk: string | null): Promise<boolean> {
if (userPk === adminUser.pk) {
return true;
}
return this.options.canManageOtherUsersSessions
? await this.options.canManageOtherUsersSessions(adminUser)
: false;
}
private get kv(): KeyValueAdapter {
return this.options.keyValueAdapter;
}
private get collection(): string {
return this.options.collection ?? DEFAULT_COLLECTION;
}
private async storeSession(pk: string | null, sessionId: string, expiresInSeconds: number, extra?: HttpExtra) {
const headers = extra?.headers ?? {};
const ip = extra ? this.adminforth.auth.getClientIp(headers) : null;
const now = new Date().toISOString();
const record: UserSessionRecord = {
ip,
country: await this.resolveCountry(ip, headers),
user_agent: headers['user-agent']?.slice(0, USER_AGENT_MAX_LENGTH) ?? null,
created_at: now,
last_used_at: now,
};
await this.kv.set(sessionKey(pk, sessionId), JSON.stringify(record), expiresInSeconds, this.collection);
}
private async resolveCountry(ip: string | null, headers: Record<string, string>): Promise<string | null> {
const headerName = this.options.countryHeader ?? DEFAULT_COUNTRY_HEADER;
if (headerName) {
const fromHeader = String(headers[headerName.toLowerCase()] ?? '').toUpperCase();
// CDNs answer with a placeholder (e.g. Cloudflare sends XX) when they can't tell the country
if (COUNTRY_CODE_RE.test(fromHeader) && fromHeader !== 'XX') {
return fromHeader;
}
}
if (this.options.resolveCountry) {
return await this.options.resolveCountry({ ip, headers });
}
return null;
}
private async authorizeSession(adminUser: AdminUser): Promise<{ allowed: boolean, error?: string }> {
if (!adminUser.sessionId) {
// no session to check: request is done by an api key (e.g. MCP plugin) or by a token
// issued before this plugin was installed
return { allowed: true };
}
const key = sessionKey(adminUser.pk, adminUser.sessionId);
const stored = await this.kv.get(key, this.collection);
if (!stored) {
return { allowed: false, error: 'Session was revoked' };
}
await this.touchSession(key, JSON.parse(stored) as UserSessionRecord, adminUser.exp);
return { allowed: true };
}
/**
* Refreshes `last_used_at`, not more often than once per `lastUsedThrottleSeconds`.
* Record is rewritten, so remaining lifetime of the token is re-applied as expiration.
*/
private async touchSession(key: string, record: UserSessionRecord, tokenExpiresAt?: number) {
const throttleMs = (this.options.lastUsedThrottleSeconds ?? DEFAULT_LAST_USED_THROTTLE_SECONDS) * 1000;
if (Date.now() - new Date(record.last_used_at).getTime() < throttleMs) {
return;
}
const expiresInSeconds = tokenExpiresAt ? tokenExpiresAt - Math.floor(Date.now() / 1000) : undefined;
if (expiresInSeconds !== undefined && expiresInSeconds <= 0) {
return;
}
await this.kv.set(
key,
JSON.stringify({ ...record, last_used_at: new Date().toISOString() }),
expiresInSeconds,
this.collection,
);
}
private async listSessions(userPk: string | null, currentSessionId?: string): Promise<UserSessionListItem[]> {
const rows = await this.kv.listByPrefix(`${userPk}:`, SESSIONS_LIST_LIMIT, this.collection);
return rows
.map((row) => {
const [key] = Object.keys(row);
const sessionId = key.slice(key.lastIndexOf(':') + 1);
const record = JSON.parse(row[key]) as UserSessionRecord;
return {
...record,
sessionId,
isCurrent: sessionId === currentSessionId,
device: parseUserAgent(record.user_agent),
};
})
.sort((a, b) => b.created_at.localeCompare(a.created_at));
}
setupEndpoints(server: IHttpServer) {
server.endpoint({
method: 'POST',
path: `${ENDPOINTS_PREFIX}/list`,
request_schema: listBodySchema,
handler: async ({ adminUser, body }) => {
const userPk = body.userPk ?? adminUser.pk;
if (!await this.canManage(adminUser, userPk)) {
return { allowed: false, sessions: [] };
}
return { allowed: true, sessions: await this.listSessions(userPk, adminUser.sessionId) };
},
});
server.endpoint({
method: 'POST',
path: `${ENDPOINTS_PREFIX}/revoke`,
request_schema: revokeBodySchema,
handler: async ({ adminUser, body, response }) => {
const userPk = body.userPk ?? adminUser.pk;
if (!await this.canManage(adminUser, userPk)) {
response.setStatus(403);
return { error: 'Not allowed to manage sessions of this user' };
}
await this.kv.delete(sessionKey(userPk, body.sessionId), this.collection);
return { ok: true };
},
});
server.endpoint({
method: 'POST',
path: `${ENDPOINTS_PREFIX}/revoke-others`,
request_schema: listBodySchema,
handler: async ({ adminUser, body, response }) => {
const userPk = body.userPk ?? adminUser.pk;
if (!await this.canManage(adminUser, userPk)) {
response.setStatus(403);
return { error: 'Not allowed to manage sessions of this user' };
}
// session the request is made with survives, for another user it means all of their sessions go
const sessions = await this.listSessions(userPk, adminUser.sessionId);
const revoked = sessions.filter((session) => !session.isCurrent);
await Promise.all(
revoked.map((session) => this.kv.delete(sessionKey(userPk, session.sessionId), this.collection))
);
return { ok: true, revoked: revoked.length };
},
});
}
}
function sessionKey(pk: string | null, sessionId: string): string {
return `${pk}:${sessionId}`;
}