Improve memory manager UI and auth persistence

This commit is contained in:
wuyang6
2026-05-13 15:13:41 +08:00
parent ea56761a22
commit b5e8b2f218
2 changed files with 115 additions and 30 deletions
+25 -2
View File
@@ -10,6 +10,8 @@ const AUTH_ROOT = path.join(
const USERS_PATH = path.join(AUTH_ROOT, "users.json");
const SESSIONS_PATH = path.join(AUTH_ROOT, "auth_sessions.json");
const COOKIE_NAME = "claw_account_session";
const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
const SESSION_REFRESH_INTERVAL_MS = 60 * 60 * 12 * 1000;
type UserRecord = {
id: string;
@@ -23,7 +25,10 @@ type UsersFile = {
};
type SessionsFile = {
sessions: Record<string, { accountId: string; createdAt: string }>;
sessions: Record<
string,
{ accountId: string; createdAt: string; updatedAt?: string }
>;
};
export type AccountSession = {
@@ -87,6 +92,11 @@ export async function getCurrentAccount(): Promise<AccountSession | null> {
const usersFile = await readUsers();
const account = usersFile.users.find((user) => user.id === session.accountId);
if (!account) return null;
if (shouldRefreshSession(session.updatedAt ?? session.createdAt)) {
session.updatedAt = new Date().toISOString();
await writeSessions(sessionsFile);
await setSessionCookie(token);
}
return { id: account.id, username: account.username };
}
@@ -132,16 +142,22 @@ async function createSession(account: UserRecord) {
sessionsFile.sessions[token] = {
accountId: account.id,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
await writeSessions(sessionsFile);
await setSessionCookie(token);
return { id: account.id, username: account.username };
}
async function setSessionCookie(token: string) {
const cookieStore = await cookies();
cookieStore.set(COOKIE_NAME, token, {
httpOnly: true,
sameSite: "lax",
path: "/",
maxAge: SESSION_MAX_AGE_SECONDS,
});
return { id: account.id, username: account.username };
}
async function createAccountDirectories(accountId: string) {
@@ -207,3 +223,10 @@ function verifyPassword(password: string, passwordHash: string) {
const expected = Buffer.from(expectedHash);
return actual.length === expected.length && timingSafeEqual(actual, expected);
}
function shouldRefreshSession(value?: string) {
if (!value) return true;
const timestamp = Date.parse(value);
if (Number.isNaN(timestamp)) return true;
return Date.now() - timestamp > SESSION_REFRESH_INTERVAL_MS;
}