diff --git a/backend/src/db/auth-sessions.ts b/backend/src/db/auth-sessions.ts new file mode 100644 index 00000000..2c6f15bf --- /dev/null +++ b/backend/src/db/auth-sessions.ts @@ -0,0 +1,13 @@ +import type { Database } from 'bun:sqlite' + +/** Reports whether a Better Auth session row still exists and has not expired. */ +export function isAuthSessionActive(db: Database, sessionId: string, now: number = Date.now()): boolean { + const row = db + .prepare('SELECT expiresAt FROM "session" WHERE id = ?') + .get(sessionId) as { expiresAt: string | number } | null + + if (!row) return false + + const expiresAt = typeof row.expiresAt === 'number' ? row.expiresAt : Date.parse(row.expiresAt) + return Number.isFinite(expiresAt) && expiresAt > now +} diff --git a/backend/src/routes/notifications.ts b/backend/src/routes/notifications.ts index 08852a95..137241b6 100644 --- a/backend/src/routes/notifications.ts +++ b/backend/src/routes/notifications.ts @@ -45,6 +45,10 @@ export function createNotificationRoutes( sessionId ); + if (!subscription) { + return c.json({ error: "Session is no longer valid" }, 401); + } + return c.json({ subscription }); }); diff --git a/backend/src/services/notification.ts b/backend/src/services/notification.ts index 19c45feb..526942d6 100644 --- a/backend/src/services/notification.ts +++ b/backend/src/services/notification.ts @@ -25,6 +25,7 @@ import { sseAggregator, type SSEEvent } from "./sse-aggregator"; import { getRepoName } from "../db/queries"; import { getScheduleRunBySessionId } from "../db/schedules"; import { ensurePushSubscriptionsTable } from "../db/push-subscriptions"; +import { isAuthSessionActive } from "../db/auth-sessions"; import type { Repo } from "../types/repo"; import { buildServerSessionPath, buildSessionPath } from "@opencode-manager/shared/utils"; import { sessionIDFromEvent } from "@opencode-manager/shared/opencode"; @@ -204,6 +205,11 @@ export class NotificationService { return this.vapidConfig !== null; } + /** + * Stores a device's push subscription, returning null when the session that registered it was + * revoked or expired before the write. The session check and the upsert share one synchronous + * transaction so a concurrent logout cannot land between them. + */ saveSubscription( userId: string, endpoint: string, @@ -211,6 +217,20 @@ export class NotificationService { auth: string, deviceName?: string, sessionId?: string | null + ): PushSubscriptionRecord | null { + return this.db.transaction(() => { + if (sessionId && !isAuthSessionActive(this.db, sessionId)) return null; + return this.writeSubscription(userId, endpoint, p256dh, auth, deviceName, sessionId); + })(); + } + + private writeSubscription( + userId: string, + endpoint: string, + p256dh: string, + auth: string, + deviceName?: string, + sessionId?: string | null ): PushSubscriptionRecord { const now = Date.now(); diff --git a/backend/test/helpers/auth-sessions.ts b/backend/test/helpers/auth-sessions.ts new file mode 100644 index 00000000..a714726a --- /dev/null +++ b/backend/test/helpers/auth-sessions.ts @@ -0,0 +1,36 @@ +import type { Database } from 'bun:sqlite' + +/** Creates the Better Auth session table for test databases that skip the migrations. */ +export function ensureAuthSessionTable(db: Database): void { + db.run(` + CREATE TABLE IF NOT EXISTS "session" ( + id TEXT PRIMARY KEY NOT NULL, + expiresAt INTEGER NOT NULL, + token TEXT NOT NULL UNIQUE, + createdAt INTEGER NOT NULL, + updatedAt INTEGER NOT NULL, + ipAddress TEXT, + userAgent TEXT, + userId TEXT NOT NULL + ) + `) +} + +/** Inserts a Better Auth session row that expires at the given time. */ +export function insertAuthSession( + db: Database, + id: string, + options: { expiresAt?: number; userId?: string } = {}, +): void { + const timestamp = new Date().toISOString() + db.prepare( + 'INSERT INTO "session" (id, expiresAt, token, createdAt, updatedAt, userId) VALUES (?, ?, ?, ?, ?, ?)', + ).run( + id, + new Date(options.expiresAt ?? Date.now() + 60_000).toISOString(), + `token-${id}`, + timestamp, + timestamp, + options.userId ?? 'default', + ) +} diff --git a/backend/test/routes/notifications.test.ts b/backend/test/routes/notifications.test.ts index 4ac87f84..ffdb7d07 100644 --- a/backend/test/routes/notifications.test.ts +++ b/backend/test/routes/notifications.test.ts @@ -4,6 +4,7 @@ import { Database } from 'bun:sqlite' import { createNotificationRoutes } from '../../src/routes/notifications' import { NotificationService } from '../../src/services/notification' import type { Session } from '../../src/auth' +import { ensureAuthSessionTable, insertAuthSession } from '../helpers/auth-sessions' interface NotificationServiceStub { getVapidPublicKey: ReturnType @@ -15,6 +16,24 @@ interface NotificationServiceStub { sendTestNotification: ReturnType } +function sessionScopedApp(service: NotificationService, sessionId: string) { + const sessionApp = new Hono<{ Variables: { session?: Session['session'] } }>() + sessionApp.use('*', async (c, next) => { + c.set('session', { id: sessionId } as Session['session']) + await next() + }) + sessionApp.route('/', createNotificationRoutes(service)) + return sessionApp +} + +function subscriptionBody(endpoint: string, deviceName?: string): string { + return JSON.stringify({ + endpoint, + keys: { p256dh: 'p256dh-key', auth: 'auth-key' }, + ...(deviceName ? { deviceName } : {}), + }) +} + describe('Notification Routes', () => { let service: NotificationServiceStub let app: ReturnType @@ -117,12 +136,7 @@ describe('Notification Routes', () => { it('saves the session of the device that subscribed', async () => { service.saveSubscription.mockReturnValue({ id: 3 }) - const sessionApp = new Hono<{ Variables: { session?: Session['session'] } }>() - sessionApp.use('*', async (c, next) => { - c.set('session', { id: 'ses_phone' } as Session['session']) - await next() - }) - sessionApp.route('/', createNotificationRoutes(service as unknown as NotificationService)) + const sessionApp = sessionScopedApp(service as unknown as NotificationService, 'ses_phone') const res = await sessionApp.fetch(new Request('http://localhost/subscribe', { method: 'POST', @@ -145,15 +159,27 @@ describe('Notification Routes', () => { ) }) + it('returns 401 when the registering session is no longer valid', async () => { + service.saveSubscription.mockReturnValue(null) + + const res = await app.fetch(new Request('http://localhost/subscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + endpoint: 'https://push.example.com/abc', + keys: { p256dh: 'p256dh-key', auth: 'auth-key' }, + }), + })) + + expect(res.status).toBe(401) + await expect(res.json()).resolves.toEqual({ error: 'Session is no longer valid' }) + }) + it('updates the stored session id and keeps the device name when the same endpoint subscribes again without one', async () => { const db = new Database(':memory:') + ensureAuthSessionTable(db) const service = new NotificationService(db) const endpoint = 'https://push.example.com/phone' - const subscriptionBody = (deviceName?: string) => JSON.stringify({ - endpoint, - keys: { p256dh: 'p256dh-key', auth: 'auth-key' }, - ...(deviceName ? { deviceName } : {}), - }) try { const subscribes: Array<[sessionId: string, deviceName: string | undefined]> = [ @@ -162,17 +188,13 @@ describe('Notification Routes', () => { ] for (const [sessionId, deviceName] of subscribes) { - const sessionApp = new Hono<{ Variables: { session?: Session['session'] } }>() - sessionApp.use('*', async (c, next) => { - c.set('session', { id: sessionId } as Session['session']) - await next() - }) - sessionApp.route('/', createNotificationRoutes(service)) + insertAuthSession(db, sessionId) + const sessionApp = sessionScopedApp(service, sessionId) const res = await sessionApp.fetch(new Request('http://localhost/subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: subscriptionBody(deviceName), + body: subscriptionBody(endpoint, deviceName), })) expect(res.status).toBe(200) } @@ -186,6 +208,39 @@ describe('Notification Routes', () => { } }) + it('keeps the newer session registration when a revoked session saves afterwards', async () => { + const db = new Database(':memory:') + ensureAuthSessionTable(db) + const service = new NotificationService(db) + const endpoint = 'https://push.example.com/phone' + + try { + insertAuthSession(db, 'ses_new') + const newSessionApp = sessionScopedApp(service, 'ses_new') + const newSessionRes = await newSessionApp.fetch(new Request('http://localhost/subscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: subscriptionBody(endpoint), + })) + expect(newSessionRes.status).toBe(200) + + const staleSessionApp = sessionScopedApp(service, 'ses_old') + const staleSessionRes = await staleSessionApp.fetch(new Request('http://localhost/subscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: subscriptionBody(endpoint), + })) + + expect(staleSessionRes.status).toBe(401) + const rows = db + .prepare('SELECT session_id FROM push_subscriptions WHERE endpoint = ?') + .all(endpoint) + expect(rows).toEqual([{ session_id: 'ses_new' }]) + } finally { + db.close() + } + }) + it('returns 400 for invalid subscription data', async () => { const res = await app.fetch(new Request('http://localhost/subscribe', { method: 'POST', diff --git a/backend/test/services/notification-subscriptions.test.ts b/backend/test/services/notification-subscriptions.test.ts index 5006968c..e7ccbf4c 100644 --- a/backend/test/services/notification-subscriptions.test.ts +++ b/backend/test/services/notification-subscriptions.test.ts @@ -5,6 +5,7 @@ import { deletePushSubscriptionsForSession, ensurePushSubscriptionsTable, } from '../../src/db/push-subscriptions' +import { ensureAuthSessionTable, insertAuthSession } from '../helpers/auth-sessions' const USER_ID = 'user-1' @@ -50,6 +51,7 @@ describe('push subscription sessions', () => { beforeEach(() => { db = new Database(':memory:') + ensureAuthSessionTable(db) service = new NotificationService(db) }) @@ -58,6 +60,8 @@ describe('push subscription sessions', () => { }) it('stores the session that registered the subscription', () => { + insertAuthSession(db, 'ses_phone') + service.saveSubscription(USER_ID, 'https://push.example.com/phone', 'p256dh-key', 'auth-key', 'Phone', 'ses_phone') expect(sessionIdOf(db, 'https://push.example.com/phone')).toBe('ses_phone') @@ -71,6 +75,8 @@ describe('push subscription sessions', () => { it('replaces the session id when the same endpoint subscribes again', () => { const endpoint = 'https://push.example.com/phone' + insertAuthSession(db, 'ses_old') + insertAuthSession(db, 'ses_new') service.saveSubscription(USER_ID, endpoint, 'p256dh-key', 'auth-key', 'Phone', 'ses_old') service.saveSubscription(USER_ID, endpoint, 'p256dh-key-2', 'auth-key-2', 'Phone', 'ses_new') @@ -80,10 +86,12 @@ describe('push subscription sessions', () => { it('keeps the stored device name when the same endpoint subscribes again without one', () => { const endpoint = 'https://push.example.com/phone' + insertAuthSession(db, 'ses_old') + insertAuthSession(db, 'ses_new') service.saveSubscription(USER_ID, endpoint, 'p256dh-key', 'auth-key', 'Phone', 'ses_old') const resubscribed = service.saveSubscription(USER_ID, endpoint, 'p256dh-key', 'auth-key', undefined, 'ses_new') - expect(resubscribed.deviceName).toBe('Phone') + expect(resubscribed?.deviceName).toBe('Phone') expect(sessionIdOf(db, endpoint)).toBe('ses_new') expect(service.getSubscriptions(USER_ID)).toHaveLength(1) }) @@ -120,6 +128,8 @@ describe('push subscription sessions', () => { }) it('deletes only the subscriptions of the revoked session', () => { + insertAuthSession(db, 'ses_phone') + insertAuthSession(db, 'ses_desktop') service.saveSubscription(USER_ID, 'https://push.example.com/phone', 'p256dh-key', 'auth-key', 'Phone', 'ses_phone') service.saveSubscription(USER_ID, 'https://push.example.com/desktop', 'p256dh-key', 'auth-key', 'Desktop', 'ses_desktop') service.saveSubscription(USER_ID, 'https://push.example.com/legacy', 'p256dh-key', 'auth-key', 'Legacy') @@ -130,4 +140,25 @@ describe('push subscription sessions', () => { 'https://push.example.com/legacy', ]) }) + + it('keeps the newer session registration when a revoked session saves afterwards', () => { + const endpoint = 'https://push.example.com/phone' + insertAuthSession(db, 'ses_new') + service.saveSubscription(USER_ID, endpoint, 'p256dh-key', 'auth-key', 'Phone', 'ses_new') + + const staleSave = service.saveSubscription(USER_ID, endpoint, 'p256dh-key', 'auth-key', 'Phone', 'ses_old') + + expect(staleSave).toBeNull() + expect(sessionIdOf(db, endpoint)).toBe('ses_new') + expect(service.getSubscriptions(USER_ID)).toHaveLength(1) + }) + + it('does not store a subscription whose auth session has expired', () => { + insertAuthSession(db, 'ses_expired', { expiresAt: Date.now() - 1_000 }) + + const saved = service.saveSubscription(USER_ID, 'https://push.example.com/phone', 'p256dh-key', 'auth-key', 'Phone', 'ses_expired') + + expect(saved).toBeNull() + expect(endpointsOf(db)).toEqual([]) + }) })