mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add NIP-98 authentication for APK Builder API keys
Users can now request API keys from build servers using Nostr authentication. The AddProviderDialog includes a key button that initiates NIP-98 auth with the configured build server URL. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
This commit is contained in:
1 parent
e8cfcb7383
commit
8660f4ad96
2 files changed
+201
-12
No files matched your search
@@ -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<string | null>(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' && (
|
||||
<ExternalInput
|
||||
type="text"
|
||||
placeholder={preset.buildServerUrlLabel || 'Build Server URL'}
|
||||
value={buildServerUrl}
|
||||
onChange={(e) => setBuildServerUrl(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<>
|
||||
<ExternalInput
|
||||
type="text"
|
||||
placeholder={preset.buildServerUrlLabel || 'Build Server URL'}
|
||||
value={buildServerUrl}
|
||||
onChange={(e) => {
|
||||
setBuildServerUrl(e.target.value);
|
||||
setApiKeyError(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.apiKeyLabel || 'API Key'}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleGetApiKey}
|
||||
disabled={!buildServerUrl.trim() || !user?.signer || isGettingApiKey}
|
||||
className="shrink-0"
|
||||
title={!user?.signer ? 'Login to Nostr first' : 'Get API key using Nostr authentication'}
|
||||
>
|
||||
{isGettingApiKey ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Key className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{apiKeyError && (
|
||||
<p className="text-xs text-destructive">{apiKeyError}</p>
|
||||
)}
|
||||
{!user?.signer && buildServerUrl.trim() && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<Link to="/settings/nostr" className="underline">Login to Nostr</Link> to get an API key automatically
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{preset.type !== 'apkbuilder' && (
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||
@@ -258,6 +330,7 @@ export function AddProviderDialog({
|
||||
url={preset.apiKeyURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -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<NostrEvent> {
|
||||
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<Response> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user