Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(auth): accept desktop session for password changes

tianma-ifb5e30dc2a45b
diff --git a/apps/api/src/auth-routes.test.mjs b/apps/api/src/auth-routes.test.mjs
index 124fdba4..ff3f67af 100644
--- a/apps/api/src/auth-routes.test.mjs
+++ b/apps/api/src/auth-routes.test.mjs
@@ -1,6 +1,12 @@
+import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
+import { globSync, readFileSync } from "node:fs";
import { Hono } from "hono";
+import { hashPassword, verifyPassword } from "./auth-crypto.ts";
import { registerAuthRoutes } from "./auth-routes.ts";
+import { authenticateRequest } from "./auth-service.ts";
+import { sha256 } from "./hash-utils.ts";
+import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";
const interactiveAuth = {
kind: "user",
@@ -94,4 +100,101 @@ describe("auth route contracts", () => {
error: { code: "current_session_cannot_be_revoked" },
});
});
+
+ test("accepts a bearer backed interactive session for password changes", async () => {
+ const app = createApp({
+ authenticateRequest: async (context) =>
+ context.req.header("Authorization") === "Bearer desktop-session" ? interactiveAuth : null,
+ isDemoMode: () => true,
+ });
+ const response = await app.request(
+ "/api/v1/auth/change-password",
+ {
+ method: "POST",
+ headers: {
+ Authorization: "Bearer desktop-session",
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ currentPassword: "old-password",
+ newPassword: "new-password",
+ confirmPassword: "new-password",
+ }),
+ },
+ environment,
+ );
+
+ expect(response.status).toBe(403);
+ });
+
+ test("does not allow an API token to change a password", async () => {
+ const app = createApp({
+ authenticateRequest: async () => ({ ...interactiveAuth, kind: "agent" }),
+ });
+ const response = await app.request(
+ "/api/v1/auth/change-password",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ currentPassword: "old-password",
+ newPassword: "new-password",
+ confirmPassword: "new-password",
+ }),
+ },
+ environment,
+ );
+
+ expect(response.status).toBe(401);
+ });
+
+ test("changes a password with an existing desktop bearer session and revokes other sessions", async () => {
+ const sqlite = new Database(":memory:");
+ try {
+ for (const path of globSync("migrations/*.sql").sort()) {
+ sqlite.exec(readFileSync(path, "utf8"));
+ }
+ const oldPasswordHash = await hashPassword("old-password");
+ sqlite.query("INSERT INTO users (id, username, password_hash) VALUES (?, ?, ?)")
+ .run("usr_owner", "owner", oldPasswordHash);
+ sqlite.query("INSERT INTO workspace_members (workspace_id, user_id, role) VALUES (?, ?, ?)")
+ .run("ws_default", "usr_owner", "owner");
+ const expiry = new Date(Date.now() + 86_400_000).toISOString();
+ sqlite.query("INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)")
+ .run("session_current", "usr_owner", await sha256("existing-desktop-token"), expiry);
+ sqlite.query("INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)")
+ .run("session_other", "usr_owner", await sha256("other-device-token"), expiry);
+
+ const app = createApp({ authenticateRequest });
+ const existingSessionEnvironment = {
+ storage: createSelfHostedStorageAdapter(sqlite, "/tmp/edgeever-auth-route-test-resources"),
+ };
+ const response = await app.request(
+ "/api/v1/auth/change-password",
+ {
+ method: "POST",
+ headers: {
+ Authorization: "Bearer existing-desktop-token",
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ currentPassword: "old-password",
+ newPassword: "new-password",
+ confirmPassword: "new-password",
+ }),
+ },
+ existingSessionEnvironment,
+ );
+
+ expect(response.status).toBe(200);
+ const passwordHash = sqlite.query("SELECT password_hash FROM users WHERE id = ?")
+ .get("usr_owner").password_hash;
+ expect(await verifyPassword("new-password", passwordHash)).toBe(true);
+ expect(await verifyPassword("old-password", passwordHash)).toBe(false);
+ expect(sqlite.query("SELECT revoked_at FROM sessions WHERE id = ?").get("session_current").revoked_at).toBeNull();
+ expect(sqlite.query("SELECT revoked_at FROM sessions WHERE id = ?").get("session_other").revoked_at).not.toBeNull();
+ } finally {
+ sqlite.close();
+ }
+ });
});
diff --git a/apps/api/src/auth-routes.ts b/apps/api/src/auth-routes.ts
index 5544cfb2..cbdb9937 100644
--- a/apps/api/src/auth-routes.ts
+++ b/apps/api/src/auth-routes.ts
@@ -311,7 +311,7 @@ export const registerAuthRoutes = (
"/api/v1/auth/change-password",
zValidator("json", ChangePasswordSchema),
async (context) => {
- const auth = await requireInteractiveSession(context, dependencies.authenticateSession);
+ const auth = await requireInteractiveSession(context, dependencies.authenticateRequest);
if (!auth) return unauthorized(context, "An interactive user session is required.");
if (dependencies.isDemoMode(context.env)) {
return forbidden(context, "The demo environment does not allow changing login passwords.");
diff --git a/apps/web/src/lib/api.test.mjs b/apps/web/src/lib/api.test.mjs
index 56747f21..a663e575 100644
--- a/apps/web/src/lib/api.test.mjs
+++ b/apps/web/src/lib/api.test.mjs
@@ -301,7 +301,45 @@ describe("desktop instance setup", () => {
await cacheDesktopSession(await api.login({ username: "admin", password: "secret" }));
});
- test("uses the desktop session token and stops network retries after a 401", async () => {
+ test("keeps the desktop session after a route-specific 401", async () => {
+ events.length = 0;
+ await cacheDesktopSession({
+ authRequired: true,
+ authenticated: true,
+ demoMode: false,
+ sessionToken: "desktop-session-token",
+ user: { id: "user-1", username: "admin", displayName: null, role: "owner" },
+ });
+
+ const requests = [];
+ globalThis.fetch = async (url, init) => {
+ requests.push({ url, authorization: new Headers(init?.headers).get("Authorization") });
+ if (String(url).endsWith("/api/v1/auth/session")) {
+ return Response.json({ authRequired: true, authenticated: true, demoMode: false, user: { id: "user-1" } });
+ }
+ if (String(url).endsWith("/api/v1/auth/sessions")) return Response.json({ sessions: [] });
+ return Response.json({ error: { code: "unauthorized", message: "Authentication required" } }, { status: 401 });
+ };
+
+ await expect(api.changePassword({
+ currentPassword: "old-password",
+ newPassword: "new-password",
+ confirmPassword: "new-password",
+ })).rejects.toMatchObject({ status: 401 });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await expect(api.listLoginDeviceSessions()).resolves.toEqual({ sessions: [] });
+
+ expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
+ "/api/v1/auth/change-password",
+ "/api/v1/auth/session",
+ "/api/v1/auth/sessions",
+ ]);
+ expect(requests.every(({ authorization }) => authorization === "Bearer desktop-session-token")).toBe(true);
+ expect(secureSessionToken).toBe("desktop-session-token");
+ expect(events).toEqual([]);
+ });
+
+ test("uses the desktop session token and stops network retries after a confirmed 401", async () => {
calls.length = 0;
events.length = 0;
storage.set(DESKTOP_API_BASE_URL_STORAGE_KEY, "https://notes.example.com");
@@ -316,6 +354,9 @@ describe("desktop instance setup", () => {
const requests = [];
globalThis.fetch = async (url, init) => {
requests.push({ url, authorization: new Headers(init?.headers).get("Authorization") });
+ if (String(url).endsWith("/api/v1/auth/session")) {
+ return Response.json({ authRequired: true, authenticated: false, demoMode: false, user: null });
+ }
return new Response(JSON.stringify({ error: { code: "unauthorized", message: "Authentication required" } }), {
status: 401,
headers: { "Content-Type": "application/json" },
@@ -323,11 +364,15 @@ describe("desktop instance setup", () => {
};
await expect(api.syncBootstrap({ limit: 200 })).rejects.toMatchObject({ status: 401 });
+ await new Promise((resolve) => setTimeout(resolve, 0));
await expect(api.syncBootstrap({ limit: 200 })).rejects.toMatchObject({ status: 401 });
expect(requests).toEqual([{
url: "https://notes.example.com/api/v1/sync/bootstrap?limit=200",
authorization: "Bearer desktop-session-token",
+ }, {
+ url: "https://notes.example.com/api/v1/auth/session",
+ authorization: "Bearer desktop-session-token",
}]);
expect(events).toEqual(["edgeever:unauthorized"]);
expect(getCachedDesktopSession()).toBeNull();
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 94e77e7f..5f5487be 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -161,11 +161,7 @@ let unauthorizedConfirmPromise: Promise<boolean> | null = null;
const isDesktopPublicRequest = (path: string) =>
path === "/api/release" || path === "/api/v1/auth/login" || path === "/api/v1/auth/session";
-/**
- * Confirm the browser is actually logged out before forcing the login screen.
- * A single flaky 401 (or a mid-session local-dev auth mode flip) should not
- * wipe the whole workspace if the session cookie is still valid.
- */
+/** Confirm the current browser or desktop session is lost before signing out. */
const confirmSessionLost = async (): Promise<boolean> => {
if (typeof window === "undefined") return true;
if (unauthorizedConfirmPromise) return unauthorizedConfirmPromise;
@@ -201,6 +197,8 @@ const notifyUnauthorized = async (isDesktop: boolean, rejectedDesktopSessionToke
if (isDesktop && rejectedDesktopSessionToken) {
if (getDesktopSessionToken() !== rejectedDesktopSessionToken) return;
+ const sessionLost = await confirmSessionLost();
+ if (!sessionLost || getDesktopSessionToken() !== rejectedDesktopSessionToken) return;
clearCachedDesktopSession();
desktopSessionRejected = true;
window.dispatchEvent(new CustomEvent("edgeever:unauthorized"));