From b3db9888222a07f4e0902fef6102fcf902e03053 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 1 Apr 2026 12:12:33 +0100 Subject: [PATCH] fix: key atproto client by fixed appurl --- server/api/_cron/sync.ts | 5 +- server/plugins/atproto-client.ts | 18 +++++ server/routes/auth/bluesky.get.ts | 2 +- server/utils/atproto-stores.ts | 115 ++++++++++++++++++++++++++++++ server/utils/atproto.ts | 88 +---------------------- 5 files changed, 138 insertions(+), 90 deletions(-) create mode 100644 server/plugins/atproto-client.ts create mode 100644 server/utils/atproto-stores.ts diff --git a/server/api/_cron/sync.ts b/server/api/_cron/sync.ts index 4b79246..a9d108e 100644 --- a/server/api/_cron/sync.ts +++ b/server/api/_cron/sync.ts @@ -44,12 +44,13 @@ async function syncGuildEvents(h3Event: Parameters } } + // Keep the atproto session alive by calling restore() on each sync. if (guild.atprotoDid) { try { await getAtprotoAgent(h3Event, guild.atprotoDid) } - catch { - // Session is invalid — will be handled when publishing + catch (error) { + console.error(`AT Proto session refresh failed for guild ${guildId}:`, error) } } diff --git a/server/plugins/atproto-client.ts b/server/plugins/atproto-client.ts new file mode 100644 index 0000000..6584c73 --- /dev/null +++ b/server/plugins/atproto-client.ts @@ -0,0 +1,18 @@ +import type { NodeOAuthClient } from '@atproto/oauth-client-node' + +/** + * Creates a long-lived NodeOAuthClient instance at server startup. + */ +export default defineNitroPlugin((nitroApp) => { + const client = createAtprotoClient() + + nitroApp.hooks.hook('request', (event) => { + event.context.atprotoClient = client + }) +}) + +declare module 'h3' { + interface H3EventContext { + atprotoClient: NodeOAuthClient + } +} diff --git a/server/routes/auth/bluesky.get.ts b/server/routes/auth/bluesky.get.ts index daebd5f..eeda93e 100644 --- a/server/routes/auth/bluesky.get.ts +++ b/server/routes/auth/bluesky.get.ts @@ -1,6 +1,6 @@ export default defineEventHandler(async (event) => { const query = getQuery(event) - const client = getAtprotoClient(event) + const client = event.context.atprotoClient // Step 1: No code = initial request, start the OAuth flow if (!query.code) { diff --git a/server/utils/atproto-stores.ts b/server/utils/atproto-stores.ts new file mode 100644 index 0000000..0cb5858 --- /dev/null +++ b/server/utils/atproto-stores.ts @@ -0,0 +1,115 @@ +import { NodeOAuthClient } from '@atproto/oauth-client-node' +import type { NodeSavedSession, NodeSavedSessionStore, NodeSavedStateStore } from '@atproto/oauth-client-node' + +export function kvSessionStore(): NodeSavedSessionStore { + return { + async get(key: string): Promise { + return (await useStorage('kv').getItem(`atproto:session:${key}`) as NodeSavedSession) ?? undefined + }, + async set(key: string, val: NodeSavedSession): Promise { + await useStorage('kv').setItem(`atproto:session:${key}`, val) + }, + async del(key: string): Promise { + await useStorage('kv').removeItem(`atproto:session:${key}`) + }, + } +} + +export function kvStateStore(): NodeSavedStateStore { + return { + async get(key: string) { + return (await useStorage('kv').getItem(`atproto:state:${key}`)) as never ?? undefined + }, + async set(key: string, val: Record): Promise { + await useStorage('kv').setItem(`atproto:state:${key}`, val, { ttl: 600 }) + }, + async del(key: string): Promise { + await useStorage('kv').removeItem(`atproto:state:${key}`) + }, + } +} + +const _locks = new Map>() + +/** + * Distributed lock for serialising token refresh operations. + * + * Uses KV-based locking with a 30-second TTL. If the lock cannot be + * acquired after two attempts, proceeds without it. + */ +export async function distributedLock(key: string, fn: () => T | PromiseLike): Promise { + const lockKey = `lock:${key}` + const lockId = Math.random().toString(36).slice(2) + const kv = useStorage('kv') + + // In-memory lock for same-process concurrency + while (_locks.has(key)) await _locks.get(key) + + // KV-based distributed lock with TTL (auto-expires after 30s to prevent deadlocks) + let acquired = false + const existing = await kv.getItem(lockKey) + if (!existing) { + await kv.setItem(lockKey, lockId, { ttl: 30 }) + const held = await kv.getItem(lockKey) + if (held === lockId) acquired = true + } + + if (!acquired) { + // Wait briefly and retry once + await new Promise(resolve => setTimeout(resolve, 100)) + const retryExisting = await kv.getItem(lockKey) + if (!retryExisting) { + await kv.setItem(lockKey, lockId, { ttl: 30 }) + const held = await kv.getItem(lockKey) + if (held === lockId) acquired = true + } + } + + if (!acquired) { + // Proceed without the lock — better than failing or force-acquiring + return await fn() + } + + const promise = Promise.resolve(fn()).finally(async () => { + _locks.delete(key) + // Only release if we still hold the lock + const held = await kv.getItem(lockKey) + if (held === lockId) { + await kv.removeItem(lockKey) + } + }) + _locks.set(key, promise) + return promise +} + +export function createAtprotoClient(): NodeOAuthClient { + const config = useRuntimeConfig() + const blueskyConfig = config.oauth.bluesky as { + scope?: string[] + redirectUris?: string[] + } + + const appUrl = config.public.appUrl as string + const scopes = [...new Set(['atproto', ...blueskyConfig.scope ?? []])] + const scope = scopes.join(' ') + const redirectUri = `${appUrl}${blueskyConfig.redirectUris?.[0] ?? '/auth/bluesky'}` + + const clientId = import.meta.dev + ? `http://localhost?redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scope)}` + : `${appUrl}/bluesky/client-metadata.json` + + return new NodeOAuthClient({ + clientMetadata: { + client_id: clientId, + redirect_uris: [redirectUri], + scope, + grant_types: ['authorization_code', 'refresh_token'], + application_type: 'web', + token_endpoint_auth_method: 'none', + dpop_bound_access_tokens: true, + }, + sessionStore: kvSessionStore(), + stateStore: kvStateStore(), + requestLock: distributedLock, + }) +} diff --git a/server/utils/atproto.ts b/server/utils/atproto.ts index b0746cf..464526d 100644 --- a/server/utils/atproto.ts +++ b/server/utils/atproto.ts @@ -1,5 +1,3 @@ -import { NodeOAuthClient } from '@atproto/oauth-client-node' -import type { NodeSavedSession, NodeSavedSessionStore, NodeSavedStateStore } from '@atproto/oauth-client-node' import { Agent } from '@atproto/api' import type { H3Event } from 'h3' @@ -27,92 +25,8 @@ const RSVP_STATUS_MAP: Record = { notgoing: 'community.lexicon.calendar.rsvp#notgoing', } -function kvSessionStore(): NodeSavedSessionStore { - return { - async get(key: string): Promise { - return (await useStorage('kv').getItem(`atproto:session:${key}`) as NodeSavedSession) ?? undefined - }, - async set(key: string, val: NodeSavedSession): Promise { - await useStorage('kv').setItem(`atproto:session:${key}`, val) - }, - async del(key: string): Promise { - await useStorage('kv').removeItem(`atproto:session:${key}`) - }, - } -} - -function kvStateStore(): NodeSavedStateStore { - return { - async get(key: string) { - return (await useStorage('kv').getItem(`atproto:state:${key}`)) as never ?? undefined - }, - async set(key: string, val: Record): Promise { - await useStorage('kv').setItem(`atproto:state:${key}`, val, { ttl: 600 }) - }, - async del(key: string): Promise { - await useStorage('kv').removeItem(`atproto:state:${key}`) - }, - } -} - -const _locks = new Map>() - -let _client: NodeOAuthClient | null = null -let _clientHost: string | null = null - -async function distributedLock(key: string, fn: () => T | PromiseLike): Promise { - const lockKey = `lock:${key}` - const lockId = Math.random().toString(36).slice(2) - const kv = useStorage('kv') - - // In-memory lock for same-process concurrency - while (_locks.has(key)) await _locks.get(key) - - // KV-based distributed lock with TTL (auto-expires after 30s to prevent deadlocks) - const maxAttempts = 10 - for (let attempt = 0; attempt < maxAttempts; attempt++) { - const existing = await kv.getItem(lockKey) - if (!existing) { - await kv.setItem(lockKey, lockId, { ttl: 30 }) - // Verify we got the lock (simple check-and-set) - const held = await kv.getItem(lockKey) - if (held === lockId) break - } - // Wait and retry - await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 300)) - if (attempt === maxAttempts - 1) { - // Force acquire after timeout (previous lock likely stale) - await kv.setItem(lockKey, lockId, { ttl: 30 }) - } - } - - const promise = Promise.resolve(fn()).finally(async () => { - _locks.delete(key) - // Only release if we still hold the lock - const held = await kv.getItem(lockKey) - if (held === lockId) { - await kv.removeItem(lockKey) - } - }) - _locks.set(key, promise) - return promise -} - -export function getAtprotoClient(event: H3Event): NodeOAuthClient { - const host = getRequestURL(event).host - if (_client && _clientHost === host) return _client - _client = new NodeOAuthClient({ - clientMetadata: getAtprotoClientMetadata(event, 'bluesky'), - sessionStore: kvSessionStore(), - stateStore: kvStateStore(), - requestLock: distributedLock, - }) - _clientHost = host - return _client -} - export async function getAtprotoAgent(event: H3Event, did: string): Promise { - const client = getAtprotoClient(event) + const client = event.context.atprotoClient try { const session = await client.restore(did) return new Agent(session) -- knotmirror 0.0.1