diff --git a/src/components/AddProviderDialog.tsx b/src/components/AddProviderDialog.tsx index 6492a986..a64228e9 100644 --- a/src/components/AddProviderDialog.tsx +++ b/src/components/AddProviderDialog.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Rocket, ChevronDown } from 'lucide-react'; +import { Rocket, ChevronDown, Key, Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { ExternalInput } from '@/components/ui/external-input'; import { @@ -19,6 +19,8 @@ import { } from '@/components/ui/dropdown-menu'; import { ExternalFavicon } from '@/components/ExternalFavicon'; import { Link } from 'react-router-dom'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { requestBuildServerApiKey } from '@/lib/nip98'; interface PresetProvider { id: string; @@ -86,10 +88,13 @@ export function AddProviderDialog({ onAdd, }: AddProviderDialogProps) { const { t } = useTranslation(); + const { user } = useCurrentUser(); const [apiKey, setApiKey] = useState(''); const [accountId, setAccountId] = useState(''); const [organizationId, setOrganizationId] = useState(''); const [buildServerUrl, setBuildServerUrl] = useState(''); + const [isGettingApiKey, setIsGettingApiKey] = useState(false); + const [apiKeyError, setApiKeyError] = useState(null); const showNostrLoginRequired = preset.requiresNostr && !isLoggedIntoNostr; const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false; @@ -102,9 +107,33 @@ export function AddProviderDialog({ setAccountId(''); setOrganizationId(''); setBuildServerUrl(''); + setApiKeyError(null); onOpenChange(false); }; + const handleGetApiKey = async () => { + if (!buildServerUrl.trim() || !user?.signer) { + setApiKeyError('Build server URL and Nostr login required'); + return; + } + + setIsGettingApiKey(true); + setApiKeyError(null); + + try { + const result = await requestBuildServerApiKey( + user.signer, + buildServerUrl.trim(), + preset.proxy ? 'https://corsproxy.io/?' : undefined + ); + setApiKey(result.apiKey); + } catch (error) { + setApiKeyError(error instanceof Error ? error.message : 'Failed to get API key'); + } finally { + setIsGettingApiKey(false); + } + }; + const url = getProviderUrl(preset); return ( @@ -231,18 +260,61 @@ export function AddProviderDialog({ /> )} {preset.type === 'apkbuilder' && ( - setBuildServerUrl(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) { - handleAdd(); - } - }} - /> + <> + { + setBuildServerUrl(e.target.value); + setApiKeyError(null); + }} + onKeyDown={(e) => { + if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) { + handleAdd(); + } + }} + /> +
+ setApiKey(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) { + handleAdd(); + } + }} + className="flex-1" + /> + +
+ {apiKeyError && ( +

{apiKeyError}

+ )} + {!user?.signer && buildServerUrl.trim() && ( +

+ Login to Nostr to get an API key automatically +

+ )} + )} + {preset.type !== 'apkbuilder' && ( + )} )} diff --git a/src/lib/nip98.ts b/src/lib/nip98.ts new file mode 100644 index 00000000..6a9b26bb --- /dev/null +++ b/src/lib/nip98.ts @@ -0,0 +1,116 @@ +/** + * NIP-98 HTTP Auth utilities + * Creates signed events for HTTP authentication + */ +import type { NostrSigner, NostrEvent } from '@nostrify/nostrify'; + +/** + * Create a NIP-98 auth event for HTTP requests + */ +export async function createNip98AuthEvent( + signer: NostrSigner, + url: string, + method: string, + payload?: string +): Promise { + const tags: string[][] = [ + ['u', url], + ['method', method.toUpperCase()], + ]; + + // Add payload hash if provided + if (payload) { + const encoder = new TextEncoder(); + const data = encoder.encode(payload); + const hashBuffer = await crypto.subtle.digest('SHA-256', data); + const hashArray = Array.from(new Uint8Array(hashBuffer)); + const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); + tags.push(['payload', hashHex]); + } + + const event = await signer.signEvent({ + kind: 27235, + content: '', + tags, + created_at: Math.floor(Date.now() / 1000), + }); + + return event; +} + +/** + * Create Authorization header value from NIP-98 event + */ +export function createNip98AuthHeader(event: NostrEvent): string { + const eventJson = JSON.stringify(event); + const base64 = btoa(eventJson); + return `Nostr ${base64}`; +} + +/** + * Perform a NIP-98 authenticated request + */ +export async function nip98Fetch( + signer: NostrSigner, + url: string, + options: RequestInit = {} +): Promise { + const method = options.method || 'GET'; + const body = options.body as string | undefined; + + const event = await createNip98AuthEvent(signer, url, method, body); + const authHeader = createNip98AuthHeader(event); + + return fetch(url, { + ...options, + headers: { + ...options.headers, + 'Authorization': authHeader, + }, + }); +} + +/** + * Request an API key from a build server using NIP-98 auth + */ +export async function requestBuildServerApiKey( + signer: NostrSigner, + buildServerUrl: string, + corsProxy?: string +): Promise<{ apiKey: string; pubkey: string; isNew: boolean }> { + const authUrl = `${buildServerUrl.replace(/\/+$/, '')}/api/auth`; + + // Create the auth event + const event = await createNip98AuthEvent(signer, authUrl, 'POST'); + const authHeader = createNip98AuthHeader(event); + + // Make the request (use CORS proxy if provided) + const targetUrl = corsProxy + ? `${corsProxy}/${authUrl.replace(/^https?:\/\//, '')}` + : authUrl; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': authHeader, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + const error = await response.json().catch(() => ({ error: 'Request failed' })); + throw new Error(error.error || `HTTP ${response.status}`); + } + + const data = await response.json(); + + if (!data.success || !data.apiKey) { + throw new Error(data.error || 'Failed to get API key'); + } + + return { + apiKey: data.apiKey, + pubkey: data.pubkey, + isNew: data.isNew, + }; +}