@heybejs/core 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/auth/sessions.ts +111 -0
- package/src/auth/tokens.ts +20 -2
- package/src/collections/scaffold.ts +18 -0
- package/src/collections/store.ts +12 -8
- package/src/cron/system.ts +6 -0
- package/src/hooks/system.ts +7 -5
- package/src/http/router.ts +2 -0
- package/src/http/routes/record-auth-flows.ts +1 -1
- package/src/http/routes/record-auth-oauth2.ts +2 -1
- package/src/http/routes/record-auth.ts +37 -3
- package/src/http/routes/sessions.ts +101 -0
- package/src/http/server.ts +2 -0
- package/src/realtime/broadcast.ts +12 -0
- package/ui/dist/assets/{index-DYrAitH0.js → index-B-BaSmc0.js} +3 -3
- package/ui/dist/index.html +1 -1
package/package.json
CHANGED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { App } from "../app";
|
|
2
|
+
import type { Collection } from "../collections/model";
|
|
3
|
+
import { internalRecords } from "../records/internal";
|
|
4
|
+
import { formatDate } from "../util";
|
|
5
|
+
|
|
6
|
+
export type SessionRow = {
|
|
7
|
+
id: string;
|
|
8
|
+
collectionRef: string;
|
|
9
|
+
recordRef: string;
|
|
10
|
+
userAgent: string;
|
|
11
|
+
ip: string;
|
|
12
|
+
created: string;
|
|
13
|
+
lastUsed: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// lastUsed is written at most this often, so a busy client does not cause a write per request
|
|
17
|
+
const TOUCH_INTERVAL_MS = 60_000;
|
|
18
|
+
// a record keeps this many sessions; the least recently used ones go first
|
|
19
|
+
const MAX_PER_RECORD = 50;
|
|
20
|
+
const MAX_USER_AGENT = 200;
|
|
21
|
+
|
|
22
|
+
const touching = new Set<string>();
|
|
23
|
+
|
|
24
|
+
const parseTime = (value: string) => Date.parse(value.replace(" ", "T"));
|
|
25
|
+
|
|
26
|
+
export function findSession(
|
|
27
|
+
app: App,
|
|
28
|
+
id: string,
|
|
29
|
+
): Pick<SessionRow, "collectionRef" | "recordRef" | "lastUsed"> | null {
|
|
30
|
+
return app.db.get(
|
|
31
|
+
"SELECT collectionRef, recordRef, lastUsed FROM _hbSessions WHERE id = ?",
|
|
32
|
+
[id],
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Called on every authenticated request, so it never blocks and a failure only gets logged.
|
|
37
|
+
export function touchSession(app: App, id: string, lastUsed: string): void {
|
|
38
|
+
const now = app.now();
|
|
39
|
+
if (now.getTime() - parseTime(lastUsed) < TOUCH_INTERVAL_MS) return;
|
|
40
|
+
if (touching.has(id)) return;
|
|
41
|
+
touching.add(id);
|
|
42
|
+
app.db
|
|
43
|
+
.write(() =>
|
|
44
|
+
app.db.run("UPDATE _hbSessions SET lastUsed = ? WHERE id = ?", [
|
|
45
|
+
formatDate(now),
|
|
46
|
+
id,
|
|
47
|
+
]),
|
|
48
|
+
)
|
|
49
|
+
.catch((error) =>
|
|
50
|
+
app.logger.warn("Failed to update the session last used time", { error }),
|
|
51
|
+
)
|
|
52
|
+
.finally(() => touching.delete(id));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function createSession(
|
|
56
|
+
app: App,
|
|
57
|
+
c: Collection,
|
|
58
|
+
recordId: string,
|
|
59
|
+
id: string,
|
|
60
|
+
ip: string,
|
|
61
|
+
userAgent: string,
|
|
62
|
+
): Promise<void> {
|
|
63
|
+
await app.db.write(async () => {
|
|
64
|
+
const sessions = internalRecords(app, "_hbSessions");
|
|
65
|
+
await sessions.create({
|
|
66
|
+
id,
|
|
67
|
+
collectionRef: c.id,
|
|
68
|
+
recordRef: recordId,
|
|
69
|
+
userAgent: userAgent.slice(0, MAX_USER_AGENT),
|
|
70
|
+
ip,
|
|
71
|
+
lastUsed: formatDate(app.now()),
|
|
72
|
+
});
|
|
73
|
+
const extra = app.db.query<{ id: string }>(
|
|
74
|
+
"SELECT id FROM _hbSessions WHERE collectionRef = ? AND recordRef = ? ORDER BY lastUsed DESC LIMIT -1 OFFSET ?",
|
|
75
|
+
[c.id, recordId, MAX_PER_RECORD],
|
|
76
|
+
);
|
|
77
|
+
for (const row of extra) await sessions.deleteWhere("id = ?", [row.id]);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// False when the session is gone (logged out meanwhile), so a refresh cannot bring it back.
|
|
82
|
+
export async function renewSession(app: App, id: string): Promise<boolean> {
|
|
83
|
+
const { changes } = await app.db.write(() =>
|
|
84
|
+
app.db.run("UPDATE _hbSessions SET lastUsed = ? WHERE id = ?", [
|
|
85
|
+
formatDate(app.now()),
|
|
86
|
+
id,
|
|
87
|
+
]),
|
|
88
|
+
);
|
|
89
|
+
return changes > 0;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function deleteSessions(
|
|
93
|
+
app: App,
|
|
94
|
+
where: string,
|
|
95
|
+
params: unknown[],
|
|
96
|
+
): Promise<void> {
|
|
97
|
+
return internalRecords(app, "_hbSessions").deleteWhere(where, params);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// A session whose last use is older than the token duration has no valid token left.
|
|
101
|
+
export async function deleteExpiredSessions(app: App): Promise<void> {
|
|
102
|
+
for (const c of app.collections.all()) {
|
|
103
|
+
if (c.type !== "auth") continue;
|
|
104
|
+
const { duration } = c.authToken as { duration: number };
|
|
105
|
+
const oldest = new Date(app.now().getTime() - duration * 1000);
|
|
106
|
+
await deleteSessions(app, "collectionRef = ? AND lastUsed < ?", [
|
|
107
|
+
c.id,
|
|
108
|
+
formatDate(oldest),
|
|
109
|
+
]);
|
|
110
|
+
}
|
|
111
|
+
}
|
package/src/auth/tokens.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { AuthState } from "../http/router";
|
|
|
4
4
|
import { NotFoundError } from "../util";
|
|
5
5
|
import { parseUnverifiedJwt, signJwt, verifyJwt } from "./jwt";
|
|
6
6
|
import { internalRecords } from "../records/internal";
|
|
7
|
+
import { findSession, touchSession } from "./sessions";
|
|
7
8
|
|
|
8
9
|
interface TokenConfig {
|
|
9
10
|
secret: string;
|
|
@@ -14,7 +15,7 @@ export function newAuthToken(
|
|
|
14
15
|
app: App,
|
|
15
16
|
collection: Collection,
|
|
16
17
|
record: Record<string, unknown>,
|
|
17
|
-
opts: { duration?: number; refreshable?: boolean } = {},
|
|
18
|
+
opts: { duration?: number; refreshable?: boolean; sid?: string } = {},
|
|
18
19
|
): string {
|
|
19
20
|
const config = collection.authToken as TokenConfig;
|
|
20
21
|
return signJwt(
|
|
@@ -23,6 +24,8 @@ export function newAuthToken(
|
|
|
23
24
|
id: record.id,
|
|
24
25
|
collectionId: collection.id,
|
|
25
26
|
refreshable: opts.refreshable ?? true,
|
|
27
|
+
// a session id ties the token to a row in _hbSessions, so logout can revoke it
|
|
28
|
+
...(opts.sid === undefined ? {} : { sid: opts.sid }),
|
|
26
29
|
exp:
|
|
27
30
|
Math.floor(app.now().getTime() / 1000) +
|
|
28
31
|
(opts.duration ?? config.duration),
|
|
@@ -75,11 +78,26 @@ export function authFromToken(
|
|
|
75
78
|
}
|
|
76
79
|
const config = collection[TOKEN_CONFIG[type]] as TokenConfig;
|
|
77
80
|
const secret = `${record.tokenKey}${config.secret}`;
|
|
78
|
-
|
|
81
|
+
const verified = verifyJwt(token, secret, app.now);
|
|
82
|
+
if (!verified) return null;
|
|
83
|
+
// tokens without sid (PocketBase's, or issued before sessions) stay valid until they expire
|
|
84
|
+
const sid = type === "auth" ? verified.sid : undefined;
|
|
85
|
+
if (sid !== undefined) {
|
|
86
|
+
if (typeof sid !== "string") return null;
|
|
87
|
+
const session = findSession(app, sid);
|
|
88
|
+
if (
|
|
89
|
+
!session ||
|
|
90
|
+
session.collectionRef !== collection.id ||
|
|
91
|
+
session.recordRef !== record.id
|
|
92
|
+
)
|
|
93
|
+
return null;
|
|
94
|
+
touchSession(app, sid, session.lastUsed);
|
|
95
|
+
}
|
|
79
96
|
return {
|
|
80
97
|
record,
|
|
81
98
|
collection,
|
|
82
99
|
isSuperuser: collection.name === "_superusers",
|
|
100
|
+
...(typeof sid === "string" ? { sessionId: sid } : {}),
|
|
83
101
|
};
|
|
84
102
|
}
|
|
85
103
|
|
|
@@ -251,6 +251,23 @@ export function usersScaffold(): Collection {
|
|
|
251
251
|
return c;
|
|
252
252
|
}
|
|
253
253
|
|
|
254
|
+
// Rows are written by the server only: the owner can read them, the session routes delete them.
|
|
255
|
+
export function sessionsScaffold(): Collection {
|
|
256
|
+
return systemBase(
|
|
257
|
+
"_hbSessions",
|
|
258
|
+
[
|
|
259
|
+
ref("collectionRef"),
|
|
260
|
+
ref("recordRef"),
|
|
261
|
+
field("text", "userAgent", { system: true }),
|
|
262
|
+
field("text", "ip", { system: true }),
|
|
263
|
+
field("date", "lastUsed", { system: true, min: "", max: "" }),
|
|
264
|
+
],
|
|
265
|
+
[
|
|
266
|
+
"CREATE INDEX `idx_hbSessions_collectionRef_recordRef` ON `_hbSessions` (collectionRef, recordRef)",
|
|
267
|
+
],
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
254
271
|
// The system collections of a fresh data directory, in creation order.
|
|
255
272
|
export function bootstrapCollections(): Collection[] {
|
|
256
273
|
return [
|
|
@@ -300,6 +317,7 @@ export function bootstrapCollections(): Collection[] {
|
|
|
300
317
|
],
|
|
301
318
|
{ deleteRule: OWNER_RULE },
|
|
302
319
|
),
|
|
320
|
+
sessionsScaffold(),
|
|
303
321
|
superusersScaffold(),
|
|
304
322
|
usersScaffold(),
|
|
305
323
|
];
|
package/src/collections/store.ts
CHANGED
|
@@ -49,6 +49,7 @@ import {
|
|
|
49
49
|
import {
|
|
50
50
|
authSystemFields,
|
|
51
51
|
bootstrapCollections,
|
|
52
|
+
sessionsScaffold,
|
|
52
53
|
idField,
|
|
53
54
|
scaffold,
|
|
54
55
|
} from "./scaffold";
|
|
@@ -246,14 +247,17 @@ export class CollectionStore {
|
|
|
246
247
|
db.run(
|
|
247
248
|
"CREATE TABLE IF NOT EXISTS _params (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
|
|
248
249
|
);
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
250
|
+
// an older data directory, or one imported from PocketBase, only lacks `_hbSessions`
|
|
251
|
+
const missing = this.find("_superusers")
|
|
252
|
+
? [sessionsScaffold()].filter((c) => !this.find(c.name))
|
|
253
|
+
: bootstrapCollections();
|
|
254
|
+
for (const c of missing) {
|
|
255
|
+
const { old, next } = this.prepare(c);
|
|
256
|
+
this.validate(old, next);
|
|
257
|
+
this.enforceSuperusers(next);
|
|
258
|
+
this.syncTable(old, next);
|
|
259
|
+
db.run(...rowInsert(next));
|
|
260
|
+
}
|
|
257
261
|
});
|
|
258
262
|
}
|
|
259
263
|
|
package/src/cron/system.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { App } from "../app";
|
|
2
2
|
import { mfaDurationMs } from "../auth/mfa";
|
|
3
3
|
import { otpDurationMs } from "../auth/otp";
|
|
4
|
+
import { deleteExpiredSessions } from "../auth/sessions";
|
|
4
5
|
import type { Collection } from "../collections/model";
|
|
5
6
|
import { exclusive } from "../db";
|
|
6
7
|
import { deleteOldLogs } from "../logs/logger";
|
|
@@ -80,6 +81,11 @@ export function registerCronJobs(app: App): void {
|
|
|
80
81
|
}),
|
|
81
82
|
),
|
|
82
83
|
);
|
|
84
|
+
app.scheduler.add("__hbSessionsCleanup__", "0 * * * *", () =>
|
|
85
|
+
deleteExpiredSessions(app).catch((error) =>
|
|
86
|
+
app.logger.warn("Failed to delete expired sessions", { error }),
|
|
87
|
+
),
|
|
88
|
+
);
|
|
83
89
|
app.scheduler.add("__hbLogsCleanup__", "0 */6 * * *", () =>
|
|
84
90
|
deleteOldLogs(app, app.settings.get().logs.maxDays).catch((error) =>
|
|
85
91
|
app.logger.warn("Failed to delete old logs", { error }),
|
package/src/hooks/system.ts
CHANGED
|
@@ -330,9 +330,10 @@ function bindPasswordChangeHook(app: App, name: string, quiet: boolean) {
|
|
|
330
330
|
);
|
|
331
331
|
}
|
|
332
332
|
|
|
333
|
-
// PB registerOTPHooks: a tokenKey change drops the record's OTPs
|
|
334
|
-
|
|
335
|
-
|
|
333
|
+
// PB registerOTPHooks: a tokenKey change drops the record's OTPs. Heybe's sessions follow the same
|
|
334
|
+
// rule, since a new tokenKey (password or email change) already ends every token of the record.
|
|
335
|
+
function bindTokenKeyHooks(app: App, name: string) {
|
|
336
|
+
bindRecordRefHooks(app, name);
|
|
336
337
|
app.hooks.onRecordUpdateExecute.bind(
|
|
337
338
|
async (e) => {
|
|
338
339
|
await e.next();
|
|
@@ -340,7 +341,7 @@ function bindOTPHooks(app: App) {
|
|
|
340
341
|
isAuth(e) &&
|
|
341
342
|
e.record.original().get("tokenKey") !== e.record.get("tokenKey")
|
|
342
343
|
)
|
|
343
|
-
await deleteByRecord(e,
|
|
344
|
+
await deleteByRecord(e, name);
|
|
344
345
|
},
|
|
345
346
|
{ priority: 99 },
|
|
346
347
|
);
|
|
@@ -376,7 +377,8 @@ export function registerSystemHooks(app: App): void {
|
|
|
376
377
|
bindSuperuserHooks(app);
|
|
377
378
|
bindExternalAuthHooks(app);
|
|
378
379
|
bindPasswordChangeHook(app, "_mfas", false);
|
|
379
|
-
|
|
380
|
+
bindTokenKeyHooks(app, "_otps");
|
|
381
|
+
bindTokenKeyHooks(app, "_hbSessions");
|
|
380
382
|
bindPasswordChangeHook(app, "_authOrigins", true);
|
|
381
383
|
bindSettingsHooks(app);
|
|
382
384
|
}
|
package/src/http/router.ts
CHANGED
|
@@ -19,6 +19,8 @@ export interface AuthState {
|
|
|
19
19
|
record: Record<string, unknown>;
|
|
20
20
|
collection: Collection;
|
|
21
21
|
isSuperuser: boolean;
|
|
22
|
+
// the session the token belongs to; absent for tokens issued without one
|
|
23
|
+
sessionId?: string;
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
type Values = Record<string, unknown>;
|
|
@@ -9,6 +9,7 @@ import { runeLength } from "../../fields/shared";
|
|
|
9
9
|
import { IP_KEY } from "../../realtime/broadcast";
|
|
10
10
|
import { buildRequestInfo } from "../../records/rules";
|
|
11
11
|
import { valuesOf } from "../../records/service";
|
|
12
|
+
import { newId } from "../../util";
|
|
12
13
|
import { ApiError } from "../errors";
|
|
13
14
|
import { skipSuccessActivityLog } from "../middlewares";
|
|
14
15
|
import { collectionPathRateLimit } from "../rate-limit";
|
|
@@ -94,7 +95,7 @@ async function authWithOAuth2Route(e: RequestEvent): Promise<void> {
|
|
|
94
95
|
oe,
|
|
95
96
|
c,
|
|
96
97
|
oe.record!,
|
|
97
|
-
newAuthToken(oe.app, c, valuesOf(oe.record!)),
|
|
98
|
+
newAuthToken(oe.app, c, valuesOf(oe.record!), { sid: newId() }),
|
|
98
99
|
body,
|
|
99
100
|
"oauth2",
|
|
100
101
|
"oauth2",
|
|
@@ -19,7 +19,9 @@ import {
|
|
|
19
19
|
RecordAuthRequestEvent,
|
|
20
20
|
RecordAuthWithPasswordRequestEvent,
|
|
21
21
|
} from "../../hooks/events";
|
|
22
|
-
import { ValidationError } from "../../util";
|
|
22
|
+
import { ValidationError, newId } from "../../util";
|
|
23
|
+
import { createSession, renewSession } from "../../auth/sessions";
|
|
24
|
+
import { decodeJwtClaims } from "../../auth/jwt";
|
|
23
25
|
import { ApiError } from "../errors";
|
|
24
26
|
import { collectionPathRateLimit } from "../rate-limit";
|
|
25
27
|
import type { RequestEvent, Router } from "../router";
|
|
@@ -195,6 +197,34 @@ function canAuthenticate(
|
|
|
195
197
|
}
|
|
196
198
|
}
|
|
197
199
|
|
|
200
|
+
// The token's session row is written once the login is complete (after MFA), so an unfinished login
|
|
201
|
+
// leaves none. A refresh keeps its session and fails when it was revoked meanwhile.
|
|
202
|
+
async function saveSession(
|
|
203
|
+
e: RequestEvent,
|
|
204
|
+
c: Collection,
|
|
205
|
+
recordId: string,
|
|
206
|
+
token: string,
|
|
207
|
+
): Promise<void> {
|
|
208
|
+
const sid = decodeJwtClaims(token)?.sid;
|
|
209
|
+
if (typeof sid !== "string") return;
|
|
210
|
+
if (sid === e.auth?.sessionId) {
|
|
211
|
+
if (!(await renewSession(e.app, sid)))
|
|
212
|
+
throw new ApiError(
|
|
213
|
+
401,
|
|
214
|
+
"The request requires valid record authorization token.",
|
|
215
|
+
);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
await createSession(
|
|
219
|
+
e.app,
|
|
220
|
+
c,
|
|
221
|
+
recordId,
|
|
222
|
+
sid,
|
|
223
|
+
realIp(e.app, e.req, e.remoteIp),
|
|
224
|
+
e.req.headers.get("user-agent") ?? "",
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
|
|
198
228
|
// PB ErrMFA: thrown after the 401 mfaId response was written, which the server keeps.
|
|
199
229
|
export const ErrMFA = new ApiError(401, "mfa required");
|
|
200
230
|
|
|
@@ -230,6 +260,7 @@ export async function authResponse(
|
|
|
230
260
|
e.json(401, { mfaId });
|
|
231
261
|
throw ErrMFA;
|
|
232
262
|
}
|
|
263
|
+
await saveSession(e, c, record.id, token);
|
|
233
264
|
// like PB, relations expand as the authenticated record
|
|
234
265
|
const info = {
|
|
235
266
|
...buildRequestInfo(e, body, context),
|
|
@@ -358,7 +389,7 @@ export function registerRecordAuthRoutes(router: Router): void {
|
|
|
358
389
|
e,
|
|
359
390
|
c,
|
|
360
391
|
record,
|
|
361
|
-
newAuthToken(e.app, c, valuesOf(record)),
|
|
392
|
+
newAuthToken(e.app, c, valuesOf(record), { sid: newId() }),
|
|
362
393
|
body,
|
|
363
394
|
"password",
|
|
364
395
|
"password",
|
|
@@ -406,8 +437,11 @@ export function registerRecordAuthRoutes(router: Router): void {
|
|
|
406
437
|
let token = authTokenFromRequest(e.req);
|
|
407
438
|
// impersonate tokens are not refreshable
|
|
408
439
|
const claims = parseUnverifiedJwt(token, e.app.now);
|
|
440
|
+
// a token from before sessions gets its session here
|
|
409
441
|
if (claims?.refreshable === true)
|
|
410
|
-
token = newAuthToken(e.app, c, valuesOf(record)
|
|
442
|
+
token = newAuthToken(e.app, c, valuesOf(record), {
|
|
443
|
+
sid: e.auth?.sessionId ?? newId(),
|
|
444
|
+
});
|
|
411
445
|
return authResponse(e, c, record, token, body, "default", "");
|
|
412
446
|
};
|
|
413
447
|
const record = new RecordModel(c, e.auth.record, false);
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { deleteSessions, type SessionRow } from "../../auth/sessions";
|
|
2
|
+
import type { Collection } from "../../collections/model";
|
|
3
|
+
import { ApiError } from "../errors";
|
|
4
|
+
import { requireAuth } from "../middlewares";
|
|
5
|
+
import type { RequestEvent, Router } from "../router";
|
|
6
|
+
import { findAuthCollection } from "./record-auth";
|
|
7
|
+
|
|
8
|
+
// Heybe only. A logout deletes the session row, which makes every token with that sid fail.
|
|
9
|
+
|
|
10
|
+
const NOT_FOUND = "The requested resource wasn't found.";
|
|
11
|
+
|
|
12
|
+
// Whose sessions the request may see: the caller's own, or any record's for a superuser.
|
|
13
|
+
function targetRecordId(e: RequestEvent, c: Collection): string {
|
|
14
|
+
const auth = e.auth!;
|
|
15
|
+
const requested = e.query.get("recordId") ?? "";
|
|
16
|
+
if (requested !== "" && requested !== auth.record.id) {
|
|
17
|
+
if (!auth.isSuperuser)
|
|
18
|
+
throw new ApiError(403, "You are not allowed to perform this request.");
|
|
19
|
+
return requested;
|
|
20
|
+
}
|
|
21
|
+
if (auth.collection.id !== c.id)
|
|
22
|
+
throw new ApiError(
|
|
23
|
+
403,
|
|
24
|
+
`The request requires auth record from ${c.name} collection.`,
|
|
25
|
+
);
|
|
26
|
+
return auth.record.id as string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function list(e: RequestEvent) {
|
|
30
|
+
const c = findAuthCollection(e);
|
|
31
|
+
const recordId = targetRecordId(e, c);
|
|
32
|
+
const rows = e.app.db.query<SessionRow>(
|
|
33
|
+
"SELECT id, recordRef, userAgent, ip, created, lastUsed FROM _hbSessions WHERE collectionRef = ? AND recordRef = ? ORDER BY lastUsed DESC",
|
|
34
|
+
[c.id, recordId],
|
|
35
|
+
);
|
|
36
|
+
return e.json(
|
|
37
|
+
200,
|
|
38
|
+
rows.map((r) => ({
|
|
39
|
+
id: r.id,
|
|
40
|
+
collectionId: c.id,
|
|
41
|
+
recordId: r.recordRef,
|
|
42
|
+
userAgent: r.userAgent,
|
|
43
|
+
ip: r.ip,
|
|
44
|
+
created: r.created,
|
|
45
|
+
lastUsed: r.lastUsed,
|
|
46
|
+
current: r.id === e.auth!.sessionId,
|
|
47
|
+
})),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function logout(e: RequestEvent) {
|
|
52
|
+
const c = findAuthCollection(e);
|
|
53
|
+
const auth = e.auth!;
|
|
54
|
+
if (auth.collection.id !== c.id)
|
|
55
|
+
throw new ApiError(
|
|
56
|
+
403,
|
|
57
|
+
`The request requires auth record from ${c.name} collection.`,
|
|
58
|
+
);
|
|
59
|
+
// a token without a session cannot be revoked, only the client forgets it
|
|
60
|
+
if (auth.sessionId)
|
|
61
|
+
await deleteSessions(e.app, "id = ? AND collectionRef = ?", [
|
|
62
|
+
auth.sessionId,
|
|
63
|
+
c.id,
|
|
64
|
+
]);
|
|
65
|
+
return e.noContent(204);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function logoutAll(e: RequestEvent) {
|
|
69
|
+
const c = findAuthCollection(e);
|
|
70
|
+
const recordId = targetRecordId(e, c);
|
|
71
|
+
await deleteSessions(e.app, "collectionRef = ? AND recordRef = ?", [
|
|
72
|
+
c.id,
|
|
73
|
+
recordId,
|
|
74
|
+
]);
|
|
75
|
+
return e.noContent(204);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function revoke(e: RequestEvent) {
|
|
79
|
+
const c = findAuthCollection(e);
|
|
80
|
+
const auth = e.auth!;
|
|
81
|
+
const id = e.params.id!;
|
|
82
|
+
const row = e.app.db.get<{ recordRef: string }>(
|
|
83
|
+
"SELECT recordRef FROM _hbSessions WHERE id = ? AND collectionRef = ?",
|
|
84
|
+
[id, c.id],
|
|
85
|
+
);
|
|
86
|
+
// someone else's session looks like a missing one
|
|
87
|
+
const owner =
|
|
88
|
+
auth.collection.id === c.id && row?.recordRef === auth.record.id;
|
|
89
|
+
if (!row || !(auth.isSuperuser || owner)) throw new ApiError(404, NOT_FOUND);
|
|
90
|
+
await deleteSessions(e.app, "id = ?", [id]);
|
|
91
|
+
return e.noContent(204);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function registerSessionRoutes(router: Router): void {
|
|
95
|
+
const base = "/api/collections/{collection}";
|
|
96
|
+
const authed = requireAuth();
|
|
97
|
+
router.route("GET", `${base}/sessions`, list, authed);
|
|
98
|
+
router.route("DELETE", `${base}/sessions/{id}`, revoke, authed);
|
|
99
|
+
router.route("POST", `${base}/logout`, logout, authed);
|
|
100
|
+
router.route("POST", `${base}/logout-all`, logoutAll, authed);
|
|
101
|
+
}
|
package/src/http/server.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { registerRealtimeRoutes } from "./routes/realtime";
|
|
|
26
26
|
import { registerRecordAuthRoutes } from "./routes/record-auth";
|
|
27
27
|
import { registerRecordAuthFlowRoutes } from "./routes/record-auth-flows";
|
|
28
28
|
import { registerRecordAuthOAuth2Routes } from "./routes/record-auth-oauth2";
|
|
29
|
+
import { registerSessionRoutes } from "./routes/sessions";
|
|
29
30
|
import { registerRecordRoutes } from "./routes/records";
|
|
30
31
|
import { registerSettingsRoutes } from "./routes/settings";
|
|
31
32
|
import { registerSqlRoutes } from "./routes/sql";
|
|
@@ -67,6 +68,7 @@ export function createRouter(): Router {
|
|
|
67
68
|
registerRecordAuthRoutes(router);
|
|
68
69
|
registerRecordAuthFlowRoutes(router);
|
|
69
70
|
registerRecordAuthOAuth2Routes(router);
|
|
71
|
+
registerSessionRoutes(router);
|
|
70
72
|
registerCollectionRoutes(router);
|
|
71
73
|
registerRecordRoutes(router);
|
|
72
74
|
registerFileRoutes(router);
|
|
@@ -299,6 +299,18 @@ export function registerRealtimeHooks(app: App): void {
|
|
|
299
299
|
return e.next();
|
|
300
300
|
}, late);
|
|
301
301
|
|
|
302
|
+
// a revoked session ends the realtime auth of the clients that used its token
|
|
303
|
+
h.onModelAfterDeleteSuccess.bind((e) => {
|
|
304
|
+
const r = e.model;
|
|
305
|
+
if (r instanceof RecordModel && r.collection.name === "_hbSessions")
|
|
306
|
+
eachAuthClient(
|
|
307
|
+
e.app,
|
|
308
|
+
(auth) => auth.sessionId === r.id,
|
|
309
|
+
(client) => client.unset(AUTH_KEY),
|
|
310
|
+
);
|
|
311
|
+
return e.next();
|
|
312
|
+
}, late);
|
|
313
|
+
|
|
302
314
|
h.onModelAfterDeleteSuccess.bind((e) => {
|
|
303
315
|
const r = e.model;
|
|
304
316
|
if (r instanceof RecordModel && r.collection.type === "auth")
|