mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
fix(device-pairing): clean up push subscriptions on admin reset and share URL helpers
The admin password reset finds the admin case-insensitively and deletes the push subscriptions of the sessions it ends. The app re-sends its push subscription once per signed-in session so revoke reaches re-signed-in devices, and the upsert keeps the stored device name. Plain-HTTP and URL parsing checks are shared helpers.
This commit is contained in:
1 parent
cbe4f7ed9e
commit
6e398c4d40
21 files changed
+540
-85
No files matched your search
@@ -26,7 +26,16 @@ export function ensurePushSubscriptionsTable(db: Database): void {
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_push_sub_session ON push_subscriptions(session_id)')
|
||||
}
|
||||
|
||||
/** Deletes the push subscriptions registered by any of the given Better Auth sessions. */
|
||||
export function deletePushSubscriptionsForSessions(db: Database, sessionIds: string[]): number {
|
||||
if (sessionIds.length === 0) return 0
|
||||
const placeholders = sessionIds.map(() => '?').join(', ')
|
||||
return db
|
||||
.prepare(`DELETE FROM push_subscriptions WHERE session_id IN (${placeholders})`)
|
||||
.run(...sessionIds).changes
|
||||
}
|
||||
|
||||
/** Deletes the push subscriptions a revoked Better Auth session registered. */
|
||||
export function deletePushSubscriptionsForSession(db: Database, sessionId: string): number {
|
||||
return db.prepare('DELETE FROM push_subscriptions WHERE session_id = ?').run(sessionId).changes
|
||||
return deletePushSubscriptionsForSessions(db, [sessionId])
|
||||
}
|
||||
@@ -244,7 +244,7 @@ try {
|
||||
await gitAuthService.initialize(ipcServer, db)
|
||||
logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`)
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
detectSandboxCapability()
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { isAdminConfigured, type AuthInstance } from '../auth'
|
||||
import { applyClientIpHeaders, resolveSocketIp } from '../auth/client-ip'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { logger } from '../utils/logger'
|
||||
import { deletePushSubscriptionsForSessions } from '../db/push-subscriptions'
|
||||
|
||||
export function createAuthRoutes(auth: AuthInstance): Hono {
|
||||
const app = new Hono()
|
||||
@@ -15,18 +17,21 @@ export function createAuthRoutes(auth: AuthInstance): Hono {
|
||||
return app
|
||||
}
|
||||
|
||||
export async function syncAdminFromEnv(auth: AuthInstance): Promise<void> {
|
||||
export async function syncAdminFromEnv(auth: AuthInstance, db: Database): Promise<void> {
|
||||
if (!isAdminConfigured()) return
|
||||
|
||||
const adminEmail = ENV.AUTH.ADMIN_EMAIL!
|
||||
const adminPassword = ENV.AUTH.ADMIN_PASSWORD!
|
||||
|
||||
const ctx = await auth.$context
|
||||
const existingAdmin = await ctx.internalAdapter.findUserByEmail(adminEmail)
|
||||
const existingAdmin = await ctx.adapter.findOne<{ id: string }>({
|
||||
model: 'user',
|
||||
where: [{ field: 'email', value: adminEmail, mode: 'insensitive' }],
|
||||
})
|
||||
|
||||
if (existingAdmin) {
|
||||
if (ENV.AUTH.ADMIN_PASSWORD_RESET) {
|
||||
const credentialAccount = (await ctx.internalAdapter.findAccounts(existingAdmin.user.id))
|
||||
const credentialAccount = (await ctx.internalAdapter.findAccounts(existingAdmin.id))
|
||||
.find((account) => account.providerId === 'credential')
|
||||
|
||||
if (credentialAccount) {
|
||||
@@ -37,7 +42,9 @@ export async function syncAdminFromEnv(auth: AuthInstance): Promise<void> {
|
||||
logger.warn(`No credential account found for ${adminEmail}; skipped the password reset`)
|
||||
}
|
||||
|
||||
await ctx.internalAdapter.deleteUserSessions(existingAdmin.user.id)
|
||||
const sessions = await ctx.internalAdapter.listSessions(existingAdmin.id)
|
||||
await ctx.internalAdapter.deleteUserSessions(existingAdmin.id)
|
||||
deletePushSubscriptionsForSessions(db, sessions.map((session) => session.id))
|
||||
logger.info(`Admin password reset from environment for ${adminEmail}`)
|
||||
logger.warn('Remove ADMIN_PASSWORD_RESET=true from environment after password reset')
|
||||
}
|
||||
|
||||
@@ -47,29 +47,28 @@ export function createDevicePairingRoutes(deps: DevicePairingRouteDeps) {
|
||||
const origin = normalizeDevicePairingOrigin(requestedOrigin)
|
||||
if (!origin) return c.json({ error: INVALID_ORIGIN_QUERY_MESSAGE }, 400)
|
||||
|
||||
return c.json(
|
||||
resolveDevicePairingAvailability(origin, {
|
||||
trustedOrigins: resolveTrustedOrigins(),
|
||||
isDevelopment: isDevelopment(),
|
||||
}),
|
||||
)
|
||||
const { available, reason, message } = resolveDevicePairingAvailability(origin, {
|
||||
trustedOrigins: resolveTrustedOrigins(),
|
||||
isDevelopment: isDevelopment(),
|
||||
})
|
||||
|
||||
return c.json({ available, reason, message })
|
||||
})
|
||||
|
||||
app.post('/links', async (c) => {
|
||||
const body = await parseJsonBody(c, CreateDevicePairingLinksRequestSchema, { allowEmpty: true })
|
||||
if (!body.ok) return body.response
|
||||
|
||||
const origin = c.req.header('origin')
|
||||
const availability = resolveDevicePairingAvailability(origin, {
|
||||
const availability = resolveDevicePairingAvailability(c.req.header('origin'), {
|
||||
trustedOrigins: resolveTrustedOrigins(),
|
||||
isDevelopment: isDevelopment(),
|
||||
})
|
||||
if (!origin || !availability.available) {
|
||||
if (!availability.available) {
|
||||
return c.json({ error: availability.message, code: availability.reason }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const originUrl = new URL(origin)
|
||||
const originUrl = availability.originUrl
|
||||
const policy = resolveAppLinkPolicy(originUrl, {
|
||||
allowPrivateNetworkHttp: deps.readAllowPrivateNetworkHttp(),
|
||||
})
|
||||
|
||||
@@ -3,19 +3,23 @@ import {
|
||||
buildManagerAppLink,
|
||||
buildManagerBrowserPairingLink,
|
||||
type AppLinkBlockedReason,
|
||||
type DevicePairingAvailability,
|
||||
type DevicePairingLinkWarning,
|
||||
type DevicePairingLinksResponse,
|
||||
type DevicePairingUnavailableReason,
|
||||
type RemoteAccessHeader,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { isLoopbackHost, isPrivateNetworkHost } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
isLoopbackHost,
|
||||
isPrivateNetworkHost,
|
||||
isPublicPlainHttpUrl,
|
||||
parseHttpUrl,
|
||||
} from '@opencode-manager/shared/utils'
|
||||
|
||||
export const MISSING_ORIGIN_MESSAGE =
|
||||
const MISSING_ORIGIN_MESSAGE =
|
||||
'The request had no Origin header. Open the Manager at an address listed in AUTH_TRUSTED_ORIGINS to pair a device.'
|
||||
export const LOOPBACK_ORIGIN_MESSAGE =
|
||||
const LOOPBACK_ORIGIN_MESSAGE =
|
||||
'This page is open on localhost, which other devices cannot reach. Open the Manager at its public or LAN address to pair a device.'
|
||||
export const INSECURE_ORIGIN_MESSAGE =
|
||||
const INSECURE_ORIGIN_MESSAGE =
|
||||
'Pairing needs HTTPS on a public address. Serve the Manager over HTTPS, or open it at a private network address.'
|
||||
|
||||
type AppLinkPolicy = {
|
||||
@@ -23,6 +27,10 @@ type AppLinkPolicy = {
|
||||
warnings: DevicePairingLinkWarning[]
|
||||
}
|
||||
|
||||
type DevicePairingAvailabilityResult =
|
||||
| { available: true; reason: null; message: null; originUrl: URL }
|
||||
| { available: false; reason: DevicePairingUnavailableReason; message: string }
|
||||
|
||||
type DevicePairingAvailabilityOptions = {
|
||||
trustedOrigins: string[]
|
||||
isDevelopment: boolean
|
||||
@@ -35,37 +43,26 @@ function untrustedOriginMessage(origin: string): string {
|
||||
function unavailable(
|
||||
reason: DevicePairingUnavailableReason,
|
||||
message: string,
|
||||
): DevicePairingAvailability {
|
||||
): DevicePairingAvailabilityResult {
|
||||
return { available: false, reason, message }
|
||||
}
|
||||
|
||||
function parseHttpOrigin(value: string): URL | null {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(value)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
|
||||
return url
|
||||
}
|
||||
|
||||
/** Normalises an address to its origin, or null when it is not an absolute http(s) URL. */
|
||||
export function normalizeDevicePairingOrigin(value: string): string | null {
|
||||
return parseHttpOrigin(value)?.origin ?? null
|
||||
return parseHttpUrl(value)?.origin ?? null
|
||||
}
|
||||
|
||||
/** Reports whether an origin can mint a pairing code, and why it cannot when blocked. */
|
||||
export function resolveDevicePairingAvailability(
|
||||
origin: string | undefined,
|
||||
options: DevicePairingAvailabilityOptions,
|
||||
): DevicePairingAvailability {
|
||||
): DevicePairingAvailabilityResult {
|
||||
if (!origin) return unavailable('untrusted-origin', MISSING_ORIGIN_MESSAGE)
|
||||
if (!isTrustedOrigin(origin, { requireOrigin: true }, options.trustedOrigins)) {
|
||||
return unavailable('untrusted-origin', untrustedOriginMessage(origin))
|
||||
}
|
||||
|
||||
const originUrl = parseHttpOrigin(origin)
|
||||
const originUrl = parseHttpUrl(origin)
|
||||
if (!originUrl) return unavailable('untrusted-origin', untrustedOriginMessage(origin))
|
||||
|
||||
const isLoopback = isLoopbackHost(originUrl.hostname)
|
||||
@@ -73,11 +70,11 @@ export function resolveDevicePairingAvailability(
|
||||
return unavailable('loopback', LOOPBACK_ORIGIN_MESSAGE)
|
||||
}
|
||||
|
||||
if (originUrl.protocol === 'http:' && !isLoopback && !isPrivateNetworkHost(originUrl.hostname)) {
|
||||
if (isPublicPlainHttpUrl(originUrl)) {
|
||||
return unavailable('insecure-origin', INSECURE_ORIGIN_MESSAGE)
|
||||
}
|
||||
|
||||
return { available: true, reason: null, message: null }
|
||||
return { available: true, reason: null, message: null, originUrl }
|
||||
}
|
||||
|
||||
/** Decides whether an origin can carry an app link and which warnings it raises. */
|
||||
|
||||
@@ -222,7 +222,7 @@ export class NotificationService {
|
||||
user_id = excluded.user_id,
|
||||
p256dh = excluded.p256dh,
|
||||
auth = excluded.auth,
|
||||
device_name = excluded.device_name,
|
||||
device_name = COALESCE(excluded.device_name, push_subscriptions.device_name),
|
||||
session_id = excluded.session_id,
|
||||
last_used_at = excluded.last_used_at`
|
||||
)
|
||||
|
||||
@@ -78,7 +78,7 @@ describe('createAuth', () => {
|
||||
body: { email: 'other@example.com', password: 'test-password', name: 'Other' },
|
||||
})).rejects.toThrow('Registration is disabled')
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
const response = await auth.handler(new Request('http://localhost:5173/api/auth/sign-in/email', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', origin: 'http://localhost:5173' },
|
||||
|
||||
@@ -7,7 +7,7 @@ export interface LoggerMocks {
|
||||
debug: Mock
|
||||
}
|
||||
|
||||
export function loggedArguments(loggerMocks: LoggerMocks): unknown[][] {
|
||||
function loggedArguments(loggerMocks: LoggerMocks): unknown[][] {
|
||||
return [...loggerMocks.info.mock.calls, ...loggerMocks.warn.mock.calls, ...loggerMocks.error.mock.calls]
|
||||
}
|
||||
|
||||
|
||||
@@ -102,6 +102,18 @@ async function findPasswordHash(auth: AuthInstance, userId: string): Promise<str
|
||||
return account!.password
|
||||
}
|
||||
|
||||
function insertPushSubscription(db: ReturnType<typeof createAuthDatabase>, endpoint: string, sessionId: string | null): void {
|
||||
db.prepare(
|
||||
`INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, session_id, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
).run('default', endpoint, 'p256dh-key', 'auth-key', sessionId, Date.now())
|
||||
}
|
||||
|
||||
function pushSubscriptionEndpoints(db: ReturnType<typeof createAuthDatabase>): string[] {
|
||||
return (db.prepare('SELECT endpoint FROM push_subscriptions ORDER BY endpoint').all() as Array<{ endpoint: string }>)
|
||||
.map((row) => row.endpoint)
|
||||
}
|
||||
|
||||
function createSession(): Session {
|
||||
return {
|
||||
session: {
|
||||
@@ -188,7 +200,7 @@ describe('syncAdminFromEnv', () => {
|
||||
})
|
||||
|
||||
it('does nothing when the admin credentials are not configured', async () => {
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect(await countRows(auth, 'user')).toBe(0)
|
||||
expect(mockLoggerInfo).not.toHaveBeenCalled()
|
||||
@@ -197,7 +209,7 @@ describe('syncAdminFromEnv', () => {
|
||||
it('does nothing when only one admin credential is configured', async () => {
|
||||
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect(await countRows(auth, 'user')).toBe(0)
|
||||
})
|
||||
@@ -208,7 +220,7 @@ describe('syncAdminFromEnv', () => {
|
||||
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect((await signInRequest(auth, 'admin@example.com', 'old-password')).status).toBe(200)
|
||||
expect((await signInRequest(auth, 'admin@example.com', 'new-password')).status).toBe(401)
|
||||
@@ -221,20 +233,39 @@ describe('syncAdminFromEnv', () => {
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
ENV.AUTH.ADMIN_PASSWORD_RESET = true
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect(await countRows(auth, 'user')).toBe(1)
|
||||
expect((await signInRequest(auth, 'Admin@Example.com', 'new-password')).status).toBe(200)
|
||||
expect((await signInRequest(auth, 'admin@example.com', 'old-password')).status).toBe(401)
|
||||
}, 30000)
|
||||
|
||||
it('finds the existing admin user when the stored email differs only by case', async () => {
|
||||
await auth.api.signUpEmail({ body: { email: 'admin@example.com', password: 'old-password', name: 'Admin' } })
|
||||
const cookies = await createUserSession(auth, 'admin@example.com', 'old-password')
|
||||
const adminId = (await auth.api.getSession({ headers: cookies }))!.user.id
|
||||
db.prepare('UPDATE "user" SET email = ? WHERE id = ?').run('Admin@Example.com', adminId)
|
||||
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
ENV.AUTH.ADMIN_PASSWORD_RESET = true
|
||||
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
const ctx = await auth.$context
|
||||
expect(await countRows(auth, 'user')).toBe(1)
|
||||
expect(await ctx.password.verify({
|
||||
password: 'new-password',
|
||||
hash: await findPasswordHash(auth, adminId),
|
||||
})).toBe(true)
|
||||
}, 30000)
|
||||
|
||||
it('resets the credential account password for an existing user', async () => {
|
||||
await auth.api.signUpEmail({ body: { email: 'admin@example.com', password: 'old-password', name: 'Admin' } })
|
||||
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
ENV.AUTH.ADMIN_PASSWORD_RESET = true
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect((await signInRequest(auth, 'admin@example.com', 'new-password')).status).toBe(200)
|
||||
expect((await signInRequest(auth, 'admin@example.com', 'old-password')).status).toBe(401)
|
||||
@@ -255,12 +286,34 @@ describe('syncAdminFromEnv', () => {
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
ENV.AUTH.ADMIN_PASSWORD_RESET = true
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect(await countRows(auth, 'session', adminId)).toBe(0)
|
||||
expect(await countRows(auth, 'session', otherId)).toBe(otherSessionsBefore)
|
||||
}, 30000)
|
||||
|
||||
it('deletes the push subscriptions of the revoked admin sessions and keeps the others', async () => {
|
||||
await auth.api.signUpEmail({ body: { email: 'admin@example.com', password: 'admin-password', name: 'Admin' } })
|
||||
await auth.api.signUpEmail({ body: { email: 'other@example.com', password: 'other-password', name: 'Other' } })
|
||||
const adminCookies = await createUserSession(auth, 'admin@example.com', 'admin-password')
|
||||
const otherCookies = await createUserSession(auth, 'other@example.com', 'other-password')
|
||||
const adminSessionId = (await auth.api.getSession({ headers: adminCookies }))!.session.id
|
||||
const otherSessionId = (await auth.api.getSession({ headers: otherCookies }))!.session.id
|
||||
insertPushSubscription(db, 'https://push.example.com/phone', adminSessionId)
|
||||
insertPushSubscription(db, 'https://push.example.com/tablet', otherSessionId)
|
||||
insertPushSubscription(db, 'https://push.example.com/legacy', null)
|
||||
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
ENV.AUTH.ADMIN_PASSWORD_RESET = true
|
||||
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect(pushSubscriptionEndpoints(db)).toEqual([
|
||||
'https://push.example.com/legacy',
|
||||
'https://push.example.com/tablet',
|
||||
])
|
||||
}, 30000)
|
||||
|
||||
it('runs the session delete hook for every revoked admin session', async () => {
|
||||
await auth.api.signUpEmail({ body: { email: 'admin@example.com', password: 'admin-password', name: 'Admin' } })
|
||||
const cookies = await createUserSession(auth, 'admin@example.com', 'admin-password')
|
||||
@@ -271,7 +324,7 @@ describe('syncAdminFromEnv', () => {
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
ENV.AUTH.ADMIN_PASSWORD_RESET = true
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect(close).toHaveBeenCalledTimes(1)
|
||||
}, 30000)
|
||||
@@ -286,7 +339,7 @@ describe('syncAdminFromEnv', () => {
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
ENV.AUTH.ADMIN_PASSWORD_RESET = true
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect(mockLoggerWarn).toHaveBeenCalledWith(expect.stringContaining('No credential account found'))
|
||||
expect(mockLoggerInfo).toHaveBeenCalledWith(expect.stringContaining('Admin password reset'))
|
||||
@@ -302,7 +355,7 @@ describe('syncAdminFromEnv', () => {
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
|
||||
ENV.AUTH.ADMIN_PASSWORD_RESET = true
|
||||
|
||||
await expect(syncAdminFromEnv(auth)).rejects.toThrow()
|
||||
await expect(syncAdminFromEnv(auth, db)).rejects.toThrow()
|
||||
|
||||
const ctx = await auth.$context
|
||||
expect(await ctx.password.verify({
|
||||
@@ -315,7 +368,7 @@ describe('syncAdminFromEnv', () => {
|
||||
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'admin-password'
|
||||
|
||||
await syncAdminFromEnv(auth)
|
||||
await syncAdminFromEnv(auth, db)
|
||||
|
||||
expect(await countRows(auth, 'user')).toBe(1)
|
||||
expect((await signInRequest(auth, 'admin@example.com', 'admin-password')).status).toBe(200)
|
||||
@@ -326,7 +379,7 @@ describe('syncAdminFromEnv', () => {
|
||||
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
|
||||
ENV.AUTH.ADMIN_PASSWORD = 'short'
|
||||
|
||||
await expect(syncAdminFromEnv(auth)).resolves.toBeUndefined()
|
||||
await expect(syncAdminFromEnv(auth, db)).resolves.toBeUndefined()
|
||||
|
||||
expect(await countRows(auth, 'user')).toBe(0)
|
||||
expect(mockLoggerError).toHaveBeenCalledWith('Failed to create admin user from environment:', expect.anything())
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { createNotificationRoutes } from '../../src/routes/notifications'
|
||||
import type { NotificationService } from '../../src/services/notification'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
import type { Session } from '../../src/auth'
|
||||
|
||||
interface NotificationServiceStub {
|
||||
@@ -144,6 +145,47 @@ describe('Notification Routes', () => {
|
||||
)
|
||||
})
|
||||
|
||||
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:')
|
||||
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]> = [
|
||||
['ses_old', 'Phone'],
|
||||
['ses_new', undefined],
|
||||
]
|
||||
|
||||
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))
|
||||
|
||||
const res = await sessionApp.fetch(new Request('http://localhost/subscribe', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: subscriptionBody(deviceName),
|
||||
}))
|
||||
expect(res.status).toBe(200)
|
||||
}
|
||||
|
||||
const rows = db
|
||||
.prepare('SELECT session_id, device_name FROM push_subscriptions WHERE endpoint = ?')
|
||||
.all(endpoint)
|
||||
expect(rows).toEqual([{ session_id: 'ses_new', device_name: 'Phone' }])
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('returns 400 for invalid subscription data', async () => {
|
||||
const res = await app.fetch(new Request('http://localhost/subscribe', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -17,6 +17,7 @@ describe('resolveDevicePairingAvailability', () => {
|
||||
available: true,
|
||||
reason: null,
|
||||
message: null,
|
||||
originUrl: new URL('https://m.example.com'),
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -78,6 +78,16 @@ describe('push subscription sessions', () => {
|
||||
expect(service.getSubscriptions(USER_ID)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps the stored device name when the same endpoint subscribes again without one', () => {
|
||||
const endpoint = 'https://push.example.com/phone'
|
||||
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(sessionIdOf(db, endpoint)).toBe('ses_new')
|
||||
expect(service.getSubscriptions(USER_ID)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('adds the session id column to a database created before it existed', () => {
|
||||
const legacyDb = new Database(':memory:')
|
||||
legacyDb.run(LEGACY_TABLE)
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isLoopbackHost, isPrivateNetworkHost } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
isLoopbackHost,
|
||||
isPrivateNetworkHost,
|
||||
isPublicPlainHttpUrl,
|
||||
parseHttpUrl,
|
||||
} from '@opencode-manager/shared/utils'
|
||||
|
||||
describe('isLoopbackHost', () => {
|
||||
it.each(['localhost', 'LOCALHOST', '127.0.0.1', '127.4.5.6', '::1', '[::1]'])(
|
||||
@@ -48,3 +53,49 @@ describe('isPrivateNetworkHost', () => {
|
||||
expect(isPrivateNetworkHost(host)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isPublicPlainHttpUrl', () => {
|
||||
it.each([
|
||||
'http://example.com',
|
||||
'http://example.com.',
|
||||
'http://203.0.113.5:5003',
|
||||
'http://8.8.8.8:5003/path',
|
||||
])('treats %s as public plain http', (url) => {
|
||||
expect(isPublicPlainHttpUrl(new URL(url))).toBe(true)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'https://example.com',
|
||||
'https://203.0.113.5:5003',
|
||||
'http://localhost:5173',
|
||||
'http://127.0.0.1:5003',
|
||||
'http://[::1]:5003',
|
||||
'http://192.168.1.20:5003',
|
||||
'http://172.16.0.1:5003',
|
||||
'http://100.64.0.1:5003',
|
||||
'http://[fd00::1]:5003',
|
||||
])('treats %s as not public plain http', (url) => {
|
||||
expect(isPublicPlainHttpUrl(new URL(url))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseHttpUrl', () => {
|
||||
it('parses an absolute http url', () => {
|
||||
expect(parseHttpUrl('http://m.example.com:5003/pair?x=1')?.origin).toBe(
|
||||
'http://m.example.com:5003',
|
||||
)
|
||||
})
|
||||
|
||||
it('parses an absolute https url with surrounding whitespace', () => {
|
||||
expect(parseHttpUrl(' https://m.example.com/settings?tab=pairing ')?.origin).toBe(
|
||||
'https://m.example.com',
|
||||
)
|
||||
})
|
||||
|
||||
it.each(['', 'not a url', '//m.example.com', 'ocm://link?v=2&kind=manager', 'ftp://example.com'])(
|
||||
'returns null for %s',
|
||||
(value) => {
|
||||
expect(parseHttpUrl(value)).toBeNull()
|
||||
},
|
||||
)
|
||||
})
|
||||
Reference in new issue
Block a user