mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Add browser-based APK signing with v1 and v2 signature schemes
Implement complete APK signing in the browser using node-forge: - JAR signing (v1) with MANIFEST.MF, CERT.SF, and CERT.RSA - APK Signature Scheme v2 for Android 7.0+ compatibility - Zipalign for 4-byte alignment (required for Android 11+) - PKCS#12 keystore support for key import/export - Key generation and persistence in localStorage 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
This commit is contained in:
1 parent
4d8a3772b2
commit
d85b4d833e
11 files changed
+1919
-45
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",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { CheckCircle, XCircle, Loader2 } from 'lucide-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;
|
||||
@@ -12,7 +14,8 @@ interface APKBuilderDeployFormProps {
|
||||
projectName?: string;
|
||||
savedAppName?: string;
|
||||
savedPackageId?: string;
|
||||
onConfigChange: (appName: string, packageId: string) => void;
|
||||
savedBuildType?: APKBuildType;
|
||||
onConfigChange: (appName: string, packageId: string, buildType: APKBuildType) => void;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
@@ -32,11 +35,13 @@ export function APKBuilderDeployForm({
|
||||
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);
|
||||
@@ -104,9 +109,9 @@ export function APKBuilderDeployForm({
|
||||
// Notify parent of config changes
|
||||
useEffect(() => {
|
||||
if (appName && packageId && !packageIdError) {
|
||||
onConfigChange(appName, packageId);
|
||||
onConfigChange(appName, packageId, buildType);
|
||||
}
|
||||
}, [appName, packageId, packageIdError, onConfigChange]);
|
||||
}, [appName, packageId, packageIdError, buildType, onConfigChange]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -181,18 +186,77 @@ export function APKBuilderDeployForm({
|
||||
)}
|
||||
</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">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Build type:</strong> Debug APK (sideloading)
|
||||
</p>
|
||||
{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>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
App icon will be auto-detected from your project
|
||||
</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,6 +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 { APKBuildType } from '@/lib/deploy/types';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
@@ -22,6 +23,7 @@ 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';
|
||||
@@ -133,6 +135,7 @@ interface DenoDeployFormData {
|
||||
interface APKBuilderFormData {
|
||||
appName: string;
|
||||
packageId: string;
|
||||
buildType: APKBuildType;
|
||||
}
|
||||
|
||||
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
|
||||
@@ -148,6 +151,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);
|
||||
|
||||
@@ -175,6 +179,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const [apkBuilderForm, setApkBuilderForm] = useState<APKBuilderFormData>({
|
||||
appName: projectName || projectId,
|
||||
packageId: '',
|
||||
buildType: 'debug',
|
||||
});
|
||||
|
||||
// Load project settings when component mounts
|
||||
@@ -320,6 +325,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
apiKey: apkBuilderProvider.apiKey,
|
||||
appName: apkBuilderForm.appName,
|
||||
packageId: apkBuilderForm.packageId,
|
||||
buildType: apkBuilderForm.buildType,
|
||||
corsProxy: apkBuilderProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else {
|
||||
@@ -388,6 +394,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
data: {
|
||||
appName: apkBuilderForm.appName,
|
||||
packageId: apkBuilderForm.packageId,
|
||||
buildType: apkBuilderForm.buildType,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -403,6 +410,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const handleClose = () => {
|
||||
setSelectedProviderId('');
|
||||
setDeployResult(null);
|
||||
setSignedApkBlob(null);
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
@@ -411,10 +419,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: '' });
|
||||
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 });
|
||||
}, []);
|
||||
@@ -443,8 +468,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setDenoDeployForm({ projectName });
|
||||
}, []);
|
||||
|
||||
const handleApkBuilderConfigChange = useCallback((appName: string, packageId: string) => {
|
||||
setApkBuilderForm({ appName, packageId });
|
||||
const handleApkBuilderConfigChange = useCallback((appName: string, packageId: string, buildType: APKBuildType) => {
|
||||
setApkBuilderForm({ appName, packageId, buildType });
|
||||
}, []);
|
||||
|
||||
const renderProviderFields = () => {
|
||||
@@ -557,6 +582,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
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
|
||||
@@ -566,6 +592,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
projectName={projectName}
|
||||
savedAppName={savedAppName}
|
||||
savedPackageId={savedPackageId}
|
||||
savedBuildType={savedBuildType}
|
||||
onConfigChange={handleApkBuilderConfigChange}
|
||||
corsProxy={apkBuilderProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
@@ -586,38 +613,124 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
{deployResult ? (
|
||||
<div className="space-y-4">
|
||||
<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>
|
||||
{/* 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>{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>
|
||||
{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">
|
||||
|
||||
@@ -58,6 +58,7 @@ const apkBuilderProjectConfigSchema = z.object({
|
||||
data: z.object({
|
||||
appName: z.string(),
|
||||
packageId: z.string(),
|
||||
buildType: z.enum(['debug', 'release']).optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -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,958 @@
|
||||
/**
|
||||
* 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);
|
||||
const originalEocdOffset = view.getUint32(eocdOffset + 16, true);
|
||||
console.log('[v2 Sign] Original EOCD CD offset:', originalEocdOffset);
|
||||
console.log('[v2 Sign] cdOffset (signing block start):', cdOffset);
|
||||
// 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
|
||||
console.log('[v2 Sign] Predicted signing block size:', signingBlockTotalSize);
|
||||
console.log('[v2 Sign] Actual signing block size:', signingBlock.length);
|
||||
if (signingBlockTotalSize !== signingBlock.length) {
|
||||
console.error('[v2 Sign] 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;
|
||||
|
||||
console.log('[APK Sign] Starting signing process...');
|
||||
|
||||
// Load the APK (ZIP file)
|
||||
console.log('[APK Sign] Loading ZIP...');
|
||||
const zip = await JSZip.loadAsync(apkData);
|
||||
console.log('[APK Sign] ZIP loaded, files:', Object.keys(zip.files).length);
|
||||
|
||||
// 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);
|
||||
}
|
||||
console.log('[APK Sign] Removed existing signatures');
|
||||
|
||||
// Create MANIFEST.MF
|
||||
console.log('[APK Sign] Creating manifest...');
|
||||
const manifest = await createManifest(zip);
|
||||
console.log('[APK Sign] Manifest created, length:', manifest.length);
|
||||
zip.file('META-INF/MANIFEST.MF', manifest, { compression: 'DEFLATE' });
|
||||
|
||||
// Create CERT.SF (signature file)
|
||||
console.log('[APK Sign] Creating signature file...');
|
||||
const signatureFile = createSignatureFile(manifest);
|
||||
console.log('[APK Sign] Signature file created, length:', signatureFile.length);
|
||||
zip.file('META-INF/CERT.SF', signatureFile, { compression: 'DEFLATE' });
|
||||
|
||||
// Create CERT.RSA (PKCS#7 signature block)
|
||||
console.log('[APK Sign] Creating signature block...');
|
||||
const signatureBlock = createSignatureBlock(signatureFile, key);
|
||||
console.log('[APK Sign] Signature block created, length:', signatureBlock.length);
|
||||
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+
|
||||
console.log('[APK Sign] Generating signed APK...');
|
||||
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+)
|
||||
console.log('[APK Sign] Applying zipalign...');
|
||||
const alignedApk = zipalign(new Uint8Array(signedApkRaw), 4);
|
||||
|
||||
// Apply APK Signature Scheme v2
|
||||
// This is required for Android 7.0+ and mandatory for Android 11+
|
||||
console.log('[APK Sign] Applying v2 signature...');
|
||||
const v2SignedApk = applyV2Signature(alignedApk, key);
|
||||
console.log('[APK Sign] Done!');
|
||||
|
||||
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> {
|
||||
console.log('[Manifest] Starting...');
|
||||
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();
|
||||
|
||||
console.log('[Manifest] Processing', files.length, 'files');
|
||||
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const fileName = files[i];
|
||||
if (i % 50 === 0) {
|
||||
console.log('[Manifest] Processing file', i, '/', files.length, fileName);
|
||||
}
|
||||
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('');
|
||||
}
|
||||
|
||||
console.log('[Manifest] Done, lines:', lines.length);
|
||||
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;
|
||||
|
||||
console.log('[Signature Block] Starting...');
|
||||
|
||||
// Create SHA-256 digest of the signature file
|
||||
console.log('[Signature Block] Creating digest...');
|
||||
const md = forge.md.sha256.create();
|
||||
md.update(signatureFile, 'utf8');
|
||||
console.log('[Signature Block] Digest created');
|
||||
|
||||
// Sign the digest directly with RSA
|
||||
// Type assertion needed due to node-forge type definition issues
|
||||
console.log('[Signature Block] Signing with RSA...');
|
||||
const rsaPrivateKey = privateKey as unknown as forge.pki.rsa.PrivateKey;
|
||||
const signature = rsaPrivateKey.sign(md);
|
||||
console.log('[Signature Block] Signature created, length:', signature.length);
|
||||
|
||||
// Build PKCS#7 SignedData structure manually
|
||||
// This avoids the recursion issues in forge.pkcs7
|
||||
// Use PEM->DER conversion to avoid certificateToAsn1 recursion issues
|
||||
console.log('[Signature Block] Converting certificate to PEM...');
|
||||
const certPem = forge.pki.certificateToPem(certificate);
|
||||
console.log('[Signature Block] PEM created, length:', certPem.length);
|
||||
|
||||
const certDerBase64 = certPem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
console.log('[Signature Block] DER base64 extracted, length:', certDerBase64.length);
|
||||
|
||||
const certDer = forge.util.decode64(certDerBase64);
|
||||
console.log('[Signature Block] DER decoded, length:', certDer.length);
|
||||
|
||||
console.log('[Signature Block] Parsing DER to ASN1...');
|
||||
const certAsn1 = forge.asn1.fromDer(certDer);
|
||||
console.log('[Signature Block] Certificate ASN1 created');
|
||||
|
||||
console.log('[Signature Block] Building signerInfo...');
|
||||
console.log('[Signature Block] issuer attributes:', certificate.issuer.attributes.length);
|
||||
console.log('[Signature Block] serialNumber:', certificate.serialNumber);
|
||||
|
||||
// Build issuer DN ASN.1 separately to debug
|
||||
console.log('[Signature Block] Building issuer DN...');
|
||||
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, []);
|
||||
}
|
||||
console.log('[Signature Block] Issuer DN built');
|
||||
|
||||
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),
|
||||
]);
|
||||
console.log('[Signature Block] signerInfo created');
|
||||
|
||||
console.log('[Signature Block] Building signedData...');
|
||||
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]),
|
||||
]);
|
||||
console.log('[Signature Block] signedData created');
|
||||
|
||||
// Wrap in ContentInfo
|
||||
console.log('[Signature Block] Building 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]),
|
||||
]);
|
||||
console.log('[Signature Block] contentInfo created');
|
||||
|
||||
console.log('[Signature Block] Converting to DER...');
|
||||
const der = forge.asn1.toDer(contentInfo);
|
||||
console.log('[Signature Block] DER conversion complete');
|
||||
|
||||
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.');
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import JSZip from 'jszip';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, APKBuilderDeployConfig } from './types';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, APKBuilderDeployConfig, APKBuildType } from './types';
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
|
||||
interface APKBuildStatus {
|
||||
@@ -22,6 +22,7 @@ export class APKBuilderAdapter implements DeployAdapter {
|
||||
private apiKey: string;
|
||||
private appName: string;
|
||||
private packageId: string;
|
||||
private buildType: APKBuildType;
|
||||
private corsProxy?: string;
|
||||
private onProgress?: (status: APKBuildStatus) => void;
|
||||
|
||||
@@ -31,6 +32,7 @@ export class APKBuilderAdapter implements DeployAdapter {
|
||||
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;
|
||||
}
|
||||
@@ -73,6 +75,7 @@ export class APKBuilderAdapter implements DeployAdapter {
|
||||
formData.append('config', JSON.stringify({
|
||||
appName: this.appName,
|
||||
packageId: this.packageId,
|
||||
buildType: this.buildType,
|
||||
}));
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
@@ -114,6 +117,7 @@ export class APKBuilderAdapter implements DeployAdapter {
|
||||
type: 'apk',
|
||||
appName: this.appName,
|
||||
packageId: this.packageId,
|
||||
buildType: this.buildType,
|
||||
apkSize: status.apkSize,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -75,6 +75,21 @@ 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 */
|
||||
@@ -85,6 +100,10 @@ export interface APKBuilderDeployConfig {
|
||||
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 */
|
||||
|
||||
Reference in new issue
Block a user