mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
15
Commits
No files matched your search
Generated
+21
@@ -68,6 +68,7 @@
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.562.0",
|
||||
"mime": "^4.1.0",
|
||||
"node-forge": "^1.3.3",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^5.15.0",
|
||||
@@ -107,6 +108,7 @@
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
@@ -5613,6 +5615,16 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node-forge": {
|
||||
"version": "1.3.14",
|
||||
"resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz",
|
||||
"integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/nunjucks": {
|
||||
"version": "3.2.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/nunjucks/-/nunjucks-3.2.6.tgz",
|
||||
@@ -11741,6 +11753,15 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/node-forge": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.3.tgz",
|
||||
"integrity": "sha512-rLvcdSyRCyouf6jcOIPe/BgwG/d7hKjzMKOas33/pHEr6gbq18IK9zV7DiPvzsz0oBJPme6qr6H6kGZuI9/DZg==",
|
||||
"license": "(BSD-3-Clause OR GPL-2.0)",
|
||||
"engines": {
|
||||
"node": ">= 6.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/node-releases": {
|
||||
"version": "2.0.26",
|
||||
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.26.tgz",
|
||||
|
||||
@@ -79,6 +79,7 @@
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.562.0",
|
||||
"mime": "^4.1.0",
|
||||
"node-forge": "^1.3.3",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^5.15.0",
|
||||
@@ -118,6 +119,7 @@
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# APK Build Service - Nginx Configuration
|
||||
#
|
||||
# Usage:
|
||||
# 1. Copy to /etc/nginx/sites-available/apk-builder
|
||||
# 2. Update server_name to your domain
|
||||
# 3. Update SSL certificate paths (or use certbot)
|
||||
# 4. sudo ln -s /etc/nginx/sites-available/apk-builder /etc/nginx/sites-enabled/
|
||||
# 5. sudo nginx -t && sudo systemctl reload nginx
|
||||
#
|
||||
# For Let's Encrypt SSL:
|
||||
# sudo certbot --nginx -d apk-builder.yourdomain.com
|
||||
#
|
||||
|
||||
# Rate limiting zone (optional - uncomment to enable)
|
||||
# limit_req_zone $binary_remote_addr zone=apk_build_limit:10m rate=5r/m;
|
||||
|
||||
upstream apk_builder {
|
||||
server 127.0.0.1:3000;
|
||||
keepalive 32;
|
||||
}
|
||||
|
||||
# Redirect HTTP to HTTPS
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name apk-builder.yourdomain.com;
|
||||
|
||||
# Let's Encrypt challenge
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://$server_name$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
# HTTPS server
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name apk-builder.yourdomain.com;
|
||||
|
||||
# SSL Configuration
|
||||
# Option 1: Let's Encrypt (recommended)
|
||||
ssl_certificate /etc/letsencrypt/live/apk-builder.yourdomain.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/apk-builder.yourdomain.com/privkey.pem;
|
||||
|
||||
# Option 2: Self-signed (for testing only)
|
||||
# ssl_certificate /etc/nginx/ssl/apk-builder.crt;
|
||||
# ssl_certificate_key /etc/nginx/ssl/apk-builder.key;
|
||||
|
||||
# SSL Security Settings
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
|
||||
ssl_prefer_server_ciphers off;
|
||||
ssl_session_timeout 1d;
|
||||
ssl_session_cache shared:SSL:50m;
|
||||
ssl_session_tickets off;
|
||||
|
||||
# OCSP Stapling
|
||||
ssl_stapling on;
|
||||
ssl_stapling_verify on;
|
||||
resolver 8.8.8.8 8.8.4.4 valid=300s;
|
||||
resolver_timeout 5s;
|
||||
|
||||
# Security Headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
|
||||
# Allow large file uploads (for project ZIPs)
|
||||
client_max_body_size 100M;
|
||||
client_body_timeout 300s;
|
||||
client_body_buffer_size 128k;
|
||||
|
||||
# Logging
|
||||
access_log /var/log/nginx/apk-builder.access.log;
|
||||
error_log /var/log/nginx/apk-builder.error.log;
|
||||
|
||||
# Health check endpoint (no auth, fast response)
|
||||
location = /health {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 10s;
|
||||
}
|
||||
|
||||
# Build submission endpoint (longer timeouts)
|
||||
location = /api/build {
|
||||
# Optional rate limiting - uncomment to enable
|
||||
# limit_req zone=apk_build_limit burst=2 nodelay;
|
||||
# limit_req_status 429;
|
||||
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
# Long timeout for upload processing
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
# Status polling endpoint
|
||||
location ~ ^/api/build/[a-f0-9-]+/status$ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
|
||||
# APK download endpoint (large response, long timeout)
|
||||
location ~ ^/api/build/[a-f0-9-]+/download$ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
# Long timeout for large APK downloads
|
||||
proxy_connect_timeout 30s;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_send_timeout 600s;
|
||||
|
||||
# Buffering for large files
|
||||
proxy_buffering on;
|
||||
proxy_buffer_size 128k;
|
||||
proxy_buffers 4 256k;
|
||||
proxy_busy_buffers_size 256k;
|
||||
}
|
||||
|
||||
# All other API endpoints
|
||||
location /api/ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 30s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
# Block all other paths
|
||||
location / {
|
||||
return 404 '{"error": "Not found"}';
|
||||
add_header Content-Type application/json;
|
||||
}
|
||||
}
|
||||
@@ -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,9 @@ import {
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { requestBuildServerApiKey } from '@/lib/nip98';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
|
||||
interface OAuthHook {
|
||||
@@ -36,7 +39,7 @@ interface AddProviderDialogProps {
|
||||
oauthHook: OAuthHook | null;
|
||||
forceManualEntry: boolean;
|
||||
onSetForceManualEntry: (force: boolean) => void;
|
||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
|
||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => void;
|
||||
}
|
||||
|
||||
export function AddProviderDialog({
|
||||
@@ -50,9 +53,14 @@ export function AddProviderDialog({
|
||||
onAdd,
|
||||
}: AddProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
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;
|
||||
@@ -60,13 +68,38 @@ export function AddProviderDialog({
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
const handleAdd = () => {
|
||||
onAdd(apiKey, accountId, organizationId);
|
||||
onAdd(apiKey, accountId, organizationId, buildServerUrl);
|
||||
setApiKey('');
|
||||
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 ? config.corsProxy : undefined
|
||||
);
|
||||
setApiKey(result.apiKey);
|
||||
} catch (error) {
|
||||
setApiKeyError(error instanceof Error ? error.message : 'Failed to get API key');
|
||||
} finally {
|
||||
setIsGettingApiKey(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
@@ -182,21 +215,78 @@ export function AddProviderDialog({
|
||||
urlTitle="Find ID"
|
||||
/>
|
||||
)}
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() &&
|
||||
(preset.type !== 'cloudflare' || accountId.trim()) &&
|
||||
(preset.type !== 'deno' || organizationId.trim())) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.apiKeyURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
{preset.type === 'apkbuilder' && (
|
||||
<>
|
||||
<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')}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() &&
|
||||
(preset.type !== 'cloudflare' || accountId.trim()) &&
|
||||
(preset.type !== 'deno' || organizationId.trim())) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.apiKeyURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -214,7 +304,8 @@ export function AddProviderDialog({
|
||||
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
||||
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
|
||||
(preset.type === 'cloudflare' && !accountId.trim()) ||
|
||||
(preset.type === 'deno' && !organizationId.trim())
|
||||
(preset.type === 'deno' && !organizationId.trim()) ||
|
||||
(preset.type === 'apkbuilder' && !buildServerUrl.trim())
|
||||
}
|
||||
>
|
||||
{t('add')}
|
||||
|
||||
@@ -125,6 +125,44 @@ export function ProviderConfigDialog({
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : localProvider.type === 'apkbuilder' ? (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-buildServerUrl">
|
||||
{preset?.buildServerUrlLabel || 'Build Server URL'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-buildServerUrl"
|
||||
placeholder="https://apk-builder.example.com"
|
||||
value={localProvider.buildServerUrl || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, buildServerUrl: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-apiKey">
|
||||
{preset?.apiKeyLabel || 'API Key'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="provider-apiKey"
|
||||
placeholder="Enter API Key"
|
||||
value={localProvider.apiKey}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, apiKey: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="provider-proxy"
|
||||
checked={localProvider.proxy || false}
|
||||
onCheckedChange={(checked) => setLocalProvider({ ...localProvider, proxy: checked === true })}
|
||||
/>
|
||||
<Label
|
||||
htmlFor="provider-proxy"
|
||||
className="text-sm font-normal cursor-pointer"
|
||||
>
|
||||
Use CORS Proxy
|
||||
</Label>
|
||||
</div>
|
||||
</>
|
||||
) : localProvider.type === 'nsite' ? (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { CheckCircle, XCircle, Loader2, Shield, Bug } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { APKBuildType } from '@/lib/deploy/types';
|
||||
|
||||
interface APKBuilderDeployFormProps {
|
||||
buildServerUrl: string;
|
||||
apiKey: string;
|
||||
projectId: string;
|
||||
projectName?: string;
|
||||
savedAppName?: string;
|
||||
savedPackageId?: string;
|
||||
savedBuildType?: APKBuildType;
|
||||
onConfigChange: (appName: string, packageId: string, buildType: APKBuildType) => void;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
interface ServerHealth {
|
||||
status: 'ok' | 'error';
|
||||
version?: string;
|
||||
queue?: {
|
||||
running: number;
|
||||
queued: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function APKBuilderDeployForm({
|
||||
buildServerUrl,
|
||||
apiKey,
|
||||
projectId,
|
||||
projectName,
|
||||
savedAppName,
|
||||
savedPackageId,
|
||||
savedBuildType,
|
||||
onConfigChange,
|
||||
corsProxy,
|
||||
}: APKBuilderDeployFormProps) {
|
||||
const [appName, setAppName] = useState(savedAppName || projectName || projectId);
|
||||
const [packageId, setPackageId] = useState(savedPackageId || '');
|
||||
const [buildType, setBuildType] = useState<APKBuildType>(savedBuildType || 'debug');
|
||||
const [packageIdError, setPackageIdError] = useState<string | null>(null);
|
||||
const [serverHealth, setServerHealth] = useState<ServerHealth | null>(null);
|
||||
const [isCheckingServer, setIsCheckingServer] = useState(true);
|
||||
|
||||
// Generate default package ID from project name
|
||||
useEffect(() => {
|
||||
if (!savedPackageId && !packageId) {
|
||||
const safeName = (projectName || projectId)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]/g, '');
|
||||
setPackageId(`com.app.${safeName}`);
|
||||
}
|
||||
}, [projectName, projectId, savedPackageId, packageId]);
|
||||
|
||||
// Check server health
|
||||
const checkServerHealth = useCallback(async () => {
|
||||
setIsCheckingServer(true);
|
||||
try {
|
||||
const url = `${buildServerUrl}/health`;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: {
|
||||
'X-API-Key': apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setServerHealth({ status: 'ok', ...data });
|
||||
} else {
|
||||
setServerHealth({ status: 'error' });
|
||||
}
|
||||
} catch {
|
||||
setServerHealth({ status: 'error' });
|
||||
} finally {
|
||||
setIsCheckingServer(false);
|
||||
}
|
||||
}, [buildServerUrl, apiKey, corsProxy]);
|
||||
|
||||
useEffect(() => {
|
||||
checkServerHealth();
|
||||
}, [checkServerHealth]);
|
||||
|
||||
// Validate package ID
|
||||
const validatePackageId = (value: string): boolean => {
|
||||
// Android package ID rules:
|
||||
// - Must have at least two segments (e.g., com.example)
|
||||
// - Each segment must start with a letter
|
||||
// - Can only contain letters, numbers, and underscores
|
||||
const pattern = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/i;
|
||||
return pattern.test(value);
|
||||
};
|
||||
|
||||
// Handle package ID change with validation
|
||||
const handlePackageIdChange = (value: string) => {
|
||||
setPackageId(value);
|
||||
if (value && !validatePackageId(value)) {
|
||||
setPackageIdError('Package ID must be like "com.example.myapp" (letters, numbers, underscores)');
|
||||
} else {
|
||||
setPackageIdError(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Notify parent of config changes
|
||||
useEffect(() => {
|
||||
if (appName && packageId && !packageIdError) {
|
||||
onConfigChange(appName, packageId, buildType);
|
||||
}
|
||||
}, [appName, packageId, packageIdError, buildType, onConfigChange]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Server Status */}
|
||||
<div className="rounded-lg border p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{isCheckingServer ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : serverHealth?.status === 'ok' ? (
|
||||
<CheckCircle className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<XCircle className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium">
|
||||
{isCheckingServer
|
||||
? 'Checking build server...'
|
||||
: serverHealth?.status === 'ok'
|
||||
? 'Build server connected'
|
||||
: 'Build server unavailable'}
|
||||
</p>
|
||||
{serverHealth?.status === 'ok' && serverHealth.queue && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{serverHealth.queue.running > 0
|
||||
? `${serverHealth.queue.running} build(s) in progress`
|
||||
: 'Ready to build'}
|
||||
{serverHealth.queue.queued > 0 && `, ${serverHealth.queue.queued} queued`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{serverHealth?.status === 'error' && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
Cannot connect to build server. Check your server URL and API key in Deploy Settings.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* App Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="app-name">App Name</Label>
|
||||
<Input
|
||||
id="app-name"
|
||||
value={appName}
|
||||
onChange={(e) => setAppName(e.target.value)}
|
||||
placeholder="My App"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This name appears on the Android home screen
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Package ID */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="package-id">Package ID</Label>
|
||||
<Input
|
||||
id="package-id"
|
||||
value={packageId}
|
||||
onChange={(e) => handlePackageIdChange(e.target.value)}
|
||||
placeholder="com.example.myapp"
|
||||
className={packageIdError ? 'border-red-500' : ''}
|
||||
/>
|
||||
{packageIdError ? (
|
||||
<p className="text-xs text-red-500">{packageIdError}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Unique identifier for your app (e.g., com.yourcompany.appname)
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Build Type Toggle */}
|
||||
<div className="space-y-2">
|
||||
<Label>Build Type</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBuildType('debug')}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
|
||||
"border-2 hover:scale-105 active:scale-95",
|
||||
buildType === 'debug'
|
||||
? "bg-primary text-primary-foreground border-primary shadow-sm"
|
||||
: "bg-background text-foreground border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Bug className="h-3.5 w-3.5" />
|
||||
<span>Debug</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBuildType('release')}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
|
||||
"border-2 hover:scale-105 active:scale-95",
|
||||
buildType === 'release'
|
||||
? "bg-primary text-primary-foreground border-primary shadow-sm"
|
||||
: "bg-background text-foreground border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Shield className="h-3.5 w-3.5" />
|
||||
<span>Release</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Build Info */}
|
||||
<div className="rounded-lg bg-muted/50 p-3 space-y-1">
|
||||
{buildType === 'debug' ? (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Build type:</strong> Debug APK (for testing/sideloading)
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Uses debug signing key. Install via USB or file transfer.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Build type:</strong> Release APK (unsigned)
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Server builds unsigned APK. Signing will be done in your browser.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Output:</strong> Downloadable .apk file
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Release Signing Info */}
|
||||
{buildType === 'release' && (
|
||||
<Alert>
|
||||
<Shield className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">
|
||||
Release builds require signing. You'll be prompted to configure your signing key after the build completes.
|
||||
Your signing key never leaves your browser.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { Key, Upload, Plus, Download, Loader2, CheckCircle, AlertCircle, FileKey, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
signApk,
|
||||
generateSigningKey,
|
||||
importKeyFromPkcs12,
|
||||
exportKeyToPkcs12,
|
||||
hasSavedKey,
|
||||
getSavedKeyInfo,
|
||||
loadSavedKey,
|
||||
saveKey,
|
||||
deleteSavedKey,
|
||||
type SigningKey,
|
||||
type StoredKeyInfo,
|
||||
} from '@/lib/apk';
|
||||
|
||||
interface APKSignerProps {
|
||||
unsignedApkUrl: string;
|
||||
appName: string;
|
||||
onComplete: (signedApkBlob: Blob) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
type KeySource = 'saved' | 'upload' | 'generate' | null;
|
||||
type SigningStatus = 'idle' | 'loading-apk' | 'signing' | 'complete' | 'error';
|
||||
|
||||
export function APKSigner({ unsignedApkUrl, appName, onComplete, onCancel }: APKSignerProps) {
|
||||
const [keySource, setKeySource] = useState<KeySource>(null);
|
||||
const [signingKey, setSigningKey] = useState<SigningKey | null>(null);
|
||||
const [status, setStatus] = useState<SigningStatus>('idle');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [progress, setProgress] = useState<string>('');
|
||||
|
||||
// Saved key state
|
||||
const [savedKeyInfo, setSavedKeyInfo] = useState<StoredKeyInfo | null>(null);
|
||||
const [savedKeyPassword, setSavedKeyPassword] = useState('');
|
||||
const [saveKeyAfter, setSaveKeyAfter] = useState(true);
|
||||
|
||||
// Upload form state
|
||||
const [uploadPassword, setUploadPassword] = useState('');
|
||||
const [uploadFile, setUploadFile] = useState<File | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Generate form state
|
||||
const [generateName, setGenerateName] = useState(appName || 'My App');
|
||||
const [generateOrg, setGenerateOrg] = useState('');
|
||||
const [generatePassword, setGeneratePassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
|
||||
// Check for saved key on mount
|
||||
useEffect(() => {
|
||||
if (hasSavedKey()) {
|
||||
const info = getSavedKeyInfo();
|
||||
setSavedKeyInfo(info);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setUploadFile(file);
|
||||
setError(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleLoadSavedKey = useCallback(() => {
|
||||
if (!savedKeyPassword) {
|
||||
setError('Please enter the password');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const key = loadSavedKey(savedKeyPassword);
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load saved key');
|
||||
}
|
||||
}, [savedKeyPassword]);
|
||||
|
||||
const handleDeleteSavedKey = useCallback(() => {
|
||||
deleteSavedKey();
|
||||
setSavedKeyInfo(null);
|
||||
setKeySource(null);
|
||||
}, []);
|
||||
|
||||
const handleImportKeystore = useCallback(async () => {
|
||||
if (!uploadFile || !uploadPassword) {
|
||||
setError('Please select a file and enter the password');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setStatus('loading-apk');
|
||||
setProgress('Reading keystore...');
|
||||
|
||||
const arrayBuffer = await uploadFile.arrayBuffer();
|
||||
const key = importKeyFromPkcs12(arrayBuffer, uploadPassword);
|
||||
|
||||
// Save key if requested
|
||||
if (saveKeyAfter) {
|
||||
saveKey(key, uploadPassword);
|
||||
setSavedKeyInfo(getSavedKeyInfo());
|
||||
}
|
||||
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
setStatus('idle');
|
||||
setProgress('');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import keystore');
|
||||
setStatus('error');
|
||||
}
|
||||
}, [uploadFile, uploadPassword, saveKeyAfter]);
|
||||
|
||||
const handleGenerateKeystore = useCallback(() => {
|
||||
if (!generateName.trim()) {
|
||||
setError('Please enter an app/key name');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!generatePassword) {
|
||||
setError('Please enter a password');
|
||||
return;
|
||||
}
|
||||
|
||||
if (generatePassword !== confirmPassword) {
|
||||
setError('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
if (generatePassword.length < 6) {
|
||||
setError('Password must be at least 6 characters');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setProgress('Generating key pair...');
|
||||
const key = generateSigningKey({
|
||||
commonName: generateName.trim(),
|
||||
organizationName: generateOrg.trim() || undefined,
|
||||
});
|
||||
|
||||
// Save key if requested
|
||||
if (saveKeyAfter) {
|
||||
saveKey(key, generatePassword);
|
||||
setSavedKeyInfo(getSavedKeyInfo());
|
||||
}
|
||||
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
setProgress('');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to generate keystore');
|
||||
}
|
||||
}, [generateName, generateOrg, generatePassword, confirmPassword, saveKeyAfter]);
|
||||
|
||||
const handleDownloadKeystore = useCallback(() => {
|
||||
if (!signingKey) return;
|
||||
|
||||
const password = keySource === 'generate' ? generatePassword : uploadPassword;
|
||||
const p12Data = exportKeyToPkcs12(signingKey, password);
|
||||
const blob = new Blob([p12Data], { type: 'application/x-pkcs12' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${appName.replace(/[^a-zA-Z0-9]/g, '_')}_release_key.p12`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}, [signingKey, keySource, generatePassword, uploadPassword, appName]);
|
||||
|
||||
const handleSign = useCallback(async () => {
|
||||
if (!signingKey) {
|
||||
setError('No signing key configured');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setStatus('loading-apk');
|
||||
setProgress('Downloading unsigned APK...');
|
||||
setError(null);
|
||||
|
||||
// Fetch the unsigned APK
|
||||
const response = await fetch(unsignedApkUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download APK: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const apkData = await response.arrayBuffer();
|
||||
const sizeMB = (apkData.byteLength / 1024 / 1024).toFixed(2);
|
||||
setProgress(`Downloaded ${sizeMB} MB. Signing APK...`);
|
||||
setStatus('signing');
|
||||
|
||||
// Sign the APK
|
||||
const signedApk = await signApk({
|
||||
key: signingKey,
|
||||
apkData,
|
||||
});
|
||||
|
||||
setStatus('complete');
|
||||
setProgress('');
|
||||
onComplete(signedApk);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to sign APK');
|
||||
setStatus('error');
|
||||
}
|
||||
}, [signingKey, unsignedApkUrl, onComplete]);
|
||||
|
||||
const renderKeySourceSelection = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Configure Signing Key</span>
|
||||
</div>
|
||||
|
||||
{/* Saved key option */}
|
||||
{savedKeyInfo && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('saved')}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left",
|
||||
keySource === 'saved'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10">
|
||||
<Key className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{savedKeyInfo.commonName}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Saved key • Expires {new Date(savedKeyInfo.expiresAt).getFullYear()}
|
||||
</p>
|
||||
</div>
|
||||
<CheckCircle className="h-5 w-5 text-primary flex-shrink-0" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('upload')}
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all",
|
||||
keySource === 'upload'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Upload className="h-6 w-6 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Upload Keystore</span>
|
||||
<span className="text-xs text-muted-foreground text-center">
|
||||
Use existing .p12 or .pfx file
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('generate')}
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all",
|
||||
keySource === 'generate'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Plus className="h-6 w-6 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Generate New</span>
|
||||
<span className="text-xs text-muted-foreground text-center">
|
||||
Create a new signing key
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderSavedKeyForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Use Saved Key</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{savedKeyInfo && (
|
||||
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10">
|
||||
<Key className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{savedKeyInfo.commonName}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Expires {new Date(savedKeyInfo.expiresAt).getFullYear()}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleDeleteSavedKey}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="saved-key-password">Password</Label>
|
||||
<Input
|
||||
id="saved-key-password"
|
||||
type="password"
|
||||
value={savedKeyPassword}
|
||||
onChange={(e) => setSavedKeyPassword(e.target.value)}
|
||||
placeholder="Enter password to unlock key"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleLoadSavedKey}
|
||||
disabled={!savedKeyPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Unlock Key
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderUploadForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Upload className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Upload Keystore</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label>Keystore File (.p12 / .pfx)</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
value={uploadFile?.name || ''}
|
||||
placeholder="Select a keystore file..."
|
||||
readOnly
|
||||
className="flex-1"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".p12,.pfx,.jks,.keystore"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
PKCS#12 format (.p12 / .pfx). For JKS files, convert first using keytool.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="keystore-password">Keystore Password</Label>
|
||||
<Input
|
||||
id="keystore-password"
|
||||
type="password"
|
||||
value={uploadPassword}
|
||||
onChange={(e) => setUploadPassword(e.target.value)}
|
||||
placeholder="Enter keystore password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="save-upload-key"
|
||||
checked={saveKeyAfter}
|
||||
onCheckedChange={(checked) => setSaveKeyAfter(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="save-upload-key" className="text-sm font-normal cursor-pointer">
|
||||
Remember this key for future builds
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleImportKeystore}
|
||||
disabled={!uploadFile || !uploadPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Import Keystore
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderGenerateForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Generate New Key</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-name">Name (Common Name)</Label>
|
||||
<Input
|
||||
id="key-name"
|
||||
value={generateName}
|
||||
onChange={(e) => setGenerateName(e.target.value)}
|
||||
placeholder="My App"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-org">Organization (optional)</Label>
|
||||
<Input
|
||||
id="key-org"
|
||||
value={generateOrg}
|
||||
onChange={(e) => setGenerateOrg(e.target.value)}
|
||||
placeholder="My Company"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-password">Password</Label>
|
||||
<Input
|
||||
id="key-password"
|
||||
type="password"
|
||||
value={generatePassword}
|
||||
onChange={(e) => setGeneratePassword(e.target.value)}
|
||||
placeholder="Enter password (min 6 characters)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-confirm">Confirm Password</Label>
|
||||
<Input
|
||||
id="key-confirm"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="Confirm password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="save-generated-key"
|
||||
checked={saveKeyAfter}
|
||||
onCheckedChange={(checked) => setSaveKeyAfter(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="save-generated-key" className="text-sm font-normal cursor-pointer">
|
||||
Remember this key for future builds
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleGenerateKeystore}
|
||||
disabled={!generateName || !generatePassword || !confirmPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Generate Key
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderKeyReady = () => (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Signing key ready: <strong>{signingKey?.alias}</strong>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{keySource === 'generate' && (
|
||||
<Alert>
|
||||
<FileKey className="h-4 w-4" />
|
||||
<AlertDescription className="space-y-2">
|
||||
<p><strong>Important:</strong> Save your keystore file! You'll need it for future updates.</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownloadKeystore}
|
||||
className="mt-2"
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Download Keystore (.p12)
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setSigningKey(null);
|
||||
setKeySource(null);
|
||||
}}
|
||||
className="flex-1"
|
||||
>
|
||||
Change Key
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSign}
|
||||
disabled={status === 'loading-apk' || status === 'signing'}
|
||||
className="flex-1"
|
||||
>
|
||||
{status === 'loading-apk' || status === 'signing' ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Signing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Sign APK
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{progress && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{progress}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border p-4">
|
||||
{signingKey ? (
|
||||
renderKeyReady()
|
||||
) : keySource === 'saved' ? (
|
||||
renderSavedKeyForm()
|
||||
) : keySource === 'upload' ? (
|
||||
renderUploadForm()
|
||||
) : keySource === 'generate' ? (
|
||||
renderGenerateForm()
|
||||
) : (
|
||||
renderKeySourceSelection()
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud, Shield, Download, CheckCircle } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -15,7 +15,7 @@ import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import type { APKBuildType, PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
@@ -23,6 +23,8 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
|
||||
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
|
||||
import { APKBuilderDeployForm } from '@/components/deploy/APKBuilderDeployForm';
|
||||
import { APKSigner } from '@/components/deploy/APKSigner';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { DeployAdapter } from '@/lib/deploy/types';
|
||||
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
|
||||
@@ -31,6 +33,7 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
|
||||
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
||||
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
|
||||
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
|
||||
import { APKBuilderAdapter } from '@/lib/deploy/APKBuilderAdapter';
|
||||
|
||||
/**
|
||||
* Normalize a URL string to ensure it has a protocol
|
||||
@@ -101,6 +104,12 @@ interface DenoDeployFormData {
|
||||
projectName: string;
|
||||
}
|
||||
|
||||
interface APKBuilderFormData {
|
||||
appName: string;
|
||||
packageId: string;
|
||||
buildType: APKBuildType;
|
||||
}
|
||||
|
||||
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
|
||||
const { t } = useTranslation();
|
||||
const { settings } = useDeploySettings();
|
||||
@@ -114,6 +123,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||
const [signedApkBlob, setSignedApkBlob] = useState<Blob | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
|
||||
@@ -138,6 +148,11 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
|
||||
projectName: projectName || projectId,
|
||||
});
|
||||
const [apkBuilderForm, setApkBuilderForm] = useState<APKBuilderFormData>({
|
||||
appName: projectName || projectId,
|
||||
packageId: '',
|
||||
buildType: 'debug',
|
||||
});
|
||||
|
||||
// Load project settings when component mounts
|
||||
useEffect(() => {
|
||||
@@ -261,6 +276,30 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
projectName: denoDeployForm.projectName || undefined,
|
||||
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'apkbuilder') {
|
||||
const apkBuilderProvider = selectedProvider;
|
||||
if (!apkBuilderProvider.buildServerUrl) {
|
||||
throw new Error('APK Builder server URL is required');
|
||||
}
|
||||
if (!apkBuilderProvider.apiKey) {
|
||||
throw new Error('APK Builder API key is required');
|
||||
}
|
||||
if (!apkBuilderForm.appName) {
|
||||
throw new Error('App name is required');
|
||||
}
|
||||
if (!apkBuilderForm.packageId) {
|
||||
throw new Error('Package ID is required');
|
||||
}
|
||||
|
||||
adapter = new APKBuilderAdapter({
|
||||
fs,
|
||||
buildServerUrl: apkBuilderProvider.buildServerUrl,
|
||||
apiKey: apkBuilderProvider.apiKey,
|
||||
appName: apkBuilderForm.appName,
|
||||
packageId: apkBuilderForm.packageId,
|
||||
buildType: apkBuilderForm.buildType,
|
||||
corsProxy: apkBuilderProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else {
|
||||
throw new Error('Unknown provider type');
|
||||
}
|
||||
@@ -320,6 +359,16 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
projectName: denoDeployForm.projectName || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'apkbuilder') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'apkbuilder',
|
||||
url: result.url,
|
||||
data: {
|
||||
appName: apkBuilderForm.appName,
|
||||
packageId: apkBuilderForm.packageId,
|
||||
buildType: apkBuilderForm.buildType,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
setDeployResult(result);
|
||||
@@ -333,6 +382,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const handleClose = () => {
|
||||
setSelectedProviderId('');
|
||||
setDeployResult(null);
|
||||
setSignedApkBlob(null);
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
@@ -341,9 +391,27 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
setCloudflareForm({ projectName: projectName || projectId });
|
||||
setDenoDeployForm({ projectName: projectName || projectId });
|
||||
setApkBuilderForm({ appName: projectName || projectId, packageId: '', buildType: 'debug' });
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleSigningComplete = useCallback((blob: Blob) => {
|
||||
setSignedApkBlob(blob);
|
||||
}, []);
|
||||
|
||||
const handleDownloadSignedApk = useCallback(() => {
|
||||
if (!signedApkBlob) return;
|
||||
|
||||
const url = URL.createObjectURL(signedApkBlob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${apkBuilderForm.appName.replace(/[^a-zA-Z0-9]/g, '_')}_signed.apk`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}, [signedApkBlob, apkBuilderForm.appName]);
|
||||
|
||||
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
@@ -372,6 +440,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setDenoDeployForm({ projectName });
|
||||
}, []);
|
||||
|
||||
const handleApkBuilderConfigChange = useCallback((appName: string, packageId: string, buildType: APKBuildType) => {
|
||||
setApkBuilderForm({ appName, packageId, buildType });
|
||||
}, []);
|
||||
|
||||
const renderProviderFields = () => {
|
||||
if (!selectedProvider) return null;
|
||||
|
||||
@@ -477,6 +549,28 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'apkbuilder') {
|
||||
const apkBuilderProvider = selectedProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedAppName = savedConfig?.type === 'apkbuilder' ? savedConfig.data.appName : undefined;
|
||||
const savedPackageId = savedConfig?.type === 'apkbuilder' ? savedConfig.data.packageId : undefined;
|
||||
const savedBuildType = savedConfig?.type === 'apkbuilder' ? savedConfig.data.buildType : undefined;
|
||||
|
||||
return (
|
||||
<APKBuilderDeployForm
|
||||
buildServerUrl={apkBuilderProvider.buildServerUrl}
|
||||
apiKey={apkBuilderProvider.apiKey}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedAppName={savedAppName}
|
||||
savedPackageId={savedPackageId}
|
||||
savedBuildType={savedBuildType}
|
||||
onConfigChange={handleApkBuilderConfigChange}
|
||||
corsProxy={apkBuilderProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -491,36 +585,124 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
{deployResult ? (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Your project has been successfully deployed!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
{/* Release APK signing flow */}
|
||||
{selectedProvider?.type === 'apkbuilder' && apkBuilderForm.buildType === 'release' ? (
|
||||
<>
|
||||
{/* Step indicator */}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-medium">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
</div>
|
||||
<span className="text-muted-foreground line-through">Build</span>
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
<div className={cn(
|
||||
"flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium",
|
||||
signedApkBlob
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-primary text-primary-foreground"
|
||||
)}>
|
||||
{signedApkBlob ? <CheckCircle className="h-3 w-3" /> : '2'}
|
||||
</div>
|
||||
<span className={signedApkBlob ? "text-muted-foreground line-through" : "font-medium"}>Sign</span>
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
<div className={cn(
|
||||
"flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium",
|
||||
signedApkBlob
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted text-muted-foreground"
|
||||
)}>
|
||||
3
|
||||
</div>
|
||||
<span className={signedApkBlob ? "font-medium" : "text-muted-foreground"}>Download</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Deployed URL</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={deployResult.url}
|
||||
readOnly
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(deployResult.url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{signedApkBlob ? (
|
||||
/* Signing complete - show download */
|
||||
<>
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
APK signed successfully! Download your release-ready APK.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="rounded-lg border p-4 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="font-medium text-sm">{apkBuilderForm.appName}_signed.apk</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(signedApkBlob.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={handleDownloadSignedApk}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Download APK
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
/* Show signing UI */
|
||||
<>
|
||||
<Alert>
|
||||
<Shield className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Release APK built! Sign it with your keystore to install on devices.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<APKSigner
|
||||
unsignedApkUrl={deployResult.url}
|
||||
appName={apkBuilderForm.appName}
|
||||
onComplete={handleSigningComplete}
|
||||
onCancel={handleClose}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
/* Standard success UI for debug APK and other providers */
|
||||
<>
|
||||
<Alert>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{selectedProvider?.type === 'apkbuilder'
|
||||
? 'Your project has been successfully built!'
|
||||
: 'Your project has been successfully deployed!'}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{selectedProvider?.type === 'apkbuilder' ? 'Download URL' : 'Deployed URL'}</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={deployResult.url}
|
||||
readOnly
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(deployResult.url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
@@ -653,7 +835,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
|
||||
(selectedProvider.type === 'apkbuilder' && (!apkBuilderForm.appName || !apkBuilderForm.packageId))
|
||||
}
|
||||
className="w-full"
|
||||
>
|
||||
|
||||
@@ -50,7 +50,14 @@ export interface DenoDeployProvider extends BaseDeployProvider {
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
|
||||
export interface APKBuilderProvider extends BaseDeployProvider {
|
||||
type: 'apkbuilder';
|
||||
buildServerUrl: string;
|
||||
apiKey: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | APKBuilderProvider;
|
||||
|
||||
export interface DeploySettings {
|
||||
providers: DeployProvider[];
|
||||
|
||||
@@ -52,6 +52,16 @@ const denoDeployProjectConfigSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
const apkBuilderProjectConfigSchema = z.object({
|
||||
type: z.literal('apkbuilder'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
appName: z.string(),
|
||||
packageId: z.string(),
|
||||
buildType: z.enum(['debug', 'release']).optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
shakespeareProjectConfigSchema,
|
||||
nsiteProjectConfigSchema,
|
||||
@@ -59,6 +69,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
vercelProjectConfigSchema,
|
||||
cloudflareProjectConfigSchema,
|
||||
denoDeployProjectConfigSchema,
|
||||
apkBuilderProjectConfigSchema,
|
||||
]);
|
||||
|
||||
const projectDeploySettingsSchema = z.object({
|
||||
@@ -72,6 +83,7 @@ export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
|
||||
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
|
||||
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
|
||||
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
|
||||
export type APKBuilderProjectConfig = z.infer<typeof apkBuilderProjectConfigSchema>;
|
||||
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
|
||||
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './signing';
|
||||
export * from './keystore';
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Keystore persistence utilities
|
||||
* Saves/loads signing keys from localStorage
|
||||
*/
|
||||
import type { SigningKey } from './signing';
|
||||
import { importKeyFromPkcs12, exportKeyToPkcs12 } from './signing';
|
||||
|
||||
const STORAGE_KEY = 'shakespeare:apk-signing-key';
|
||||
|
||||
export interface StoredKeyInfo {
|
||||
alias: string;
|
||||
commonName: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
interface StoredKeyData {
|
||||
p12Base64: string;
|
||||
info: StoredKeyInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a signing key is saved in localStorage
|
||||
*/
|
||||
export function hasSavedKey(): boolean {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
return stored !== null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get info about the saved key without loading it
|
||||
*/
|
||||
export function getSavedKeyInfo(): StoredKeyInfo | null {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (!stored) return null;
|
||||
|
||||
const data: StoredKeyData = JSON.parse(stored);
|
||||
return data.info;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a saved signing key from localStorage
|
||||
* Requires the password to decrypt the PKCS#12 data
|
||||
*/
|
||||
export function loadSavedKey(password: string): SigningKey {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (!stored) {
|
||||
throw new Error('No saved signing key found');
|
||||
}
|
||||
|
||||
const data: StoredKeyData = JSON.parse(stored);
|
||||
const p12Buffer = Uint8Array.from(atob(data.p12Base64), c => c.charCodeAt(0));
|
||||
|
||||
return importKeyFromPkcs12(p12Buffer.buffer, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a signing key to localStorage
|
||||
* The key is stored as encrypted PKCS#12 data
|
||||
*/
|
||||
export function saveKey(key: SigningKey, password: string): void {
|
||||
const p12Data = exportKeyToPkcs12(key, password);
|
||||
const p12Base64 = btoa(String.fromCharCode(...p12Data));
|
||||
|
||||
// Extract certificate info
|
||||
const cert = key.certificate;
|
||||
const commonName = cert.subject.getField('CN')?.value || key.alias;
|
||||
|
||||
const data: StoredKeyData = {
|
||||
p12Base64,
|
||||
info: {
|
||||
alias: key.alias,
|
||||
commonName: typeof commonName === 'string' ? commonName : key.alias,
|
||||
createdAt: cert.validity.notBefore.toISOString(),
|
||||
expiresAt: cert.validity.notAfter.toISOString(),
|
||||
},
|
||||
};
|
||||
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the saved signing key from localStorage
|
||||
*/
|
||||
export function deleteSavedKey(): void {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
@@ -0,0 +1,905 @@
|
||||
/**
|
||||
* Browser-based APK signing utility
|
||||
* Implements JAR signing (v1) for Android APKs
|
||||
*/
|
||||
import JSZip from 'jszip';
|
||||
import forge from 'node-forge';
|
||||
|
||||
export interface SigningKey {
|
||||
privateKey: forge.pki.PrivateKey;
|
||||
certificate: forge.pki.Certificate;
|
||||
alias: string;
|
||||
}
|
||||
|
||||
export interface SigningOptions {
|
||||
key: SigningKey;
|
||||
apkData: ArrayBuffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zipalign implementation for 4-byte alignment
|
||||
* Aligns uncompressed entries to the specified boundary
|
||||
*/
|
||||
function zipalign(data: Uint8Array, alignment: number): Uint8Array {
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
|
||||
// Find End of Central Directory (EOCD)
|
||||
let eocdOffset = -1;
|
||||
for (let i = data.length - 22; i >= 0; i--) {
|
||||
if (view.getUint32(i, true) === 0x06054b50) {
|
||||
eocdOffset = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocdOffset === -1) throw new Error('Invalid ZIP: EOCD not found');
|
||||
|
||||
const cdOffset = view.getUint32(eocdOffset + 16, true);
|
||||
const _cdSize = view.getUint32(eocdOffset + 12, true);
|
||||
const entryCount = view.getUint16(eocdOffset + 10, true);
|
||||
|
||||
// Parse central directory to get file entries
|
||||
interface Entry {
|
||||
nameOffset: number;
|
||||
nameLength: number;
|
||||
extraLength: number;
|
||||
commentLength: number;
|
||||
compressionMethod: number;
|
||||
localHeaderOffset: number;
|
||||
compressedSize: number;
|
||||
uncompressedSize: number;
|
||||
}
|
||||
const entries: Entry[] = [];
|
||||
let pos = cdOffset;
|
||||
for (let i = 0; i < entryCount; i++) {
|
||||
if (view.getUint32(pos, true) !== 0x02014b50) throw new Error('Invalid central directory');
|
||||
const compressionMethod = view.getUint16(pos + 10, true);
|
||||
const compressedSize = view.getUint32(pos + 20, true);
|
||||
const uncompressedSize = view.getUint32(pos + 24, true);
|
||||
const nameLength = view.getUint16(pos + 28, true);
|
||||
const extraLength = view.getUint16(pos + 30, true);
|
||||
const commentLength = view.getUint16(pos + 32, true);
|
||||
const localHeaderOffset = view.getUint32(pos + 42, true);
|
||||
entries.push({
|
||||
nameOffset: pos + 46,
|
||||
nameLength,
|
||||
extraLength,
|
||||
commentLength,
|
||||
compressionMethod,
|
||||
localHeaderOffset,
|
||||
compressedSize,
|
||||
uncompressedSize,
|
||||
});
|
||||
pos += 46 + nameLength + extraLength + commentLength;
|
||||
}
|
||||
|
||||
// Calculate new offsets and padding needed
|
||||
interface AlignmentInfo {
|
||||
entry: Entry;
|
||||
localExtraLength: number;
|
||||
newOffset: number;
|
||||
paddingNeeded: number;
|
||||
name: string;
|
||||
}
|
||||
const alignmentInfos: AlignmentInfo[] = [];
|
||||
let currentOffset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const localPos = entry.localHeaderOffset;
|
||||
if (view.getUint32(localPos, true) !== 0x04034b50) throw new Error('Invalid local header');
|
||||
|
||||
const localNameLength = view.getUint16(localPos + 26, true);
|
||||
const localExtraLength = view.getUint16(localPos + 28, true);
|
||||
const _headerSize = 30 + localNameLength + localExtraLength;
|
||||
const _dataOffset = localPos + _headerSize;
|
||||
|
||||
const nameBytes = data.slice(localPos + 30, localPos + 30 + localNameLength);
|
||||
const name = new TextDecoder().decode(nameBytes);
|
||||
|
||||
// Only align uncompressed files (compression method 0 = STORE)
|
||||
let paddingNeeded = 0;
|
||||
if (entry.compressionMethod === 0 && entry.uncompressedSize > 0) {
|
||||
const newDataOffset = currentOffset + 30 + localNameLength + localExtraLength;
|
||||
const misalignment = newDataOffset % alignment;
|
||||
if (misalignment !== 0) {
|
||||
paddingNeeded = alignment - misalignment;
|
||||
}
|
||||
}
|
||||
|
||||
alignmentInfos.push({
|
||||
entry,
|
||||
localExtraLength,
|
||||
newOffset: currentOffset,
|
||||
paddingNeeded,
|
||||
name,
|
||||
});
|
||||
|
||||
currentOffset += 30 + localNameLength + localExtraLength + paddingNeeded + entry.compressedSize;
|
||||
}
|
||||
|
||||
// Calculate new central directory offset
|
||||
const _newCdOffset = currentOffset;
|
||||
|
||||
// Build new ZIP
|
||||
const cdEntrySize = pos - cdOffset; // Total size of central directory entries
|
||||
const newSize = currentOffset + cdEntrySize + 22;
|
||||
const result = new Uint8Array(newSize);
|
||||
const resultView = new DataView(result.buffer);
|
||||
|
||||
let writePos = 0;
|
||||
|
||||
// Write local file headers and data
|
||||
for (const info of alignmentInfos) {
|
||||
const entry = info.entry;
|
||||
const oldLocalPos = entry.localHeaderOffset;
|
||||
const oldNameLength = view.getUint16(oldLocalPos + 26, true);
|
||||
const oldExtraLength = view.getUint16(oldLocalPos + 28, true);
|
||||
const oldHeaderSize = 30 + oldNameLength + oldExtraLength;
|
||||
|
||||
// Copy local file header
|
||||
result.set(data.slice(oldLocalPos, oldLocalPos + 30), writePos);
|
||||
|
||||
// Update extra field length to include padding
|
||||
const newExtraLength = oldExtraLength + info.paddingNeeded;
|
||||
resultView.setUint16(writePos + 28, newExtraLength, true);
|
||||
|
||||
// Copy filename
|
||||
result.set(data.slice(oldLocalPos + 30, oldLocalPos + 30 + oldNameLength), writePos + 30);
|
||||
|
||||
// Copy original extra field
|
||||
if (oldExtraLength > 0) {
|
||||
result.set(
|
||||
data.slice(oldLocalPos + 30 + oldNameLength, oldLocalPos + 30 + oldNameLength + oldExtraLength),
|
||||
writePos + 30 + oldNameLength
|
||||
);
|
||||
}
|
||||
|
||||
// Padding is implicitly zero-filled (Uint8Array is initialized to 0)
|
||||
|
||||
writePos += 30 + oldNameLength + newExtraLength;
|
||||
|
||||
// Copy file data
|
||||
const dataStart = oldLocalPos + oldHeaderSize;
|
||||
result.set(data.slice(dataStart, dataStart + entry.compressedSize), writePos);
|
||||
writePos += entry.compressedSize;
|
||||
}
|
||||
|
||||
// Write central directory
|
||||
const newCdStart = writePos;
|
||||
for (let i = 0; i < alignmentInfos.length; i++) {
|
||||
const info = alignmentInfos[i];
|
||||
const entry = info.entry;
|
||||
|
||||
// Find this entry in original central directory
|
||||
let oldCdPos = cdOffset;
|
||||
for (let j = 0; j < i; j++) {
|
||||
const e = entries[j];
|
||||
oldCdPos += 46 + e.nameLength + e.extraLength + e.commentLength;
|
||||
}
|
||||
|
||||
const cdEntryLength = 46 + entry.nameLength + entry.extraLength + entry.commentLength;
|
||||
|
||||
// Copy central directory entry
|
||||
result.set(data.slice(oldCdPos, oldCdPos + cdEntryLength), writePos);
|
||||
|
||||
// Update local header offset
|
||||
resultView.setUint32(writePos + 42, info.newOffset, true);
|
||||
|
||||
writePos += cdEntryLength;
|
||||
}
|
||||
|
||||
// Write EOCD
|
||||
result.set(data.slice(eocdOffset, eocdOffset + 22), writePos);
|
||||
// Update central directory offset
|
||||
resultView.setUint32(writePos + 16, newCdStart, true);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* APK Signature Scheme v2 implementation
|
||||
* Inserts a signing block between ZIP content and Central Directory
|
||||
*/
|
||||
function applyV2Signature(apk: Uint8Array, key: SigningKey): Uint8Array {
|
||||
const view = new DataView(apk.buffer, apk.byteOffset, apk.byteLength);
|
||||
|
||||
// Find EOCD
|
||||
let eocdOffset = -1;
|
||||
for (let i = apk.length - 22; i >= 0; i--) {
|
||||
if (view.getUint32(i, true) === 0x06054b50) {
|
||||
eocdOffset = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocdOffset === -1) throw new Error('Invalid ZIP: EOCD not found');
|
||||
|
||||
const cdOffset = view.getUint32(eocdOffset + 16, true);
|
||||
const _cdSize = view.getUint32(eocdOffset + 12, true);
|
||||
|
||||
// Section 1: ZIP entries (before CD)
|
||||
const zipEntries = apk.slice(0, cdOffset);
|
||||
// Section 3: Central Directory
|
||||
const centralDir = apk.slice(cdOffset, eocdOffset);
|
||||
// Section 4: EOCD
|
||||
const eocd = apk.slice(eocdOffset);
|
||||
|
||||
// Calculate content digests using 1MB chunks
|
||||
const CHUNK_SIZE = 1024 * 1024;
|
||||
const digests: Uint8Array[] = [];
|
||||
|
||||
// Helper to compute SHA256
|
||||
const sha256 = (data: Uint8Array): Uint8Array => {
|
||||
const md = forge.md.sha256.create();
|
||||
const len = data.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(data[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
return new Uint8Array(forge.util.binary.raw.decode(md.digest().getBytes()));
|
||||
};
|
||||
|
||||
// Digest section 1 (ZIP entries)
|
||||
for (let offset = 0; offset < zipEntries.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, zipEntries.length);
|
||||
const chunk = zipEntries.slice(offset, chunkEnd);
|
||||
// Chunk format: 0xa5 + 4-byte little-endian length + data
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Digest section 3 (Central Directory)
|
||||
for (let offset = 0; offset < centralDir.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, centralDir.length);
|
||||
const chunk = centralDir.slice(offset, chunkEnd);
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Pre-calculate signing block size to compute modified EOCD
|
||||
// The signing block size depends on: certificate size, signature size (256 for RSA-2048), public key size
|
||||
// We'll compute the actual size after building the blocks, but for now estimate
|
||||
// Actually, we need to include EOCD with modified offset in the digest
|
||||
// So we need to know the final signing block size first
|
||||
|
||||
// For RSA-2048: signature is 256 bytes
|
||||
// We'll calculate the exact size by building the structure first without the actual signature
|
||||
const certDerForSize = getCertificateDer(key.certificate);
|
||||
const pubKeyDerForSize = getPublicKeyDer(key.certificate);
|
||||
|
||||
// Calculate signing block size components:
|
||||
// digestsBlock: 4 (seq) + 4 (entry) + 4 (algo) + 4 (digest_len) + 32 (digest) = 48
|
||||
// certsBlock: 4 + 4 + certDer.length
|
||||
// attrsBlock: 4
|
||||
// signedData: 4 + digestsBlock + certsBlock + attrsBlock
|
||||
// sigsBlock: 4 (seq) + 4 (entry) + 4 (algo) + 4 (sig_len) + 256 (sig) = 272 (RSA-2048)
|
||||
// pubKeyBlock: 4 + pubKeyDer.length
|
||||
// signerBlock: 4 + signedData + sigsBlock + pubKeyBlock
|
||||
// signersBlock: 4 + signerBlock
|
||||
// v2Block: 8 (pair_size) + 4 (id) + signersBlock
|
||||
// signingBlock: 8 + v2Block + 8 + 16
|
||||
const digestsBlockSize = 4 + 4 + 4 + 4 + 32; // 48
|
||||
const certsBlockSize = 4 + 4 + certDerForSize.length;
|
||||
const attrsBlockSize = 4;
|
||||
const signedDataSize = 4 + digestsBlockSize + certsBlockSize + attrsBlockSize;
|
||||
const sigsBlockSize = 4 + 4 + 4 + 4 + 256; // 272 for RSA-2048 signature
|
||||
const pubKeyBlockSize = 4 + pubKeyDerForSize.length;
|
||||
const signerBlockSize = 4 + signedDataSize + sigsBlockSize + pubKeyBlockSize;
|
||||
const signersBlockSize = 4 + signerBlockSize;
|
||||
const v2BlockSize = 8 + 4 + signersBlockSize; // uint64 pair_size + uint32 ID + value
|
||||
const signingBlockTotalSize = 8 + v2BlockSize + 8 + 16;
|
||||
|
||||
// For digest computation, EOCD's offset is treated as pointing to signing block start
|
||||
// (which is the original cdOffset, where we'll insert the signing block)
|
||||
// The actual file's EOCD will point to real CD, but digest uses signing block offset
|
||||
const eocdForDigest = new Uint8Array(eocd);
|
||||
// cdOffset is where signing block will be inserted, so EOCD offset = cdOffset for digest
|
||||
new DataView(eocdForDigest.buffer).setUint32(16, cdOffset, true);
|
||||
|
||||
// Digest section 4 (EOCD with modified CD offset)
|
||||
for (let offset = 0; offset < eocdForDigest.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, eocdForDigest.length);
|
||||
const chunk = eocdForDigest.slice(offset, chunkEnd);
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Combine chunk digests into content digest
|
||||
// Format: 0x5a + 4-byte count + all digests concatenated
|
||||
const digestData = new Uint8Array(5 + digests.length * 32);
|
||||
digestData[0] = 0x5a;
|
||||
new DataView(digestData.buffer).setUint32(1, digests.length, true);
|
||||
for (let i = 0; i < digests.length; i++) {
|
||||
digestData.set(digests[i], 5 + i * 32);
|
||||
}
|
||||
const contentDigest = sha256(digestData);
|
||||
|
||||
// Build signed data
|
||||
// Structure: sequence of length-prefixed digests, certificates, and additional attributes
|
||||
const certDer = getCertificateDer(key.certificate);
|
||||
|
||||
// Digests: length-prefixed sequence of length-prefixed (algorithmId, digest) pairs
|
||||
// Algorithm ID: 0x0103 = RSASSA-PKCS1-v1_5 with SHA-256
|
||||
// Structure: sequence_length + [entry_length + algorithm_id + digest_length + digest]
|
||||
const digestEntrySize = 4 + 4 + 32; // algorithm_id + digest_length + digest
|
||||
const digestsBlock = new Uint8Array(4 + 4 + digestEntrySize);
|
||||
let dPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 4 + digestEntrySize, true);
|
||||
dPos += 4;
|
||||
// Entry length
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, digestEntrySize, true);
|
||||
dPos += 4;
|
||||
// Algorithm ID
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 0x0103, true);
|
||||
dPos += 4;
|
||||
// Digest length
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 32, true);
|
||||
dPos += 4;
|
||||
// Digest
|
||||
digestsBlock.set(contentDigest, dPos);
|
||||
|
||||
// Certificates: length-prefixed sequence of DER-encoded certificates
|
||||
const certsBlock = new Uint8Array(4 + 4 + certDer.length);
|
||||
let cPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(certsBlock.buffer).setUint32(cPos, 4 + certDer.length, true);
|
||||
cPos += 4;
|
||||
// Certificate length
|
||||
new DataView(certsBlock.buffer).setUint32(cPos, certDer.length, true);
|
||||
cPos += 4;
|
||||
// Certificate
|
||||
certsBlock.set(certDer, cPos);
|
||||
|
||||
// Additional attributes (empty for now)
|
||||
const attrsBlock = new Uint8Array(4);
|
||||
new DataView(attrsBlock.buffer).setUint32(0, 0, true);
|
||||
|
||||
// Combine into signed data content (without length prefix - that's added separately)
|
||||
const signedDataContent = new Uint8Array(digestsBlock.length + certsBlock.length + attrsBlock.length);
|
||||
let sdPos = 0;
|
||||
signedDataContent.set(digestsBlock, sdPos);
|
||||
sdPos += digestsBlock.length;
|
||||
signedDataContent.set(certsBlock, sdPos);
|
||||
sdPos += certsBlock.length;
|
||||
signedDataContent.set(attrsBlock, sdPos);
|
||||
|
||||
// Sign the signed data content (RSA-PKCS1-v1_5 with SHA-256)
|
||||
// The signing algorithm hashes internally, so we feed it the raw content
|
||||
const md = forge.md.sha256.create();
|
||||
// Convert to string in chunks to avoid stack overflow
|
||||
const len = signedDataContent.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(signedDataContent[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
const rsaPrivateKey = key.privateKey as unknown as forge.pki.rsa.PrivateKey;
|
||||
const signature = rsaPrivateKey.sign(md);
|
||||
const signatureBytes = new Uint8Array(forge.util.binary.raw.decode(signature));
|
||||
|
||||
// Create length-prefixed signed data for the signer block
|
||||
const signedData = new Uint8Array(4 + signedDataContent.length);
|
||||
new DataView(signedData.buffer).setUint32(0, signedDataContent.length, true);
|
||||
signedData.set(signedDataContent, 4);
|
||||
|
||||
// Build signatures block
|
||||
// Structure: sequence_length + [entry_length + algorithm_id + signature_length + signature]
|
||||
const sigEntrySize = 4 + 4 + signatureBytes.length; // algorithm_id + sig_length + signature
|
||||
const sigsBlock = new Uint8Array(4 + 4 + sigEntrySize);
|
||||
let sPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, 4 + sigEntrySize, true);
|
||||
sPos += 4;
|
||||
// Entry length
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, sigEntrySize, true);
|
||||
sPos += 4;
|
||||
// Algorithm ID
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, 0x0103, true);
|
||||
sPos += 4;
|
||||
// Signature length
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, signatureBytes.length, true);
|
||||
sPos += 4;
|
||||
// Signature
|
||||
sigsBlock.set(signatureBytes, sPos);
|
||||
|
||||
// Get public key DER
|
||||
const pubKeyDer = getPublicKeyDer(key.certificate);
|
||||
const pubKeyBlock = new Uint8Array(4 + pubKeyDer.length);
|
||||
new DataView(pubKeyBlock.buffer).setUint32(0, pubKeyDer.length, true);
|
||||
pubKeyBlock.set(pubKeyDer, 4);
|
||||
|
||||
// Build signer block
|
||||
const signerBlock = new Uint8Array(4 + signedData.length + sigsBlock.length + pubKeyBlock.length);
|
||||
let signerPos = 0;
|
||||
// Length prefix
|
||||
new DataView(signerBlock.buffer).setUint32(signerPos, signedData.length + sigsBlock.length + pubKeyBlock.length, true);
|
||||
signerPos += 4;
|
||||
signerBlock.set(signedData, signerPos);
|
||||
signerPos += signedData.length;
|
||||
signerBlock.set(sigsBlock, signerPos);
|
||||
signerPos += sigsBlock.length;
|
||||
signerBlock.set(pubKeyBlock, signerPos);
|
||||
|
||||
// Build signers sequence (just one signer)
|
||||
const signersBlock = new Uint8Array(4 + signerBlock.length);
|
||||
new DataView(signersBlock.buffer).setUint32(0, signerBlock.length, true);
|
||||
signersBlock.set(signerBlock, 4);
|
||||
|
||||
// Build v2 signature block (ID 0x7109871a)
|
||||
// Format: uint64 pair_size + uint32 ID + value
|
||||
const v2Block = new Uint8Array(8 + 4 + signersBlock.length);
|
||||
// Pair size (uint64): ID (4 bytes) + value
|
||||
new DataView(v2Block.buffer).setBigUint64(0, BigInt(4 + signersBlock.length), true);
|
||||
// ID (uint32)
|
||||
new DataView(v2Block.buffer).setUint32(8, 0x7109871a, true);
|
||||
// Value (signers)
|
||||
v2Block.set(signersBlock, 12);
|
||||
|
||||
// Build APK Signing Block
|
||||
// Structure: 8-byte size + pairs + 8-byte size + 16-byte magic
|
||||
const MAGIC = new Uint8Array([
|
||||
0x41, 0x50, 0x4b, 0x20, 0x53, 0x69, 0x67, 0x20,
|
||||
0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x34, 0x32,
|
||||
]); // "APK Sig Block 42"
|
||||
|
||||
const pairsSize = v2Block.length;
|
||||
const blockSize = pairsSize + 8 + 16; // pairs + second size + magic
|
||||
const signingBlock = new Uint8Array(8 + blockSize);
|
||||
let sbPos = 0;
|
||||
// First size
|
||||
new DataView(signingBlock.buffer).setBigUint64(sbPos, BigInt(blockSize), true);
|
||||
sbPos += 8;
|
||||
// Pairs (v2 block)
|
||||
signingBlock.set(v2Block, sbPos);
|
||||
sbPos += v2Block.length;
|
||||
// Second size
|
||||
new DataView(signingBlock.buffer).setBigUint64(sbPos, BigInt(blockSize), true);
|
||||
sbPos += 8;
|
||||
// Magic
|
||||
signingBlock.set(MAGIC, sbPos);
|
||||
|
||||
// Verify size calculation matches actual size
|
||||
if (signingBlockTotalSize !== signingBlock.length) {
|
||||
throw new Error('V2 signing block size mismatch - digest will be invalid');
|
||||
}
|
||||
|
||||
// Update EOCD with new CD offset (after signing block)
|
||||
const newEocd = new Uint8Array(eocd);
|
||||
new DataView(newEocd.buffer).setUint32(16, cdOffset + signingBlock.length, true);
|
||||
|
||||
// Build final APK
|
||||
const result = new Uint8Array(zipEntries.length + signingBlock.length + centralDir.length + newEocd.length);
|
||||
let rPos = 0;
|
||||
result.set(zipEntries, rPos);
|
||||
rPos += zipEntries.length;
|
||||
result.set(signingBlock, rPos);
|
||||
rPos += signingBlock.length;
|
||||
result.set(centralDir, rPos);
|
||||
rPos += centralDir.length;
|
||||
result.set(newEocd, rPos);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate as DER bytes
|
||||
*/
|
||||
function getCertificateDer(cert: forge.pki.Certificate): Uint8Array {
|
||||
const pem = forge.pki.certificateToPem(cert);
|
||||
const base64 = pem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
const der = forge.util.decode64(base64);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get public key as DER bytes (SubjectPublicKeyInfo)
|
||||
*/
|
||||
function getPublicKeyDer(cert: forge.pki.Certificate): Uint8Array {
|
||||
const pem = forge.pki.publicKeyToPem(cert.publicKey);
|
||||
const base64 = pem
|
||||
.replace(/-----BEGIN PUBLIC KEY-----/, '')
|
||||
.replace(/-----END PUBLIC KEY-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
const der = forge.util.decode64(base64);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign an APK using JAR signing (v1 signature scheme)
|
||||
* This creates META-INF/MANIFEST.MF, META-INF/CERT.SF, and META-INF/CERT.RSA
|
||||
*/
|
||||
export async function signApk(options: SigningOptions): Promise<Blob> {
|
||||
const { key, apkData } = options;
|
||||
|
||||
// Load the APK (ZIP file)
|
||||
const zip = await JSZip.loadAsync(apkData);
|
||||
|
||||
// Remove any existing signatures
|
||||
zip.remove('META-INF/MANIFEST.MF');
|
||||
zip.remove('META-INF/CERT.SF');
|
||||
zip.remove('META-INF/CERT.RSA');
|
||||
zip.remove('META-INF/CERT.DSA');
|
||||
zip.remove('META-INF/CERT.EC');
|
||||
|
||||
// Remove any other signature files
|
||||
const metaInfFiles = Object.keys(zip.files).filter(f =>
|
||||
f.startsWith('META-INF/') && (f.endsWith('.SF') || f.endsWith('.RSA') || f.endsWith('.DSA') || f.endsWith('.EC'))
|
||||
);
|
||||
for (const file of metaInfFiles) {
|
||||
zip.remove(file);
|
||||
}
|
||||
|
||||
// Create MANIFEST.MF
|
||||
const manifest = await createManifest(zip);
|
||||
zip.file('META-INF/MANIFEST.MF', manifest, { compression: 'DEFLATE' });
|
||||
|
||||
// Create CERT.SF (signature file)
|
||||
const signatureFile = createSignatureFile(manifest);
|
||||
zip.file('META-INF/CERT.SF', signatureFile, { compression: 'DEFLATE' });
|
||||
|
||||
// Create CERT.RSA (PKCS#7 signature block)
|
||||
const signatureBlock = createSignatureBlock(signatureFile, key);
|
||||
zip.file('META-INF/CERT.RSA', signatureBlock, { compression: 'DEFLATE' });
|
||||
|
||||
// Generate the signed APK
|
||||
// Don't use global compression - preserve original compression settings
|
||||
// This is critical for resources.arsc which must be STORE (uncompressed) on Android 11+
|
||||
const signedApkRaw = await zip.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
// Use per-file compression to preserve original settings
|
||||
// resources.arsc and .so files must stay uncompressed
|
||||
});
|
||||
|
||||
// Apply zipalign to ensure 4-byte alignment for uncompressed files
|
||||
// This is required for Android 11+ (API 30+)
|
||||
const alignedApk = zipalign(new Uint8Array(signedApkRaw), 4);
|
||||
|
||||
// Apply APK Signature Scheme v2
|
||||
// This is required for Android 7.0+ and mandatory for Android 11+
|
||||
const v2SignedApk = applyV2Signature(alignedApk, key);
|
||||
|
||||
return new Blob([v2SignedApk], { type: 'application/vnd.android.package-archive' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Create MANIFEST.MF with SHA-256 digests of all files
|
||||
*/
|
||||
async function createManifest(zip: JSZip): Promise<string> {
|
||||
const lines: string[] = [
|
||||
'Manifest-Version: 1.0',
|
||||
'Created-By: Shakespeare APK Signer',
|
||||
'',
|
||||
];
|
||||
|
||||
// Get all files (excluding META-INF directory)
|
||||
const files = Object.keys(zip.files)
|
||||
.filter(name => !zip.files[name].dir && !name.startsWith('META-INF/'))
|
||||
.sort();
|
||||
|
||||
for (const fileName of files) {
|
||||
const file = zip.files[fileName];
|
||||
const content = await file.async('uint8array');
|
||||
const digest = sha256Base64(content);
|
||||
|
||||
lines.push(`Name: ${fileName}`);
|
||||
lines.push(`SHA-256-Digest: ${digest}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create CERT.SF (signature file) with digests of manifest sections
|
||||
*/
|
||||
function createSignatureFile(manifest: string): string {
|
||||
const lines: string[] = [
|
||||
'Signature-Version: 1.0',
|
||||
'Created-By: Shakespeare APK Signer',
|
||||
`SHA-256-Digest-Manifest: ${sha256Base64(new TextEncoder().encode(manifest))}`,
|
||||
'',
|
||||
];
|
||||
|
||||
// Parse manifest sections and create digests for each
|
||||
const sections = manifest.split('\r\n\r\n');
|
||||
|
||||
for (let i = 1; i < sections.length; i++) {
|
||||
const section = sections[i];
|
||||
if (!section.trim()) continue;
|
||||
|
||||
// Extract the Name attribute
|
||||
const nameMatch = section.match(/^Name: (.+)$/m);
|
||||
if (nameMatch) {
|
||||
const sectionWithNewline = section + '\r\n\r\n';
|
||||
const digest = sha256Base64(new TextEncoder().encode(sectionWithNewline));
|
||||
|
||||
lines.push(`Name: ${nameMatch[1]}`);
|
||||
lines.push(`SHA-256-Digest: ${digest}`);
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create CERT.RSA (PKCS#7 signature block)
|
||||
*/
|
||||
function createSignatureBlock(signatureFile: string, key: SigningKey): Uint8Array {
|
||||
const { privateKey, certificate } = key;
|
||||
|
||||
// Create SHA-256 digest of the signature file
|
||||
const md = forge.md.sha256.create();
|
||||
md.update(signatureFile, 'utf8');
|
||||
|
||||
// Sign the digest directly with RSA
|
||||
// Type assertion needed due to node-forge type definition issues
|
||||
const rsaPrivateKey = privateKey as unknown as forge.pki.rsa.PrivateKey;
|
||||
const signature = rsaPrivateKey.sign(md);
|
||||
|
||||
// Build PKCS#7 SignedData structure manually
|
||||
// This avoids the recursion issues in forge.pkcs7
|
||||
// Use PEM->DER conversion to avoid certificateToAsn1 recursion issues
|
||||
const certPem = forge.pki.certificateToPem(certificate);
|
||||
|
||||
const certDerBase64 = certPem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
|
||||
const certDer = forge.util.decode64(certDerBase64);
|
||||
|
||||
const certAsn1 = forge.asn1.fromDer(certDer);
|
||||
|
||||
// Build issuer DN ASN.1
|
||||
let issuerAsn1;
|
||||
if (certificate.issuer.attributes.length > 0) {
|
||||
issuerAsn1 = forge.pki.distinguishedNameToAsn1(certificate.issuer);
|
||||
} else {
|
||||
issuerAsn1 = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, []);
|
||||
}
|
||||
|
||||
const signerInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// version
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.asn1.integerToDer(1).getBytes()),
|
||||
// issuerAndSerialNumber
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// issuer
|
||||
issuerAsn1,
|
||||
// serialNumber
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.util.hexToBytes(certificate.serialNumber)),
|
||||
]),
|
||||
// digestAlgorithm (SHA-256)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
// digestEncryptionAlgorithm (RSA)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.1.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
// encryptedDigest (the signature)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OCTETSTRING, false, signature),
|
||||
]);
|
||||
|
||||
const signedData = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// version
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.asn1.integerToDer(1).getBytes()),
|
||||
// digestAlgorithms
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
]),
|
||||
// contentInfo (empty for detached signature)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.7.1').getBytes()),
|
||||
]),
|
||||
// certificates (implicit tag 0)
|
||||
forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [certAsn1]),
|
||||
// signerInfos
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [signerInfo]),
|
||||
]);
|
||||
|
||||
// Wrap in ContentInfo
|
||||
const contentInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// contentType (signedData)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.7.2').getBytes()),
|
||||
// content
|
||||
forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [signedData]),
|
||||
]);
|
||||
|
||||
const der = forge.asn1.toDer(contentInfo);
|
||||
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate SHA-256 hash and return as base64
|
||||
*/
|
||||
function sha256Base64(data: Uint8Array): string {
|
||||
const md = forge.md.sha256.create();
|
||||
// forge.util.binary.raw.encode uses String.fromCharCode.apply which causes
|
||||
// stack overflow for large arrays. Build string manually.
|
||||
const len = data.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(data[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
const digest = md.digest();
|
||||
return forge.util.encode64(digest.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new signing key pair and self-signed certificate
|
||||
*/
|
||||
export function generateSigningKey(options: {
|
||||
commonName: string;
|
||||
organizationName?: string;
|
||||
countryCode?: string;
|
||||
validityYears?: number;
|
||||
alias?: string;
|
||||
}): SigningKey {
|
||||
const {
|
||||
commonName,
|
||||
organizationName = 'Shakespeare',
|
||||
countryCode = 'US',
|
||||
validityYears = 25,
|
||||
alias = 'key0',
|
||||
} = options;
|
||||
|
||||
// Generate RSA key pair
|
||||
const keys = forge.pki.rsa.generateKeyPair(2048);
|
||||
|
||||
// Create certificate
|
||||
const cert = forge.pki.createCertificate();
|
||||
cert.publicKey = keys.publicKey;
|
||||
cert.serialNumber = '01' + forge.util.bytesToHex(forge.random.getBytesSync(8));
|
||||
|
||||
// Set validity
|
||||
cert.validity.notBefore = new Date();
|
||||
cert.validity.notAfter = new Date();
|
||||
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + validityYears);
|
||||
|
||||
// Set subject/issuer attributes
|
||||
const attrs = [
|
||||
{ name: 'commonName', value: commonName },
|
||||
{ name: 'organizationName', value: organizationName },
|
||||
{ name: 'countryName', value: countryCode },
|
||||
];
|
||||
cert.setSubject(attrs);
|
||||
cert.setIssuer(attrs);
|
||||
|
||||
// Set extensions
|
||||
cert.setExtensions([
|
||||
{
|
||||
name: 'basicConstraints',
|
||||
cA: false,
|
||||
},
|
||||
{
|
||||
name: 'keyUsage',
|
||||
digitalSignature: true,
|
||||
keyEncipherment: true,
|
||||
},
|
||||
{
|
||||
name: 'extKeyUsage',
|
||||
codeSigning: true,
|
||||
},
|
||||
]);
|
||||
|
||||
// Self-sign the certificate
|
||||
cert.sign(keys.privateKey, forge.md.sha256.create());
|
||||
|
||||
return {
|
||||
privateKey: keys.privateKey,
|
||||
certificate: cert,
|
||||
alias,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Export signing key to PKCS#12 format (.p12)
|
||||
*/
|
||||
export function exportKeyToPkcs12(key: SigningKey, password: string): Uint8Array {
|
||||
// Type assertion needed due to node-forge type definition issues
|
||||
const p12Asn1 = forge.pkcs12.toPkcs12Asn1(
|
||||
key.privateKey as unknown as Parameters<typeof forge.pkcs12.toPkcs12Asn1>[0],
|
||||
[key.certificate],
|
||||
password,
|
||||
{
|
||||
friendlyName: key.alias,
|
||||
algorithm: '3des', // Use 3DES for compatibility
|
||||
}
|
||||
);
|
||||
|
||||
const p12Der = forge.asn1.toDer(p12Asn1);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(p12Der.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Import signing key from PKCS#12 format (.p12 / .pfx)
|
||||
*/
|
||||
export function importKeyFromPkcs12(data: ArrayBuffer, password: string): SigningKey {
|
||||
const p12Der = forge.util.binary.raw.encode(new Uint8Array(data));
|
||||
const p12Asn1 = forge.asn1.fromDer(p12Der);
|
||||
const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, password);
|
||||
|
||||
// Find the private key and certificate
|
||||
let privateKey: forge.pki.PrivateKey | null = null;
|
||||
let certificate: forge.pki.Certificate | null = null;
|
||||
let alias = 'key0';
|
||||
|
||||
for (const safeContents of p12.safeContents) {
|
||||
for (const safeBag of safeContents.safeBags) {
|
||||
if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag && safeBag.key) {
|
||||
privateKey = safeBag.key;
|
||||
if (safeBag.attributes?.friendlyName?.[0]) {
|
||||
alias = safeBag.attributes.friendlyName[0];
|
||||
}
|
||||
} else if (safeBag.type === forge.pki.oids.certBag && safeBag.cert) {
|
||||
certificate = safeBag.cert;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!privateKey || !certificate) {
|
||||
throw new Error('Could not find private key and certificate in PKCS#12 file');
|
||||
}
|
||||
|
||||
return { privateKey, certificate, alias };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if data is a JKS (Java KeyStore) file and throw helpful error
|
||||
* Note: JKS is a proprietary format. For best compatibility, convert to PKCS#12 first:
|
||||
* keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12
|
||||
*/
|
||||
export function checkJksAndThrow(data: ArrayBuffer): never {
|
||||
const view = new DataView(data);
|
||||
|
||||
// JKS magic number: 0xFEEDFEED
|
||||
const magic = view.getUint32(0, false);
|
||||
if (magic === 0xFEEDFEED) {
|
||||
throw new Error(
|
||||
'JKS format is not directly supported. Please convert to PKCS#12 format using:\n' +
|
||||
'keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12'
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error('Unknown keystore format. Please use PKCS#12 (.p12 / .pfx) format.');
|
||||
}
|
||||
@@ -129,6 +129,12 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
|
||||
baseDomain: z.string().optional(),
|
||||
});
|
||||
|
||||
const apkBuilderProviderSchema = baseDeployProviderSchema.extend({
|
||||
type: z.literal('apkbuilder'),
|
||||
buildServerUrl: z.string().url(),
|
||||
apiKey: z.string(),
|
||||
});
|
||||
|
||||
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
|
||||
shakespeareDeployProviderSchema,
|
||||
netlifyProviderSchema,
|
||||
@@ -136,6 +142,7 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
|
||||
nsiteProviderSchema,
|
||||
cloudflareProviderSchema,
|
||||
denoDeployProviderSchema,
|
||||
apkBuilderProviderSchema,
|
||||
]);
|
||||
|
||||
const deploySettingsSchema = z.object({
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import JSZip from 'jszip';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, APKBuilderDeployConfig, APKBuildType } from './types';
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
|
||||
interface APKBuildStatus {
|
||||
id: string;
|
||||
status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled';
|
||||
progress: number;
|
||||
error?: string;
|
||||
apkSize?: number;
|
||||
logs?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* APK Builder Deploy Adapter
|
||||
* Builds Android APKs from web projects using a Capacitor build service
|
||||
*/
|
||||
export class APKBuilderAdapter implements DeployAdapter {
|
||||
private fs: JSRuntimeFS;
|
||||
private buildServerUrl: string;
|
||||
private apiKey: string;
|
||||
private appName: string;
|
||||
private packageId: string;
|
||||
private buildType: APKBuildType;
|
||||
private corsProxy?: string;
|
||||
private onProgress?: (status: APKBuildStatus) => void;
|
||||
|
||||
constructor(config: APKBuilderDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
this.buildServerUrl = config.buildServerUrl.replace(/\/$/, '');
|
||||
this.apiKey = config.apiKey;
|
||||
this.appName = config.appName;
|
||||
this.packageId = config.packageId;
|
||||
this.buildType = config.buildType || 'debug';
|
||||
this.corsProxy = config.corsProxy;
|
||||
this.onProgress = config.onProgress;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectPath } = options;
|
||||
const distPath = `${projectPath}/dist`;
|
||||
|
||||
// Verify dist exists
|
||||
try {
|
||||
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
|
||||
} catch {
|
||||
throw new Error('No dist folder found. Build the project first using the Build button.');
|
||||
}
|
||||
|
||||
// Create ZIP of dist folder
|
||||
const zip = new JSZip();
|
||||
const distFolder = zip.folder('dist');
|
||||
if (!distFolder) {
|
||||
throw new Error('Failed to create ZIP folder');
|
||||
}
|
||||
await this.addDirectoryToZip(distPath, distFolder);
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Submit build request
|
||||
const buildId = await this.submitBuild(zipBlob);
|
||||
|
||||
// Poll for completion
|
||||
const result = await this.waitForBuild(buildId);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async submitBuild(zipBlob: Blob): Promise<string> {
|
||||
const url = `${this.buildServerUrl}/api/build`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('project', zipBlob, 'project.zip');
|
||||
formData.append('config', JSON.stringify({
|
||||
appName: this.appName,
|
||||
packageId: this.packageId,
|
||||
buildType: this.buildType,
|
||||
}));
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || `Build submission failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.buildId;
|
||||
}
|
||||
|
||||
private async waitForBuild(buildId: string): Promise<DeployResult> {
|
||||
const maxWait = 10 * 60 * 1000; // 10 minutes
|
||||
const pollInterval = 3000; // 3 seconds
|
||||
const startTime = Date.now();
|
||||
|
||||
while (Date.now() - startTime < maxWait) {
|
||||
const status = await this.getStatus(buildId);
|
||||
|
||||
if (this.onProgress) {
|
||||
this.onProgress(status);
|
||||
}
|
||||
|
||||
if (status.status === 'complete') {
|
||||
// Fetch APK with header auth and create blob URL
|
||||
const apkBlobUrl = await this.downloadApk(buildId);
|
||||
|
||||
return {
|
||||
url: apkBlobUrl,
|
||||
metadata: {
|
||||
buildId,
|
||||
type: 'apk',
|
||||
appName: this.appName,
|
||||
packageId: this.packageId,
|
||||
buildType: this.buildType,
|
||||
apkSize: status.apkSize,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (status.status === 'failed') {
|
||||
throw new Error(status.error || 'APK build failed');
|
||||
}
|
||||
|
||||
if (status.status === 'cancelled') {
|
||||
throw new Error('APK build was cancelled');
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
throw new Error('APK build timed out after 10 minutes');
|
||||
}
|
||||
|
||||
private async downloadApk(buildId: string): Promise<string> {
|
||||
const url = `${this.buildServerUrl}/api/build/${buildId}/download`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download APK: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
private async getStatus(buildId: string): Promise<APKBuildStatus> {
|
||||
const url = `${this.buildServerUrl}/api/build/${buildId}/status`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get build status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
|
||||
try {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
const folder = zip.folder(entry.name);
|
||||
if (folder) {
|
||||
await this.addDirectoryToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
try {
|
||||
const fileContent = await this.fs.readFile(fullPath);
|
||||
zip.file(entry.name, fileContent);
|
||||
} catch {
|
||||
console.warn(`Failed to read file ${fullPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
console.warn(`Failed to read directory ${dirPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,3 +5,4 @@ export * from './VercelAdapter';
|
||||
export * from './NsiteAdapter';
|
||||
export * from './CloudflareAdapter';
|
||||
export * from './DenoDeployAdapter';
|
||||
export * from './APKBuilderAdapter';
|
||||
+43
-1
@@ -75,9 +75,50 @@ export interface DenoDeployConfig {
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
/** Build type for APK */
|
||||
export type APKBuildType = 'debug' | 'release';
|
||||
|
||||
/** Keystore configuration for release builds */
|
||||
export interface KeystoreConfig {
|
||||
/** Keystore data as base64 */
|
||||
keystoreBase64: string;
|
||||
/** Keystore password */
|
||||
keystorePassword: string;
|
||||
/** Key alias */
|
||||
keyAlias: string;
|
||||
/** Key password */
|
||||
keyPassword: string;
|
||||
}
|
||||
|
||||
export interface APKBuilderDeployConfig {
|
||||
fs: JSRuntimeFS;
|
||||
/** URL of the APK build server */
|
||||
buildServerUrl: string;
|
||||
/** API key for the build server */
|
||||
apiKey: string;
|
||||
/** Display name of the Android app */
|
||||
appName: string;
|
||||
/** Android package ID (e.g., com.example.myapp) */
|
||||
packageId: string;
|
||||
/** Build type: debug (default) or release */
|
||||
buildType?: APKBuildType;
|
||||
/** Keystore configuration for release builds (browser-based signing) */
|
||||
keystoreConfig?: KeystoreConfig;
|
||||
/** Optional CORS proxy */
|
||||
corsProxy?: string;
|
||||
/** Optional progress callback */
|
||||
onProgress?: (status: {
|
||||
id: string;
|
||||
status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled';
|
||||
progress: number;
|
||||
error?: string;
|
||||
logs?: string[];
|
||||
}) => void;
|
||||
}
|
||||
|
||||
export interface PresetDeployProvider {
|
||||
id: string;
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder';
|
||||
name: string;
|
||||
description: string;
|
||||
baseURL?: string;
|
||||
@@ -88,5 +129,6 @@ export interface PresetDeployProvider {
|
||||
accountIdURL?: string;
|
||||
organizationIdLabel?: string;
|
||||
organizationIdURL?: string;
|
||||
buildServerUrlLabel?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
@@ -60,4 +60,14 @@ export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
|
||||
organizationIdURL: 'https://dash.deno.com/orgs',
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: 'apkbuilder',
|
||||
type: 'apkbuilder',
|
||||
name: 'APK Builder',
|
||||
description: 'Build Android APKs from your web app',
|
||||
baseURL: 'https://android.com',
|
||||
buildServerUrlLabel: 'Build Server URL',
|
||||
apiKeyLabel: 'API Key',
|
||||
proxy: true,
|
||||
},
|
||||
];
|
||||
+1
-1
@@ -1107,7 +1107,7 @@ class GitHttp implements HttpClient {
|
||||
|
||||
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
|
||||
this.proxy = proxy;
|
||||
this.fetch = fetch ?? globalThis.fetch;
|
||||
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
|
||||
}
|
||||
|
||||
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* NIP-98 HTTP Auth utilities
|
||||
* Creates signed events for HTTP authentication
|
||||
*/
|
||||
import type { NostrSigner, NostrEvent } from '@nostrify/nostrify';
|
||||
import { proxyUrl } from './proxyUrl';
|
||||
|
||||
/**
|
||||
* 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
|
||||
? proxyUrl(corsProxy, authUrl)
|
||||
: 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,
|
||||
};
|
||||
}
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
UnzipCommand,
|
||||
WcCommand,
|
||||
WhoamiCommand,
|
||||
WhichCommand
|
||||
WhichCommand,
|
||||
} from "../commands";
|
||||
|
||||
interface ShellToolParams {
|
||||
|
||||
@@ -181,7 +181,7 @@ export function DeploySettings() {
|
||||
setAddDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string) => {
|
||||
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => {
|
||||
// For Shakespeare, just check if user is logged in
|
||||
if (preset.requiresNostr && !user) {
|
||||
return;
|
||||
@@ -260,6 +260,18 @@ export function DeploySettings() {
|
||||
organizationId: organizationId.trim(),
|
||||
...(preset.proxy && { proxy: true }),
|
||||
};
|
||||
} else if (preset.type === 'apkbuilder') {
|
||||
if (!buildServerUrl?.trim() || !apiKey?.trim()) {
|
||||
return;
|
||||
}
|
||||
newProvider = {
|
||||
id: preset.id,
|
||||
name: preset.name,
|
||||
type: 'apkbuilder',
|
||||
buildServerUrl: buildServerUrl.trim(),
|
||||
apiKey: apiKey.trim(),
|
||||
...(preset.proxy && { proxy: true }),
|
||||
};
|
||||
} else {
|
||||
return; // Unknown type
|
||||
}
|
||||
@@ -278,6 +290,8 @@ export function DeploySettings() {
|
||||
|
||||
const handleRemoveProvider = (index: number) => {
|
||||
removeProvider(index);
|
||||
setDialogOpen(false);
|
||||
setSelectedProviderIndex(null);
|
||||
};
|
||||
|
||||
const handleUpdateProvider = (index: number, provider: DeployProvider) => {
|
||||
@@ -397,8 +411,8 @@ export function DeploySettings() {
|
||||
onSetForceManualEntry={(force) =>
|
||||
setForceManualEntry(prev => ({ ...prev, [selectedPreset.id]: force }))
|
||||
}
|
||||
onAdd={(apiKey, accountId, organizationId) =>
|
||||
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId)
|
||||
onAdd={(apiKey, accountId, organizationId, buildServerUrl) =>
|
||||
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId, buildServerUrl)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user