mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +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`
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user