mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
316ddf284d | ||
|
|
5fc96c9007 | ||
|
|
9352b70df8 | ||
|
|
b4cfc1a5ee | ||
|
|
a07368b190 | ||
|
|
66bfb56694 | ||
|
|
3cb7a8f673 | ||
|
|
6edc623c13 | ||
|
|
027cd819f8 | ||
|
|
ef55e80c35 | ||
|
|
3666aac2a1 | ||
|
|
f58f75ae8b | ||
|
|
22885e0978 | ||
|
|
a988238bb4 | ||
|
|
11197139f9 | ||
|
|
9ccad00888 | ||
|
|
32ff6570cf | ||
|
|
80bb72ef79 | ||
|
|
e45f167d2b | ||
|
|
7e755916c0 | ||
|
|
5915b96d98 | ||
|
|
b327607be3 | ||
|
|
e23b5031ee | ||
|
|
104a08c75a | ||
|
|
ddc23e3800 | ||
|
|
a1959369c5 | ||
|
|
6c4c1dab3b |
No files matched your search
+42
-2
@@ -15,6 +15,7 @@ The OAuth system consists of three main components:
|
|||||||
- **GitHub** - Git repository hosting (with PKCE support)
|
- **GitHub** - Git repository hosting (with PKCE support)
|
||||||
- **Netlify** - Static site deployment
|
- **Netlify** - Static site deployment
|
||||||
- **Vercel** - Static site deployment
|
- **Vercel** - Static site deployment
|
||||||
|
- **OpenRouter** - AI model routing (with PKCE support)
|
||||||
|
|
||||||
## File Structure
|
## File Structure
|
||||||
|
|
||||||
@@ -24,11 +25,13 @@ src/
|
|||||||
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
||||||
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
||||||
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
||||||
│ └── useVercelOAuth.ts # Vercel-specific configuration
|
│ ├── useVercelOAuth.ts # Vercel-specific configuration
|
||||||
|
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
|
||||||
├── pages/
|
├── pages/
|
||||||
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
||||||
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
|
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
|
||||||
│ └── VercelOAuth.tsx # Vercel OAuth callback page
|
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
|
||||||
|
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
|
||||||
└── AppRouter.tsx # Routes for OAuth callbacks
|
└── AppRouter.tsx # Routes for OAuth callbacks
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -190,6 +193,7 @@ const config: OAuthConfig = {
|
|||||||
- ✅ GitHub - Supports PKCE (enabled)
|
- ✅ GitHub - Supports PKCE (enabled)
|
||||||
- ❌ Netlify - Doesn't support PKCE (disabled)
|
- ❌ Netlify - Doesn't support PKCE (disabled)
|
||||||
- ❌ Vercel - Doesn't support PKCE (disabled)
|
- ❌ Vercel - Doesn't support PKCE (disabled)
|
||||||
|
- ✅ OpenRouter - Requires PKCE (enabled)
|
||||||
|
|
||||||
### Scope Parameter
|
### Scope Parameter
|
||||||
|
|
||||||
@@ -199,6 +203,42 @@ The `scope` parameter is optional in the OAuth configuration. Some providers (li
|
|||||||
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
|
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
|
||||||
- ❌ Netlify - No scope parameter (permissions set in app settings)
|
- ❌ Netlify - No scope parameter (permissions set in app settings)
|
||||||
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
|
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
|
||||||
|
- ❌ OpenRouter - No scope parameter (uses PKCE for authorization)
|
||||||
|
|
||||||
|
### OpenRouter Custom OAuth Implementation
|
||||||
|
|
||||||
|
OpenRouter uses a custom OAuth flow that differs from the standard OAuth 2.0 specification. Instead of using the generic `useOAuth` hook, it has a dedicated `useOpenRouterOAuth` hook with the following key differences:
|
||||||
|
|
||||||
|
1. **No Client Credentials**: OpenRouter doesn't require client ID or client secret - it uses PKCE only
|
||||||
|
2. **Authorization URL**: Uses `callback_url` parameter instead of `redirect_uri`
|
||||||
|
3. **Token Exchange**: Posts to `/api/v1/auth/keys` with a simplified request body
|
||||||
|
4. **Response Format**: Returns `{ key }` instead of standard `{ access_token }`
|
||||||
|
5. **PKCE Required**: Must use PKCE with S256 code challenge method
|
||||||
|
6. **No User Info**: Doesn't provide a user info endpoint after authentication
|
||||||
|
7. **No Environment Variables**: No configuration needed - works out of the box
|
||||||
|
|
||||||
|
**Authorization URL Format:**
|
||||||
|
```
|
||||||
|
https://openrouter.ai/auth?callback_url=<REDIRECT_URI>&code_challenge=<CHALLENGE>&code_challenge_method=S256
|
||||||
|
```
|
||||||
|
|
||||||
|
**Token Exchange Request:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": "<CODE_FROM_QUERY_PARAM>",
|
||||||
|
"code_verifier": "<CODE_VERIFIER>",
|
||||||
|
"code_challenge_method": "S256"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Token Exchange Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"key": "sk-or-v1-..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This custom implementation is fully contained in `useOpenRouterOAuth.ts` and doesn't rely on the generic OAuth hook. Unlike other providers, OpenRouter's OAuth doesn't require any environment variables or application registration - it works immediately without configuration.
|
||||||
|
|
||||||
## Adding a New OAuth Provider
|
## Adding a New OAuth Provider
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"nostr": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
-41
@@ -68,7 +68,6 @@
|
|||||||
"jszip": "^3.10.1",
|
"jszip": "^3.10.1",
|
||||||
"lucide-react": "^0.562.0",
|
"lucide-react": "^0.562.0",
|
||||||
"mime": "^4.1.0",
|
"mime": "^4.1.0",
|
||||||
"node-forge": "^1.3.3",
|
|
||||||
"nostr-tools": "^2.15.2",
|
"nostr-tools": "^2.15.2",
|
||||||
"nunjucks": "^3.2.4",
|
"nunjucks": "^3.2.4",
|
||||||
"openai": "^5.15.0",
|
"openai": "^5.15.0",
|
||||||
@@ -108,7 +107,6 @@
|
|||||||
"@testing-library/user-event": "^14.6.1",
|
"@testing-library/user-event": "^14.6.1",
|
||||||
"@types/jszip": "^3.4.0",
|
"@types/jszip": "^3.4.0",
|
||||||
"@types/node": "^22.5.5",
|
"@types/node": "^22.5.5",
|
||||||
"@types/node-forge": "^1.3.14",
|
|
||||||
"@types/nunjucks": "^3.2.6",
|
"@types/nunjucks": "^3.2.6",
|
||||||
"@types/path-browserify": "^1.0.3",
|
"@types/path-browserify": "^1.0.3",
|
||||||
"@types/prismjs": "^1.26.5",
|
"@types/prismjs": "^1.26.5",
|
||||||
@@ -4490,7 +4488,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4504,7 +4501,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4518,7 +4514,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4532,7 +4527,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4546,7 +4540,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4560,7 +4553,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4574,7 +4566,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4588,7 +4579,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4602,7 +4592,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4616,7 +4605,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4630,7 +4618,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"loong64"
|
"loong64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4644,7 +4631,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4658,7 +4644,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4672,7 +4657,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4686,7 +4670,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4700,7 +4683,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4714,7 +4696,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4728,7 +4709,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4742,7 +4722,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"ia32"
|
"ia32"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4756,7 +4735,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -5615,16 +5593,6 @@
|
|||||||
"undici-types": "~6.21.0"
|
"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": {
|
"node_modules/@types/nunjucks": {
|
||||||
"version": "3.2.6",
|
"version": "3.2.6",
|
||||||
"resolved": "https://registry.npmjs.org/@types/nunjucks/-/nunjucks-3.2.6.tgz",
|
"resolved": "https://registry.npmjs.org/@types/nunjucks/-/nunjucks-3.2.6.tgz",
|
||||||
@@ -11753,15 +11721,6 @@
|
|||||||
"node": ">= 0.6"
|
"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": {
|
"node_modules/node-releases": {
|
||||||
"version": "2.0.26",
|
"version": "2.0.26",
|
||||||
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.26.tgz",
|
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.26.tgz",
|
||||||
|
|||||||
@@ -79,7 +79,6 @@
|
|||||||
"jszip": "^3.10.1",
|
"jszip": "^3.10.1",
|
||||||
"lucide-react": "^0.562.0",
|
"lucide-react": "^0.562.0",
|
||||||
"mime": "^4.1.0",
|
"mime": "^4.1.0",
|
||||||
"node-forge": "^1.3.3",
|
|
||||||
"nostr-tools": "^2.15.2",
|
"nostr-tools": "^2.15.2",
|
||||||
"nunjucks": "^3.2.4",
|
"nunjucks": "^3.2.4",
|
||||||
"openai": "^5.15.0",
|
"openai": "^5.15.0",
|
||||||
@@ -119,7 +118,6 @@
|
|||||||
"@testing-library/user-event": "^14.6.1",
|
"@testing-library/user-event": "^14.6.1",
|
||||||
"@types/jszip": "^3.4.0",
|
"@types/jszip": "^3.4.0",
|
||||||
"@types/node": "^22.5.5",
|
"@types/node": "^22.5.5",
|
||||||
"@types/node-forge": "^1.3.14",
|
|
||||||
"@types/nunjucks": "^3.2.6",
|
"@types/nunjucks": "^3.2.6",
|
||||||
"@types/path-browserify": "^1.0.3",
|
"@types/path-browserify": "^1.0.3",
|
||||||
"@types/prismjs": "^1.26.5",
|
"@types/prismjs": "^1.26.5",
|
||||||
|
|||||||
@@ -1,166 +0,0 @@
|
|||||||
# 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+7
-6
@@ -24,8 +24,13 @@ export default {
|
|||||||
return new Response('Invalid url parameter', { status: 400 });
|
return new Response('Invalid url parameter', { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let hostname = url.hostname;
|
||||||
|
|
||||||
|
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||||
|
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||||
|
|
||||||
// GitHub hack: neutral color for light/dark mode
|
// GitHub hack: neutral color for light/dark mode
|
||||||
if (url.hostname === 'github.com') {
|
if (hostname === 'github.com') {
|
||||||
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
|
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
|
||||||
return new Response(svg.replaceAll('#24292E', '#808080'), {
|
return new Response(svg.replaceAll('#24292E', '#808080'), {
|
||||||
headers: { 'Content-Type': 'image/svg+xml' },
|
headers: { 'Content-Type': 'image/svg+xml' },
|
||||||
@@ -33,20 +38,16 @@ export default {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AI-provider-specific hacks
|
// AI-provider-specific hacks
|
||||||
let hostname = url.hostname;
|
|
||||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||||
hostname = 'ollama.com';
|
hostname = 'ollama.com';
|
||||||
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
|
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
|
||||||
hostname = 'claude.ai';
|
hostname = 'claude.ai';
|
||||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||||
hostname = 'gemini.google.com';
|
hostname = 'gemini.google.com';
|
||||||
} else if (url.host === 'api.z.ai') {
|
} else if (url.host === 'z.ai') {
|
||||||
hostname = 'docs.z.ai';
|
hostname = 'docs.z.ai';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
|
||||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
|
||||||
|
|
||||||
// Fetch the favicon from DuckDuckGo's service
|
// Fetch the favicon from DuckDuckGo's service
|
||||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||||
},
|
},
|
||||||
|
|||||||
+9
-8
@@ -12,16 +12,17 @@ export default {
|
|||||||
return new Response(null, {
|
return new Response(null, {
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: {
|
headers: {
|
||||||
"Access-Control-Allow-Origin": "*",
|
"access-control-allow-origin": "*",
|
||||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
"access-control-allow-methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||||
"Access-Control-Allow-Headers": "*", // Or specify specific headers
|
"access-control-allow-headers": "*", // Or specify specific headers
|
||||||
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
|
"access-control-max-age": "86400", // Cache preflight for 24 hours
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const headers = new Headers(request.headers);
|
const headers = new Headers(request.headers);
|
||||||
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
headers.set('user-agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||||
|
headers.delete('origin');
|
||||||
|
|
||||||
const targetResponse = await fetch(target, {
|
const targetResponse = await fetch(target, {
|
||||||
method: request.method,
|
method: request.method,
|
||||||
@@ -31,9 +32,9 @@ export default {
|
|||||||
|
|
||||||
const response = new Response(targetResponse.body, targetResponse);
|
const response = new Response(targetResponse.body, targetResponse);
|
||||||
|
|
||||||
response.headers.set("Access-Control-Allow-Origin", "*");
|
response.headers.set("access-control-allow-origin", "*");
|
||||||
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
response.headers.set("access-control-allow-methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||||
response.headers.set("Access-Control-Allow-Headers", "*");
|
response.headers.set("access-control-allow-headers", "*");
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import AboutSettings from "./pages/AboutSettings";
|
|||||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||||
import VercelOAuth from "./pages/VercelOAuth";
|
import VercelOAuth from "./pages/VercelOAuth";
|
||||||
|
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
||||||
import { NIP19Page } from "./pages/NIP19Page";
|
import { NIP19Page } from "./pages/NIP19Page";
|
||||||
import NotFound from "./pages/NotFound";
|
import NotFound from "./pages/NotFound";
|
||||||
import { ProjectView } from "./pages/ProjectView";
|
import { ProjectView } from "./pages/ProjectView";
|
||||||
@@ -39,6 +40,7 @@ export function AppRouter() {
|
|||||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||||
|
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
||||||
<Route path="/settings" element={<SettingsLayout />}>
|
<Route path="/settings" element={<SettingsLayout />}>
|
||||||
<Route index element={<Settings />} />
|
<Route index element={<Settings />} />
|
||||||
<Route path="preferences" element={<Preferences />} />
|
<Route path="preferences" element={<Preferences />} />
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Bot } from 'lucide-react';
|
import { Bot, ChevronDown } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
import { ExternalInput } from '@/components/ui/external-input';
|
import { ExternalInput } from '@/components/ui/external-input';
|
||||||
@@ -12,15 +12,31 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import type { PresetProvider } from '@/lib/aiProviderPresets';
|
import type { PresetProvider } from '@/lib/aiProviderPresets';
|
||||||
|
|
||||||
|
interface OAuthHook {
|
||||||
|
isOAuthConfigured: boolean;
|
||||||
|
isLoading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
initiateOAuth: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
interface AddAIProviderDialogProps {
|
interface AddAIProviderDialogProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
preset: PresetProvider;
|
preset: PresetProvider;
|
||||||
isLoggedIntoNostr: boolean;
|
isLoggedIntoNostr: boolean;
|
||||||
|
oauthHook?: OAuthHook | null;
|
||||||
|
forceManualEntry?: boolean;
|
||||||
|
onSetForceManualEntry?: (force: boolean) => void;
|
||||||
onAdd: (apiKey: string) => void;
|
onAdd: (apiKey: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,6 +45,9 @@ export function AddAIProviderDialog({
|
|||||||
onOpenChange,
|
onOpenChange,
|
||||||
preset,
|
preset,
|
||||||
isLoggedIntoNostr,
|
isLoggedIntoNostr,
|
||||||
|
oauthHook,
|
||||||
|
forceManualEntry = false,
|
||||||
|
onSetForceManualEntry,
|
||||||
onAdd,
|
onAdd,
|
||||||
}: AddAIProviderDialogProps) {
|
}: AddAIProviderDialogProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -36,16 +55,27 @@ export function AddAIProviderDialog({
|
|||||||
const [termsAgreed, setTermsAgreed] = useState(false);
|
const [termsAgreed, setTermsAgreed] = useState(false);
|
||||||
|
|
||||||
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
|
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
|
||||||
|
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||||
|
const isOAuthLoading = oauthHook?.isLoading ?? false;
|
||||||
|
const oauthError = oauthHook?.error ?? null;
|
||||||
|
|
||||||
const handleAdd = () => {
|
const handleAdd = () => {
|
||||||
onAdd(apiKey);
|
onAdd(apiKey);
|
||||||
setApiKey('');
|
setApiKey('');
|
||||||
setTermsAgreed(false);
|
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Reset state when dialog closes
|
||||||
|
const handleOpenChange = (open: boolean) => {
|
||||||
|
if (!open) {
|
||||||
|
setApiKey('');
|
||||||
|
setTermsAgreed(false);
|
||||||
|
}
|
||||||
|
onOpenChange(open);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
<DialogContent className="max-w-md">
|
<DialogContent className="max-w-md">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -73,6 +103,50 @@ export function AddAIProviderDialog({
|
|||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
) : isOAuthConfigured && !forceManualEntry ? (
|
||||||
|
// Show OAuth button if OAuth is configured and not forced to manual
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex gap-0">
|
||||||
|
<Button
|
||||||
|
onClick={() => oauthHook?.initiateOAuth()}
|
||||||
|
disabled={isOAuthLoading}
|
||||||
|
className="flex-1 rounded-r-none gap-2"
|
||||||
|
variant="default"
|
||||||
|
>
|
||||||
|
{isOAuthLoading ? (
|
||||||
|
<>
|
||||||
|
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||||
|
Connecting...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="truncate text-ellipsis overflow-hidden">
|
||||||
|
Connect to {preset.name}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
className="rounded-l-none border-l border-primary-foreground/20 px-2"
|
||||||
|
disabled={isOAuthLoading}
|
||||||
|
>
|
||||||
|
<ChevronDown className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem onClick={() => onSetForceManualEntry?.(true)}>
|
||||||
|
Enter API key
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
{oauthError && (
|
||||||
|
<p className="text-sm text-destructive">
|
||||||
|
{oauthError}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{!preset.nostr && preset.apiKeysURL && (
|
{!preset.nostr && preset.apiKeysURL && (
|
||||||
@@ -123,7 +197,7 @@ export function AddAIProviderDialog({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!showNostrLoginRequired && (
|
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
{t('cancel')}
|
{t('cancel')}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Rocket, ChevronDown, Key, Loader2 } from 'lucide-react';
|
import { Rocket, ChevronDown } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { ExternalInput } from '@/components/ui/external-input';
|
import { ExternalInput } from '@/components/ui/external-input';
|
||||||
import {
|
import {
|
||||||
@@ -19,9 +19,6 @@ import {
|
|||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
import { Link } from 'react-router-dom';
|
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';
|
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||||
|
|
||||||
interface OAuthHook {
|
interface OAuthHook {
|
||||||
@@ -31,7 +28,7 @@ interface OAuthHook {
|
|||||||
initiateOAuth: () => void;
|
initiateOAuth: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AddProviderDialogProps {
|
interface AddDeployProviderDialogProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
preset: PresetDeployProvider;
|
preset: PresetDeployProvider;
|
||||||
@@ -39,10 +36,10 @@ interface AddProviderDialogProps {
|
|||||||
oauthHook: OAuthHook | null;
|
oauthHook: OAuthHook | null;
|
||||||
forceManualEntry: boolean;
|
forceManualEntry: boolean;
|
||||||
onSetForceManualEntry: (force: boolean) => void;
|
onSetForceManualEntry: (force: boolean) => void;
|
||||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => void;
|
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AddProviderDialog({
|
export function AddDeployProviderDialog({
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
preset,
|
preset,
|
||||||
@@ -51,16 +48,11 @@ export function AddProviderDialog({
|
|||||||
forceManualEntry,
|
forceManualEntry,
|
||||||
onSetForceManualEntry,
|
onSetForceManualEntry,
|
||||||
onAdd,
|
onAdd,
|
||||||
}: AddProviderDialogProps) {
|
}: AddDeployProviderDialogProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { config } = useAppContext();
|
|
||||||
const [apiKey, setApiKey] = useState('');
|
const [apiKey, setApiKey] = useState('');
|
||||||
const [accountId, setAccountId] = useState('');
|
const [accountId, setAccountId] = useState('');
|
||||||
const [organizationId, setOrganizationId] = 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 showNostrLoginRequired = preset.requiresNostr && !isLoggedIntoNostr;
|
||||||
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||||
@@ -68,38 +60,13 @@ export function AddProviderDialog({
|
|||||||
const oauthError = oauthHook?.error ?? null;
|
const oauthError = oauthHook?.error ?? null;
|
||||||
|
|
||||||
const handleAdd = () => {
|
const handleAdd = () => {
|
||||||
onAdd(apiKey, accountId, organizationId, buildServerUrl);
|
onAdd(apiKey, accountId, organizationId);
|
||||||
setApiKey('');
|
setApiKey('');
|
||||||
setAccountId('');
|
setAccountId('');
|
||||||
setOrganizationId('');
|
setOrganizationId('');
|
||||||
setBuildServerUrl('');
|
|
||||||
setApiKeyError(null);
|
|
||||||
onOpenChange(false);
|
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 (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent className="max-w-md">
|
<DialogContent className="max-w-md">
|
||||||
@@ -145,16 +112,9 @@ export function AddProviderDialog({
|
|||||||
Connecting...
|
Connecting...
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
|
||||||
<ExternalFavicon
|
|
||||||
url={preset.baseURL}
|
|
||||||
size={16}
|
|
||||||
fallback={<Rocket size={16} />}
|
|
||||||
/>
|
|
||||||
<span className="truncate text-ellipsis overflow-hidden">
|
<span className="truncate text-ellipsis overflow-hidden">
|
||||||
Connect to {preset.name}
|
Connect to {preset.name}
|
||||||
</span>
|
</span>
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -215,62 +175,6 @@ export function AddProviderDialog({
|
|||||||
urlTitle="Find ID"
|
urlTitle="Find ID"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{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
|
<ExternalInput
|
||||||
type="password"
|
type="password"
|
||||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||||
@@ -286,7 +190,6 @@ export function AddProviderDialog({
|
|||||||
url={preset.apiKeyURL}
|
url={preset.apiKeyURL}
|
||||||
urlTitle="Get Key"
|
urlTitle="Get Key"
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -304,8 +207,7 @@ export function AddProviderDialog({
|
|||||||
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
||||||
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
|
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
|
||||||
(preset.type === 'cloudflare' && !accountId.trim()) ||
|
(preset.type === 'cloudflare' && !accountId.trim()) ||
|
||||||
(preset.type === 'deno' && !organizationId.trim()) ||
|
(preset.type === 'deno' && !organizationId.trim())
|
||||||
(preset.type === 'apkbuilder' && !buildServerUrl.trim())
|
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{t('add')}
|
{t('add')}
|
||||||
@@ -84,8 +84,8 @@ export function AddGitCredentialDialog({
|
|||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="space-y-4 py-4">
|
<div className="space-y-4 py-4">
|
||||||
{preset.id === 'github' && isOAuthConfigured && !forceManualEntry ? (
|
{isOAuthConfigured && !forceManualEntry ? (
|
||||||
// Special rendering for GitHub OAuth
|
// Show OAuth button if OAuth is configured and not forced to manual
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="flex gap-0">
|
<div className="flex gap-0">
|
||||||
<Button
|
<Button
|
||||||
@@ -100,16 +100,9 @@ export function AddGitCredentialDialog({
|
|||||||
Connecting...
|
Connecting...
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
|
||||||
<ExternalFavicon
|
|
||||||
url="https://github.com"
|
|
||||||
size={16}
|
|
||||||
fallback={<GitBranch size={16} />}
|
|
||||||
/>
|
|
||||||
<span className="truncate text-ellipsis overflow-hidden">
|
<span className="truncate text-ellipsis overflow-hidden">
|
||||||
Connect to GitHub
|
Connect to {preset.name}
|
||||||
</span>
|
</span>
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -124,7 +117,7 @@ export function AddGitCredentialDialog({
|
|||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
||||||
Enter API key
|
Enter token manually
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
@@ -136,7 +129,7 @@ export function AddGitCredentialDialog({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
// Standard token input
|
// Show manual token input
|
||||||
<ExternalInput
|
<ExternalInput
|
||||||
type="password"
|
type="password"
|
||||||
placeholder={t('enterToken')}
|
placeholder={t('enterToken')}
|
||||||
@@ -153,7 +146,7 @@ export function AddGitCredentialDialog({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!(preset.id === 'github' && isOAuthConfigured && !forceManualEntry) && (
|
{!(isOAuthConfigured && !forceManualEntry) && (
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
{t('cancel')}
|
{t('cancel')}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useState, useEffect, useRef } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { generateSecretKey } from 'nostr-tools';
|
import { generateSecretKey } from 'nostr-tools';
|
||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
|
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, Search, Coins } from 'lucide-react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@@ -9,7 +9,7 @@ import { Card, CardHeader, CardTitle } from '@/components/ui/card';
|
|||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { PasswordInput } from '@/components/ui/password-input';
|
import { ExternalInput } from '@/components/ui/external-input';
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||||
@@ -465,37 +465,28 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
|||||||
{/* API Key Input Section */}
|
{/* API Key Input Section */}
|
||||||
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
||||||
<div className="space-y-3 max-w-md mx-auto">
|
<div className="space-y-3 max-w-md mx-auto">
|
||||||
<div className="text-center">
|
<h3 className="flex justify-center text-lg font-semibold gap-2">
|
||||||
<h3 className="text-lg font-semibold">
|
<ExternalFavicon
|
||||||
|
url={selectedProvider.baseURL}
|
||||||
|
size={16}
|
||||||
|
fallback={<Bot size={16} />}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||||
|
</span>
|
||||||
</h3>
|
</h3>
|
||||||
<p className="text-sm text-muted-foreground">
|
<ExternalInput
|
||||||
{selectedProvider.id === 'routstr' ? (
|
type="password"
|
||||||
t('requiresCashuToken', { providerName: selectedProvider.name })
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
{selectedProvider.name} {t('requiresAnApiKey')}{' '}
|
|
||||||
{selectedProvider.apiKeysURL ? (
|
|
||||||
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
|
|
||||||
{t('apiKey')}
|
|
||||||
<ExternalLink className="inline-block h-4 w-4 ml-1" />
|
|
||||||
</a>
|
|
||||||
) : (
|
|
||||||
t('apiKey')
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<PasswordInput
|
|
||||||
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||||
value={providerApiKey}
|
value={providerApiKey}
|
||||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Enter' && providerApiKey.trim()) {
|
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
|
||||||
handleContinueFromProviderSelection();
|
handleContinueFromProviderSelection();
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
url={selectedProvider.apiKeysURL}
|
||||||
|
urlTitle="Get Key"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ export function ProjectTitleMenu({
|
|||||||
className="gap-2"
|
className="gap-2"
|
||||||
>
|
>
|
||||||
<MessageSquarePlus className="h-4 w-4" />
|
<MessageSquarePlus className="h-4 w-4" />
|
||||||
New Chat
|
{t('newChat')}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
|
|||||||
@@ -125,44 +125,6 @@ export function ProviderConfigDialog({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</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' ? (
|
) : localProvider.type === 'nsite' ? (
|
||||||
<>
|
<>
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
/** Visual divider between chat sessions */
|
||||||
|
export function SessionDivider() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-3 text-xs text-muted-foreground py-4">
|
||||||
|
<div className="flex-1 h-px bg-border" />
|
||||||
|
<span className="uppercase tracking-wide">
|
||||||
|
{t('newChat', 'New chat')}
|
||||||
|
</span>
|
||||||
|
<div className="flex-1 h-px bg-border" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||||
import { ChevronDown, Play } from 'lucide-react';
|
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
@@ -47,11 +47,12 @@ import OpenAI from 'openai';
|
|||||||
import { useGit } from '@/hooks/useGit';
|
import { useGit } from '@/hooks/useGit';
|
||||||
import { Quilly } from '@/components/Quilly';
|
import { Quilly } from '@/components/Quilly';
|
||||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||||
|
import { SessionDivider } from '@/components/SessionDivider';
|
||||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||||
import { DotAI } from '@/lib/DotAI';
|
import { DotAI } from '@/lib/DotAI';
|
||||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||||
import { AIMessage } from '@/lib/SessionManager';
|
import { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||||
|
|
||||||
// Clean interfaces now handled by proper hooks
|
// Clean interfaces now handled by proper hooks
|
||||||
|
|
||||||
@@ -294,9 +295,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
sessionName,
|
||||||
streamingMessage,
|
streamingMessage,
|
||||||
isLoading: internalIsLoading,
|
isLoading: internalIsLoading,
|
||||||
isLoadingHistory,
|
isLoadingHistory,
|
||||||
|
hasMoreHistory,
|
||||||
|
isLoadingMoreHistory,
|
||||||
totalCost,
|
totalCost,
|
||||||
lastInputTokens,
|
lastInputTokens,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
@@ -305,6 +310,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
startGeneration,
|
startGeneration,
|
||||||
stopGeneration,
|
stopGeneration,
|
||||||
startNewSession: internalStartNewSession,
|
startNewSession: internalStartNewSession,
|
||||||
|
loadMoreHistory,
|
||||||
} = useAIChat({
|
} = useAIChat({
|
||||||
projectId,
|
projectId,
|
||||||
tools,
|
tools,
|
||||||
@@ -318,7 +324,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
const checkTemplateInfo = async () => {
|
const checkTemplateInfo = async () => {
|
||||||
try {
|
try {
|
||||||
// Only check if we have at least 1 message
|
// Only check if we have at least 1 message
|
||||||
if (messages.length === 0) {
|
if (displayMessages.length === 0) {
|
||||||
setShowTemplateInfo(false);
|
setShowTemplateInfo(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -357,7 +363,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
};
|
};
|
||||||
|
|
||||||
checkTemplateInfo();
|
checkTemplateInfo();
|
||||||
}, [fs, projectsPath, projectId, messages.length]);
|
}, [fs, projectsPath, projectId, displayMessages.length]);
|
||||||
|
|
||||||
// Handle console error help requests
|
// Handle console error help requests
|
||||||
const handleConsoleErrorHelp = useCallback(async () => {
|
const handleConsoleErrorHelp = useCallback(async () => {
|
||||||
@@ -435,9 +441,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
|
|
||||||
// Function to scroll to bottom
|
// Function to scroll to bottom
|
||||||
const scrollToBottom = useCallback(() => {
|
const scrollToBottom = useCallback(() => {
|
||||||
|
if (scrollAreaRef.current) {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
if (scrollAreaRef.current) {
|
if (scrollAreaRef.current) {
|
||||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Function to open model selector dropdown
|
// Function to open model selector dropdown
|
||||||
@@ -489,17 +499,20 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
||||||
// Check if user was already at or near the bottom (within 100px threshold)
|
|
||||||
const threshold = 100;
|
|
||||||
const container = scrollAreaRef.current;
|
const container = scrollAreaRef.current;
|
||||||
|
const lastMessage = messages[messages.length - 1];
|
||||||
|
const isUserMessage = lastMessage?.role === 'user';
|
||||||
|
|
||||||
|
// Check if user was already near the bottom (within 100px threshold)
|
||||||
|
const threshold = 100;
|
||||||
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
||||||
|
|
||||||
// Only auto-scroll if user was already near the bottom
|
// Scroll to bottom if user sent a message or was already near the bottom
|
||||||
if (isNearBottom) {
|
if (isUserMessage || isNearBottom) {
|
||||||
container.scrollTop = container.scrollHeight;
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [messages, streamingMessage, isLoading]);
|
}, [messages, streamingMessage, isLoading, scrollToBottom]);
|
||||||
|
|
||||||
// Scroll to bottom when first visiting a project (including page refresh)
|
// Scroll to bottom when first visiting a project (including page refresh)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -577,8 +590,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
// Add model to recently used when sending a message
|
// Add model to recently used when sending a message
|
||||||
addRecentlyUsedModel(modelToUse);
|
addRecentlyUsedModel(modelToUse);
|
||||||
|
|
||||||
|
// Scroll to bottom when user sends a message
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
await sendMessage(messageContent, modelToUse);
|
await sendMessage(messageContent, modelToUse);
|
||||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
|
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, scrollToBottom]);
|
||||||
|
|
||||||
// Handle textarea focus - show onboarding if not configured
|
// Handle textarea focus - show onboarding if not configured
|
||||||
const handleTextareaFocus = useCallback(() => {
|
const handleTextareaFocus = useCallback(() => {
|
||||||
@@ -757,7 +773,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Empty state when no messages and not loading */}
|
{/* Empty state when no messages and not loading */}
|
||||||
{!isLoadingHistory && messages.length === 0 && !streamingMessage && !isLoading && (
|
{!isLoadingHistory && displayMessages.length === 0 && !streamingMessage && !isLoading && (
|
||||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
@@ -781,13 +797,49 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isLoadingHistory && messages.map((message, index) => {
|
{/* Load older messages button */}
|
||||||
|
{!isLoadingHistory && hasMoreHistory && (
|
||||||
|
<div className="flex justify-center py-3">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={async () => {
|
||||||
|
const container = scrollAreaRef.current;
|
||||||
|
const oldScrollHeight = container?.scrollHeight || 0;
|
||||||
|
await loadMoreHistory();
|
||||||
|
// Preserve scroll position after prepending content
|
||||||
|
if (container) {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
container.scrollTop += container.scrollHeight - oldScrollHeight;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={isLoadingMoreHistory}
|
||||||
|
className="gap-2 text-muted-foreground"
|
||||||
|
>
|
||||||
|
<ChevronUp className="h-4 w-4" />
|
||||||
|
{isLoadingMoreHistory ? t('loading') : t('loadOlderMessages', 'Load older messages')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoadingHistory && displayMessages.map((message, index) => {
|
||||||
|
// Get the current message's session ID and compare to previous
|
||||||
|
const currentSessionId = (message as DisplayMessage).sessionId;
|
||||||
|
const prevSessionId = index > 0 ? (displayMessages[index - 1] as DisplayMessage).sessionId : undefined;
|
||||||
|
|
||||||
|
// Show divider when session changes (not on first message)
|
||||||
|
const showDivider = index > 0 && currentSessionId !== prevSessionId;
|
||||||
|
|
||||||
|
// Dim messages from older sessions (compare against current active session)
|
||||||
|
const isOlderSession = currentSessionId !== sessionName;
|
||||||
|
|
||||||
// Find the corresponding tool call for tool messages
|
// Find the corresponding tool call for tool messages
|
||||||
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
||||||
if (message.role === 'tool') {
|
if (message.role === 'tool') {
|
||||||
// Look backwards to find the assistant message with matching tool call
|
// Look backwards to find the assistant message with matching tool call
|
||||||
for (let i = index - 1; i >= 0; i--) {
|
for (let i = index - 1; i >= 0; i--) {
|
||||||
const prevMessage = messages[i];
|
const prevMessage = displayMessages[i];
|
||||||
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
|
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
|
||||||
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
|
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
|
||||||
if (toolCall) break;
|
if (toolCall) break;
|
||||||
@@ -796,14 +848,27 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AIMessageItem
|
<div
|
||||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||||
|
className={isOlderSession ? 'opacity-65' : ''}
|
||||||
|
>
|
||||||
|
{showDivider && <SessionDivider />}
|
||||||
|
<AIMessageItem
|
||||||
message={message}
|
message={message}
|
||||||
toolCall={toolCall}
|
toolCall={toolCall}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
|
{/* Trailing session divider - shown when New Chat is clicked before sending a message */}
|
||||||
|
{!isLoadingHistory && displayMessages.length > 0 && (() => {
|
||||||
|
const lastSessionId = (displayMessages[displayMessages.length - 1] as DisplayMessage).sessionId;
|
||||||
|
return sessionName && lastSessionId && sessionName !== lastSessionId ? (
|
||||||
|
<SessionDivider key="trailing-divider" />
|
||||||
|
) : null;
|
||||||
|
})()}
|
||||||
|
|
||||||
{!isLoadingHistory && renderStreamingMessage()}
|
{!isLoadingHistory && renderStreamingMessage()}
|
||||||
|
|
||||||
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
|
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
|
||||||
|
|||||||
@@ -1,262 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,595 +0,0 @@
|
|||||||
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 { useState, useEffect, useCallback } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud, Shield, Download, CheckCircle } from 'lucide-react';
|
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
@@ -15,7 +15,7 @@ import { useAppContext } from '@/hooks/useAppContext';
|
|||||||
import { useNostr } from '@nostrify/react';
|
import { useNostr } from '@nostrify/react';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||||
import type { APKBuildType, PresetDeployProvider } from '@/lib/deploy/types';
|
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||||
@@ -23,8 +23,6 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
|||||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||||
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
|
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
|
||||||
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
|
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
|
||||||
import { APKBuilderDeployForm } from '@/components/deploy/APKBuilderDeployForm';
|
|
||||||
import { APKSigner } from '@/components/deploy/APKSigner';
|
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { DeployAdapter } from '@/lib/deploy/types';
|
import { DeployAdapter } from '@/lib/deploy/types';
|
||||||
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
|
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
|
||||||
@@ -33,7 +31,6 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
|
|||||||
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
||||||
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
|
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
|
||||||
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
|
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
|
||||||
import { APKBuilderAdapter } from '@/lib/deploy/APKBuilderAdapter';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalize a URL string to ensure it has a protocol
|
* Normalize a URL string to ensure it has a protocol
|
||||||
@@ -104,12 +101,6 @@ interface DenoDeployFormData {
|
|||||||
projectName: string;
|
projectName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface APKBuilderFormData {
|
|
||||||
appName: string;
|
|
||||||
packageId: string;
|
|
||||||
buildType: APKBuildType;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
|
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { settings } = useDeploySettings();
|
const { settings } = useDeploySettings();
|
||||||
@@ -123,7 +114,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||||
const [isDeploying, setIsDeploying] = useState(false);
|
const [isDeploying, setIsDeploying] = useState(false);
|
||||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||||
const [signedApkBlob, setSignedApkBlob] = useState<Blob | null>(null);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||||
|
|
||||||
@@ -148,11 +138,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
|
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
|
||||||
projectName: projectName || projectId,
|
projectName: projectName || projectId,
|
||||||
});
|
});
|
||||||
const [apkBuilderForm, setApkBuilderForm] = useState<APKBuilderFormData>({
|
|
||||||
appName: projectName || projectId,
|
|
||||||
packageId: '',
|
|
||||||
buildType: 'debug',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Load project settings when component mounts
|
// Load project settings when component mounts
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -276,30 +261,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
projectName: denoDeployForm.projectName || undefined,
|
projectName: denoDeployForm.projectName || undefined,
|
||||||
corsProxy: denoProvider.proxy ? config.corsProxy : 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 {
|
} else {
|
||||||
throw new Error('Unknown provider type');
|
throw new Error('Unknown provider type');
|
||||||
}
|
}
|
||||||
@@ -359,16 +320,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
projectName: denoDeployForm.projectName || undefined,
|
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);
|
setDeployResult(result);
|
||||||
@@ -382,7 +333,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setSelectedProviderId('');
|
setSelectedProviderId('');
|
||||||
setDeployResult(null);
|
setDeployResult(null);
|
||||||
setSignedApkBlob(null);
|
|
||||||
setError(null);
|
setError(null);
|
||||||
// Reset forms
|
// Reset forms
|
||||||
setShakespeareForm({ subdomain: projectId });
|
setShakespeareForm({ subdomain: projectId });
|
||||||
@@ -391,27 +341,9 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||||
setCloudflareForm({ projectName: projectName || projectId });
|
setCloudflareForm({ projectName: projectName || projectId });
|
||||||
setDenoDeployForm({ projectName: projectName || projectId });
|
setDenoDeployForm({ projectName: projectName || projectId });
|
||||||
setApkBuilderForm({ appName: projectName || projectId, packageId: '', buildType: 'debug' });
|
|
||||||
onClose();
|
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) => {
|
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
|
||||||
setShakespeareForm({ subdomain });
|
setShakespeareForm({ subdomain });
|
||||||
}, []);
|
}, []);
|
||||||
@@ -440,10 +372,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
setDenoDeployForm({ projectName });
|
setDenoDeployForm({ projectName });
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleApkBuilderConfigChange = useCallback((appName: string, packageId: string, buildType: APKBuildType) => {
|
|
||||||
setApkBuilderForm({ appName, packageId, buildType });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const renderProviderFields = () => {
|
const renderProviderFields = () => {
|
||||||
if (!selectedProvider) return null;
|
if (!selectedProvider) return null;
|
||||||
|
|
||||||
@@ -549,28 +477,6 @@ 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;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -585,101 +491,15 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
|
|
||||||
{deployResult ? (
|
{deployResult ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{/* 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>
|
|
||||||
|
|
||||||
{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="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>
|
<Alert>
|
||||||
<Rocket className="h-4 w-4" />
|
<Rocket className="h-4 w-4" />
|
||||||
<AlertDescription>
|
<AlertDescription>
|
||||||
{selectedProvider?.type === 'apkbuilder'
|
Your project has been successfully deployed!
|
||||||
? 'Your project has been successfully built!'
|
|
||||||
: 'Your project has been successfully deployed!'}
|
|
||||||
</AlertDescription>
|
</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>{selectedProvider?.type === 'apkbuilder' ? 'Download URL' : 'Deployed URL'}</Label>
|
<Label>Deployed URL</Label>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Input
|
<Input
|
||||||
value={deployResult.url}
|
value={deployResult.url}
|
||||||
@@ -701,8 +521,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
{t('close')}
|
{t('close')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -835,8 +653,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
(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"
|
className="w-full"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useEffect, useRef } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { CloudUpload, Loader2, Check } from 'lucide-react';
|
import { CloudUpload, Loader2, Check, AlertTriangle } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||||
@@ -16,6 +16,8 @@ interface GitSyncButtonProps {
|
|||||||
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [syncSuccess, setSyncSuccess] = useState(false);
|
const [syncSuccess, setSyncSuccess] = useState(false);
|
||||||
|
const [showWarningPopover, setShowWarningPopover] = useState(false);
|
||||||
|
const warningDismissed = useRef(false);
|
||||||
|
|
||||||
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
|
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
|
||||||
const { getError, getState } = useGitSyncState();
|
const { getError, getState } = useGitSyncState();
|
||||||
@@ -26,6 +28,18 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
|||||||
const gitSyncState = getState(dir);
|
const gitSyncState = getState(dir);
|
||||||
const isGitActionOccurring = gitSyncState?.isActive ?? false;
|
const isGitActionOccurring = gitSyncState?.isActive ?? false;
|
||||||
const prevIsGitActionOccurring = useRef(isGitActionOccurring);
|
const prevIsGitActionOccurring = useRef(isGitActionOccurring);
|
||||||
|
const prevProjectId = useRef(projectId);
|
||||||
|
|
||||||
|
// Reset state when projectId changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (prevProjectId.current !== projectId) {
|
||||||
|
setSyncSuccess(false);
|
||||||
|
setShowWarningPopover(false);
|
||||||
|
warningDismissed.current = false;
|
||||||
|
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||||
|
prevProjectId.current = projectId;
|
||||||
|
}
|
||||||
|
}, [projectId, isGitActionOccurring]);
|
||||||
|
|
||||||
// Detect when a git action completes successfully
|
// Detect when a git action completes successfully
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -38,6 +52,29 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
|||||||
prevIsGitActionOccurring.current = isGitActionOccurring;
|
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||||
}, [isGitActionOccurring, hasError]);
|
}, [isGitActionOccurring, hasError]);
|
||||||
|
|
||||||
|
// Check if we need to show the warning popover
|
||||||
|
const needsRemote = !isGitStatusLoading && gitStatus &&
|
||||||
|
!gitStatus.remotes.find(r => r.name === 'origin') &&
|
||||||
|
gitStatus.totalCommits > 1;
|
||||||
|
|
||||||
|
// Show warning popover when purple indicator is visible (only if not dismissed)
|
||||||
|
useEffect(() => {
|
||||||
|
if (needsRemote && !warningDismissed.current && gitStatus.totalCommits > 1) {
|
||||||
|
setShowWarningPopover(true);
|
||||||
|
} else {
|
||||||
|
setShowWarningPopover(false);
|
||||||
|
}
|
||||||
|
}, [gitStatus?.totalCommits, needsRemote]);
|
||||||
|
|
||||||
|
// Handle button click - dismiss warning popover permanently
|
||||||
|
const handleButtonClick = () => {
|
||||||
|
if (showWarningPopover) {
|
||||||
|
warningDismissed.current = true;
|
||||||
|
setShowWarningPopover(false);
|
||||||
|
}
|
||||||
|
setOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
// Determine which indicator to show (only one at a time, in priority order)
|
// Determine which indicator to show (only one at a time, in priority order)
|
||||||
const renderIndicator = () => {
|
const renderIndicator = () => {
|
||||||
// Checkmark: sync just completed successfully - highest priority
|
// Checkmark: sync just completed successfully - highest priority
|
||||||
@@ -78,6 +115,12 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
|
{/* Warning popover - shown when purple indicator is visible */}
|
||||||
|
<Popover open={showWarningPopover} modal={false}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<div className="relative">
|
||||||
|
{/* Main Git Sync popover */}
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<Popover open={open} onOpenChange={setOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
@@ -85,6 +128,7 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
|||||||
size="sm"
|
size="sm"
|
||||||
className={cn("size-8 p-0 group relative", className)}
|
className={cn("size-8 p-0 group relative", className)}
|
||||||
aria-label="Sync with Git"
|
aria-label="Sync with Git"
|
||||||
|
onClick={handleButtonClick}
|
||||||
>
|
>
|
||||||
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
||||||
{renderIndicator()}
|
{renderIndicator()}
|
||||||
@@ -98,6 +142,34 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
|||||||
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
|
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
|
</div>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent
|
||||||
|
side="bottom"
|
||||||
|
align="center"
|
||||||
|
className="w-80 pointer-events-none z-40"
|
||||||
|
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||||
|
onInteractOutside={(e) => e.preventDefault()}
|
||||||
|
>
|
||||||
|
<div className="space-y-3 pointer-events-auto">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<AlertTriangle className="size-5 text-primary shrink-0" />
|
||||||
|
<h4 className="font-semibold text-sm">Your project files are not safe</h4>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Your project files are stored in your browser session and could be deleted. Sync with git to back up your project.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
onClick={handleButtonClick}
|
||||||
|
className="w-full"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
Continue
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -50,14 +50,7 @@ export interface DenoDeployProvider extends BaseDeployProvider {
|
|||||||
proxy?: boolean;
|
proxy?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface APKBuilderProvider extends BaseDeployProvider {
|
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
|
||||||
type: 'apkbuilder';
|
|
||||||
buildServerUrl: string;
|
|
||||||
apiKey: string;
|
|
||||||
proxy?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | APKBuilderProvider;
|
|
||||||
|
|
||||||
export interface DeploySettings {
|
export interface DeploySettings {
|
||||||
providers: DeployProvider[];
|
providers: DeployProvider[];
|
||||||
|
|||||||
+44
-2
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
|
|||||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import type { AIMessage } from '@/lib/SessionManager';
|
import type { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||||
import type OpenAI from 'openai';
|
import type OpenAI from 'openai';
|
||||||
import type { Tool } from '@/lib/tools/Tool';
|
import type { Tool } from '@/lib/tools/Tool';
|
||||||
|
|
||||||
@@ -39,12 +39,16 @@ export function useAIChat({
|
|||||||
|
|
||||||
// Split session state into individual variables for efficient updates
|
// Split session state into individual variables for efficient updates
|
||||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||||
|
const [displayMessages, setDisplayMessages] = useState<DisplayMessage[]>([]);
|
||||||
|
const [sessionName, setSessionName] = useState<string>('');
|
||||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||||
const [totalCost, setTotalCost] = useState<number>(0);
|
const [totalCost, setTotalCost] = useState<number>(0);
|
||||||
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
||||||
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
||||||
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
||||||
|
const [hasMoreHistory, setHasMoreHistory] = useState<boolean>(false);
|
||||||
|
const [isLoadingMoreHistory, setIsLoadingMoreHistory] = useState<boolean>(false);
|
||||||
|
|
||||||
const initSession = useCallback(async () => {
|
const initSession = useCallback(async () => {
|
||||||
setIsLoadingHistory(true);
|
setIsLoadingHistory(true);
|
||||||
@@ -53,11 +57,15 @@ export function useAIChat({
|
|||||||
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
||||||
// Initialize individual state variables from existing session
|
// Initialize individual state variables from existing session
|
||||||
setMessages([...session.messages]);
|
setMessages([...session.messages]);
|
||||||
|
setDisplayMessages([...session.displayMessages]);
|
||||||
|
setSessionName(session.sessionName);
|
||||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||||
setIsLoading(session.isLoading);
|
setIsLoading(session.isLoading);
|
||||||
setTotalCost(session.totalCost || 0);
|
setTotalCost(session.totalCost || 0);
|
||||||
setLastInputTokens(session.lastInputTokens || 0);
|
setLastInputTokens(session.lastInputTokens || 0);
|
||||||
setLastFinishReason(session.lastFinishReason ?? null);
|
setLastFinishReason(session.lastFinishReason ?? null);
|
||||||
|
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
|
||||||
|
setIsLoadingMoreHistory(session.isLoadingMoreHistory || false);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingHistory(false);
|
setIsLoadingHistory(false);
|
||||||
}
|
}
|
||||||
@@ -123,6 +131,25 @@ export function useAIChat({
|
|||||||
}
|
}
|
||||||
}, [projectId]);
|
}, [projectId]);
|
||||||
|
|
||||||
|
useSessionSubscription('displayMessageAdded', (updatedProjectId: string, message: DisplayMessage) => {
|
||||||
|
if (updatedProjectId === projectId) {
|
||||||
|
setDisplayMessages(prev => [...prev, message]);
|
||||||
|
}
|
||||||
|
}, [projectId]);
|
||||||
|
|
||||||
|
useSessionSubscription('displayMessagesPrepended', (updatedProjectId: string, newMessages: DisplayMessage[]) => {
|
||||||
|
if (updatedProjectId === projectId) {
|
||||||
|
setDisplayMessages(prev => [...newMessages, ...prev]);
|
||||||
|
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
|
||||||
|
}
|
||||||
|
}, [projectId, sessionManager]);
|
||||||
|
|
||||||
|
useSessionSubscription('loadingMoreHistoryChanged', (updatedProjectId: string, loading: boolean) => {
|
||||||
|
if (updatedProjectId === projectId) {
|
||||||
|
setIsLoadingMoreHistory(loading);
|
||||||
|
}
|
||||||
|
}, [projectId]);
|
||||||
|
|
||||||
// Actions
|
// Actions
|
||||||
const sendMessage = useCallback(async (
|
const sendMessage = useCallback(async (
|
||||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||||
@@ -164,7 +191,13 @@ export function useAIChat({
|
|||||||
const startNewSession = useCallback(async () => {
|
const startNewSession = useCallback(async () => {
|
||||||
await sessionManager.startNewSession(projectId);
|
await sessionManager.startNewSession(projectId);
|
||||||
|
|
||||||
// Reset individual state variables
|
// Get the updated session to retrieve the new session name
|
||||||
|
const session = sessionManager.getSession(projectId);
|
||||||
|
if (session) {
|
||||||
|
setSessionName(session.sessionName);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset only AI prompt state (not display state which is handled via events)
|
||||||
setMessages([]);
|
setMessages([]);
|
||||||
setStreamingMessage(undefined);
|
setStreamingMessage(undefined);
|
||||||
setTotalCost(0);
|
setTotalCost(0);
|
||||||
@@ -177,11 +210,19 @@ export function useAIChat({
|
|||||||
await startNewSession();
|
await startNewSession();
|
||||||
}, [startNewSession]);
|
}, [startNewSession]);
|
||||||
|
|
||||||
|
const loadMoreHistory = useCallback(async () => {
|
||||||
|
await sessionManager.loadOlderSession(projectId);
|
||||||
|
}, [projectId, sessionManager]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
sessionName,
|
||||||
streamingMessage,
|
streamingMessage,
|
||||||
isLoading,
|
isLoading,
|
||||||
isLoadingHistory,
|
isLoadingHistory,
|
||||||
|
hasMoreHistory,
|
||||||
|
isLoadingMoreHistory,
|
||||||
totalCost,
|
totalCost,
|
||||||
lastInputTokens,
|
lastInputTokens,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
@@ -191,6 +232,7 @@ export function useAIChat({
|
|||||||
clearMessages,
|
clearMessages,
|
||||||
startNewSession,
|
startNewSession,
|
||||||
addMessage,
|
addMessage,
|
||||||
|
loadMoreHistory,
|
||||||
isConfigured,
|
isConfigured,
|
||||||
projectId
|
projectId
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
|
|||||||
import { proxyUrl } from '@/lib/proxyUrl';
|
import { proxyUrl } from '@/lib/proxyUrl';
|
||||||
|
|
||||||
export interface OAuthConfig {
|
export interface OAuthConfig {
|
||||||
provider: 'github' | 'netlify' | 'vercel';
|
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
|
||||||
clientId: string;
|
clientId: string;
|
||||||
clientSecret: string;
|
clientSecret: string;
|
||||||
authorizeUrl: string;
|
authorizeUrl: string;
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { useAISettings } from './useAISettings';
|
||||||
|
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||||
|
|
||||||
|
interface OpenRouterTokenResponse {
|
||||||
|
key: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook for OpenRouter OAuth authentication with PKCE.
|
||||||
|
* OpenRouter uses a custom OAuth flow that differs from standard OAuth 2.0.
|
||||||
|
* It uses PKCE without requiring client credentials.
|
||||||
|
*/
|
||||||
|
export function useOpenRouterOAuth() {
|
||||||
|
const { setProvider, isLoading: isSettingsLoading } = useAISettings();
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// OpenRouter doesn't require client credentials - it uses PKCE only
|
||||||
|
const isOAuthConfigured = true;
|
||||||
|
|
||||||
|
// Generate a cryptographically secure random string for PKCE code verifier
|
||||||
|
const generateCodeVerifier = (): string => {
|
||||||
|
const array = new Uint8Array(32);
|
||||||
|
crypto.getRandomValues(array);
|
||||||
|
return btoa(String.fromCharCode(...array))
|
||||||
|
.replace(/\+/g, '-')
|
||||||
|
.replace(/\//g, '_')
|
||||||
|
.replace(/=/g, '');
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create SHA-256 hash of the code verifier for PKCE code challenge
|
||||||
|
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const data = encoder.encode(codeVerifier);
|
||||||
|
const digest = await crypto.subtle.digest('SHA-256', data);
|
||||||
|
return btoa(String.fromCharCode(...new Uint8Array(digest)))
|
||||||
|
.replace(/\+/g, '-')
|
||||||
|
.replace(/\//g, '_')
|
||||||
|
.replace(/=/g, '');
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initiates the OAuth flow by redirecting to OpenRouter's authorization page.
|
||||||
|
*/
|
||||||
|
const initiateOAuth = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
// Generate a random state parameter for security
|
||||||
|
const state = crypto.randomUUID();
|
||||||
|
const storagePrefix = 'openrouter_oauth';
|
||||||
|
|
||||||
|
// Store state for later verification
|
||||||
|
localStorage.setItem(`${storagePrefix}_state`, state);
|
||||||
|
|
||||||
|
// Generate PKCE parameters
|
||||||
|
const codeVerifier = generateCodeVerifier();
|
||||||
|
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||||
|
|
||||||
|
localStorage.setItem(`${storagePrefix}_code_verifier`, codeVerifier);
|
||||||
|
|
||||||
|
// Build authorization URL
|
||||||
|
const redirectUri = window.location.origin + '/oauth/openrouter';
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
callback_url: redirectUri,
|
||||||
|
code_challenge: codeChallenge,
|
||||||
|
code_challenge_method: 'S256',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Redirect to OpenRouter's authorization page
|
||||||
|
window.location.href = `https://openrouter.ai/auth?${params.toString()}`;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to initiate OpenRouter OAuth:', error);
|
||||||
|
setError('Failed to generate PKCE parameters. Please try again.');
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the OAuth callback after the user authorizes the application.
|
||||||
|
* Exchanges the authorization code for an API key.
|
||||||
|
*/
|
||||||
|
const handleCallback = useCallback(async (
|
||||||
|
code: string,
|
||||||
|
_state: string
|
||||||
|
): Promise<boolean> => {
|
||||||
|
setIsLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const storagePrefix = 'openrouter_oauth';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Get PKCE code verifier
|
||||||
|
const codeVerifier = localStorage.getItem(`${storagePrefix}_code_verifier`);
|
||||||
|
if (!codeVerifier) {
|
||||||
|
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up stored values
|
||||||
|
localStorage.removeItem(`${storagePrefix}_state`);
|
||||||
|
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||||
|
|
||||||
|
// Exchange code for API key using OpenRouter's custom endpoint
|
||||||
|
const tokenResponse = await fetch('https://openrouter.ai/api/v1/auth/keys', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
code: code,
|
||||||
|
code_verifier: codeVerifier,
|
||||||
|
code_challenge_method: 'S256',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!tokenResponse.ok) {
|
||||||
|
const errorText = await tokenResponse.text();
|
||||||
|
throw new Error(`OpenRouter token exchange failed: ${tokenResponse.statusText} - ${errorText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenData: OpenRouterTokenResponse = await tokenResponse.json();
|
||||||
|
|
||||||
|
if (!tokenData.key) {
|
||||||
|
throw new Error('No API key received from OpenRouter');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for settings to be initialized before storing
|
||||||
|
if (isSettingsLoading) {
|
||||||
|
throw new Error('Settings not initialized. Please try again.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new OpenRouter provider with the OAuth token
|
||||||
|
const newProvider: AIProvider = {
|
||||||
|
id: 'openrouter',
|
||||||
|
name: 'OpenRouter',
|
||||||
|
baseURL: 'https://openrouter.ai/api/v1',
|
||||||
|
apiKey: tokenData.key,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add or update the OpenRouter provider in settings
|
||||||
|
setProvider(newProvider);
|
||||||
|
|
||||||
|
setIsLoading(false);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('OpenRouter OAuth error:', error);
|
||||||
|
|
||||||
|
// Clean up any remaining OAuth data on error
|
||||||
|
localStorage.removeItem(`${storagePrefix}_state`);
|
||||||
|
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||||
|
|
||||||
|
setError(error instanceof Error ? error.message : 'OAuth authentication failed');
|
||||||
|
setIsLoading(false);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, [setProvider, isSettingsLoading]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
isOAuthConfigured,
|
||||||
|
initiateOAuth,
|
||||||
|
handleCallback,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@@ -52,16 +52,6 @@ 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', [
|
const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||||
shakespeareProjectConfigSchema,
|
shakespeareProjectConfigSchema,
|
||||||
nsiteProjectConfigSchema,
|
nsiteProjectConfigSchema,
|
||||||
@@ -69,7 +59,6 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
|||||||
vercelProjectConfigSchema,
|
vercelProjectConfigSchema,
|
||||||
cloudflareProjectConfigSchema,
|
cloudflareProjectConfigSchema,
|
||||||
denoDeployProjectConfigSchema,
|
denoDeployProjectConfigSchema,
|
||||||
apkBuilderProjectConfigSchema,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const projectDeploySettingsSchema = z.object({
|
const projectDeploySettingsSchema = z.object({
|
||||||
@@ -83,7 +72,6 @@ export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
|
|||||||
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
|
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
|
||||||
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
|
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
|
||||||
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
|
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
|
||||||
export type APKBuilderProjectConfig = z.infer<typeof apkBuilderProjectConfigSchema>;
|
|
||||||
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
|
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
|
||||||
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
|
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
|
||||||
|
|
||||||
|
|||||||
@@ -27,73 +27,6 @@ describe('DotAI', () => {
|
|||||||
dotAI = new DotAI(mockFS, '/test-project');
|
dotAI = new DotAI(mockFS, '/test-project');
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('readLastSessionHistory', () => {
|
|
||||||
it('should return null when history directory does not exist', async () => {
|
|
||||||
// Mock historyDirExists to return false
|
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
|
||||||
|
|
||||||
const result = await dotAI.readLastSessionHistory();
|
|
||||||
expect(result).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return null when no session files exist', async () => {
|
|
||||||
// Mock historyDirExists to return true
|
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
|
||||||
|
|
||||||
// Mock readdir to return empty array
|
|
||||||
vi.mocked(mockFS.readdir).mockResolvedValue([]);
|
|
||||||
|
|
||||||
const result = await dotAI.readLastSessionHistory();
|
|
||||||
expect(result).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return messages and session name from most recent file', async () => {
|
|
||||||
// Mock historyDirExists to return true
|
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
|
||||||
|
|
||||||
// Mock readdir to return session files
|
|
||||||
vi.mocked(mockFS.readdir).mockResolvedValue([
|
|
||||||
'2024-08-24T16-30-45Z-abc.jsonl',
|
|
||||||
'2024-08-24T17-15-22Z-def.jsonl', // This should be the most recent
|
|
||||||
'2024-08-24T15-00-00Z-xyz.jsonl'
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Mock readFile to return JSONL content
|
|
||||||
const mockContent = `{"role":"user","content":"Hello"}
|
|
||||||
{"role":"assistant","content":"Hi there!"}`;
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
|
|
||||||
|
|
||||||
const result = await dotAI.readLastSessionHistory();
|
|
||||||
|
|
||||||
expect(result).not.toBeNull();
|
|
||||||
expect(result?.sessionName).toBe('2024-08-24T17-15-22Z-def');
|
|
||||||
expect(result?.messages).toHaveLength(2);
|
|
||||||
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
|
|
||||||
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle malformed JSON lines gracefully', async () => {
|
|
||||||
// Mock historyDirExists to return true
|
|
||||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
|
||||||
|
|
||||||
// Mock readdir to return session files
|
|
||||||
vi.mocked(mockFS.readdir).mockResolvedValue(['session.jsonl']);
|
|
||||||
|
|
||||||
// Mock readFile to return content with malformed JSON
|
|
||||||
const mockContent = `{"role":"user","content":"Hello"}
|
|
||||||
invalid json line
|
|
||||||
{"role":"assistant","content":"Hi there!"}`;
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
|
|
||||||
|
|
||||||
const result = await dotAI.readLastSessionHistory();
|
|
||||||
|
|
||||||
expect(result).not.toBeNull();
|
|
||||||
expect(result?.messages).toHaveLength(2); // Should skip the malformed line
|
|
||||||
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
|
|
||||||
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('setHistory', () => {
|
describe('setHistory', () => {
|
||||||
it('should create history directory if it does not exist', async () => {
|
it('should create history directory if it does not exist', async () => {
|
||||||
// Mock historyDirExists to return false initially
|
// Mock historyDirExists to return false initially
|
||||||
|
|||||||
+23
-39
@@ -216,35 +216,34 @@ export class DotAI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read the most recent session history
|
* List all session names sorted chronologically (oldest first)
|
||||||
* @returns Object containing messages array and session name, or null if no history found
|
* Fast operation - does not load message content
|
||||||
|
* @returns Array of session names (filenames without .jsonl extension)
|
||||||
*/
|
*/
|
||||||
async readLastSessionHistory(): Promise<{
|
async listSessionNames(): Promise<string[]> {
|
||||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
|
||||||
sessionName: string;
|
|
||||||
} | null> {
|
|
||||||
try {
|
try {
|
||||||
// Check if history directory exists
|
|
||||||
if (!(await this.historyDirExists())) {
|
if (!(await this.historyDirExists())) {
|
||||||
return null;
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the most recent session file
|
|
||||||
try {
|
|
||||||
const files = await this.fs.readdir(this.historyDir);
|
const files = await this.fs.readdir(this.historyDir);
|
||||||
const sessionFiles = files
|
return files
|
||||||
.filter(file => file.endsWith('.jsonl'))
|
.filter(file => file.endsWith('.jsonl'))
|
||||||
.sort()
|
.map(file => file.replace('.jsonl', ''))
|
||||||
.reverse(); // Most recent first
|
.sort(); // Chronological order (oldest first) - filenames contain timestamps
|
||||||
|
} catch {
|
||||||
if (sessionFiles.length === 0) {
|
return [];
|
||||||
return null;
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const latestSessionFile = sessionFiles[0];
|
/**
|
||||||
const sessionPath = join(this.historyDir, latestSessionFile);
|
* Read messages for a single session
|
||||||
|
* @param sessionName The session name (filename without .jsonl)
|
||||||
|
* @returns Array of messages, or empty array if session not found
|
||||||
|
*/
|
||||||
|
async readSessionHistory(sessionName: string): Promise<OpenAI.Chat.Completions.ChatCompletionMessageParam[]> {
|
||||||
try {
|
try {
|
||||||
|
const sessionPath = join(this.historyDir, sessionName + '.jsonl');
|
||||||
const content = await this.fs.readFile(sessionPath, 'utf8');
|
const content = await this.fs.readFile(sessionPath, 'utf8');
|
||||||
const lines = content.trim().split('\n').filter(line => line.trim());
|
const lines = content.trim().split('\n').filter(line => line.trim());
|
||||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||||
@@ -253,29 +252,14 @@ export class DotAI {
|
|||||||
try {
|
try {
|
||||||
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||||
messages.push(message);
|
messages.push(message);
|
||||||
} catch (parseError) {
|
} catch {
|
||||||
console.warn('Failed to parse message from history:', parseError);
|
// Skip malformed lines
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return session name without .jsonl extension
|
return messages;
|
||||||
const sessionName = latestSessionFile.replace('.jsonl', '');
|
} catch {
|
||||||
|
return [];
|
||||||
return {
|
|
||||||
messages,
|
|
||||||
sessionName
|
|
||||||
};
|
|
||||||
} catch (readError) {
|
|
||||||
console.warn('Failed to read session file:', readError);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
} catch (readdirError) {
|
|
||||||
console.warn('Failed to read history directory:', readdirError);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Failed to read last session history:', error);
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+137
-21
@@ -24,12 +24,20 @@ export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
|||||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** AIMessage with session tracking for UI display */
|
||||||
|
export type DisplayMessage = AIMessage & {
|
||||||
|
sessionId?: string; // Session identifier for grouping messages in UI
|
||||||
|
};
|
||||||
|
|
||||||
export interface SessionState {
|
export interface SessionState {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||||
customTools: Record<string, Tool<unknown>>;
|
customTools: Record<string, Tool<unknown>>;
|
||||||
maxSteps?: number;
|
maxSteps?: number;
|
||||||
messages: AIMessage[];
|
messages: AIMessage[]; // Current session messages (sent to AI)
|
||||||
|
displayMessages: DisplayMessage[]; // All messages from all sessions (for UI, with sessionId)
|
||||||
|
availableSessionNames: string[]; // All session names (for lazy loading)
|
||||||
|
loadedSessionCount: number; // How many sessions loaded from the end
|
||||||
streamingMessage?: {
|
streamingMessage?: {
|
||||||
role: 'assistant';
|
role: 'assistant';
|
||||||
content: string;
|
content: string;
|
||||||
@@ -37,6 +45,7 @@ export interface SessionState {
|
|||||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||||
};
|
};
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
isLoadingMoreHistory: boolean; // Loading older sessions
|
||||||
sessionName: string;
|
sessionName: string;
|
||||||
lastActivity: Date;
|
lastActivity: Date;
|
||||||
abortController?: AbortController;
|
abortController?: AbortController;
|
||||||
@@ -50,8 +59,11 @@ export interface SessionManagerEvents {
|
|||||||
sessionCreated: (projectId: string) => void;
|
sessionCreated: (projectId: string) => void;
|
||||||
sessionDeleted: (projectId: string) => void;
|
sessionDeleted: (projectId: string) => void;
|
||||||
messageAdded: (projectId: string, message: AIMessage) => void;
|
messageAdded: (projectId: string, message: AIMessage) => void;
|
||||||
|
displayMessageAdded: (projectId: string, message: DisplayMessage) => void;
|
||||||
|
displayMessagesPrepended: (projectId: string, messages: DisplayMessage[]) => void;
|
||||||
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||||
|
loadingMoreHistoryChanged: (projectId: string, isLoading: boolean) => void;
|
||||||
costUpdated: (projectId: string, totalCost: number) => void;
|
costUpdated: (projectId: string, totalCost: number) => void;
|
||||||
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
||||||
fileChanged: (projectId: string, filePath: string) => void;
|
fileChanged: (projectId: string, filePath: string) => void;
|
||||||
@@ -97,7 +109,7 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new session for a project
|
* Create a new session for a project (lazy loading - only loads most recent session)
|
||||||
*/
|
*/
|
||||||
async loadSession(
|
async loadSession(
|
||||||
projectId: string,
|
projectId: string,
|
||||||
@@ -105,18 +117,39 @@ export class SessionManager {
|
|||||||
customTools: Record<string, Tool<unknown>>,
|
customTools: Record<string, Tool<unknown>>,
|
||||||
maxSteps?: number
|
maxSteps?: number
|
||||||
): Promise<SessionState> {
|
): Promise<SessionState> {
|
||||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
const messages: AIMessage[] = [];
|
||||||
|
const displayMessages: DisplayMessage[] = [];
|
||||||
let sessionName = DotAI.generateSessionName();
|
let sessionName = DotAI.generateSessionName();
|
||||||
|
let availableSessionNames: string[] = [];
|
||||||
|
let loadedSessionCount = 0;
|
||||||
let lastFinishReason: string | null | undefined;
|
let lastFinishReason: string | null | undefined;
|
||||||
|
|
||||||
// Try to load existing history
|
// Try to load existing history (lazy - only load last session)
|
||||||
try {
|
try {
|
||||||
const config = this.getConfig();
|
const config = this.getConfig();
|
||||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||||
const lastSession = await dotAI.readLastSessionHistory();
|
|
||||||
if (lastSession) {
|
// Get all available session names (fast - no content loading)
|
||||||
messages = lastSession.messages;
|
availableSessionNames = await dotAI.listSessionNames();
|
||||||
sessionName = lastSession.sessionName;
|
|
||||||
|
if (availableSessionNames.length > 0) {
|
||||||
|
// Only load the most recent session
|
||||||
|
const lastSessionName = availableSessionNames[availableSessionNames.length - 1];
|
||||||
|
const lastSessionMessages = await dotAI.readSessionHistory(lastSessionName);
|
||||||
|
|
||||||
|
if (lastSessionMessages.length > 0) {
|
||||||
|
// Add messages with sessionId annotation
|
||||||
|
for (const msg of lastSessionMessages) {
|
||||||
|
displayMessages.push({
|
||||||
|
...msg as AIMessage,
|
||||||
|
sessionId: lastSessionName,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
messages.push(...lastSessionMessages as AIMessage[]);
|
||||||
|
sessionName = lastSessionName;
|
||||||
|
loadedSessionCount = 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load last finish reason
|
// Load last finish reason
|
||||||
@@ -131,22 +164,34 @@ export class SessionManager {
|
|||||||
customTools,
|
customTools,
|
||||||
maxSteps,
|
maxSteps,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
|
isLoadingMoreHistory: false,
|
||||||
lastActivity: new Date(),
|
lastActivity: new Date(),
|
||||||
totalCost: 0,
|
totalCost: 0,
|
||||||
lastInputTokens: 0,
|
lastInputTokens: 0,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
...this.sessions.get(projectId),
|
...this.sessions.get(projectId),
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
availableSessionNames,
|
||||||
|
loadedSessionCount,
|
||||||
sessionName,
|
sessionName,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Update session configuration
|
// Update session configuration
|
||||||
session.projectId = projectId;
|
session.projectId = projectId;
|
||||||
session.tools = tools;
|
session.tools = tools;
|
||||||
|
|
||||||
session.customTools = customTools;
|
session.customTools = customTools;
|
||||||
session.maxSteps = maxSteps;
|
session.maxSteps = maxSteps;
|
||||||
|
|
||||||
|
// Update messages from loaded history if not already set by an existing session
|
||||||
|
if (!this.sessions.has(projectId)) {
|
||||||
|
session.messages = messages;
|
||||||
|
session.displayMessages = displayMessages;
|
||||||
|
session.availableSessionNames = availableSessionNames;
|
||||||
|
session.loadedSessionCount = loadedSessionCount;
|
||||||
|
session.sessionName = sessionName;
|
||||||
|
}
|
||||||
|
|
||||||
this.sessions.set(projectId, session);
|
this.sessions.set(projectId, session);
|
||||||
|
|
||||||
this.emit('sessionCreated', projectId);
|
this.emit('sessionCreated', projectId);
|
||||||
@@ -187,11 +232,69 @@ export class SessionManager {
|
|||||||
const session = this.sessions.get(projectId);
|
const session = this.sessions.get(projectId);
|
||||||
if (!session) return;
|
if (!session) return;
|
||||||
|
|
||||||
|
// Add to current session messages (for AI prompts)
|
||||||
session.messages.push(message);
|
session.messages.push(message);
|
||||||
|
|
||||||
|
// Also add to display messages with session ID annotation (for UI)
|
||||||
|
const displayMessage: DisplayMessage = { ...message, sessionId: session.sessionName };
|
||||||
|
session.displayMessages.push(displayMessage);
|
||||||
|
|
||||||
session.lastActivity = new Date();
|
session.lastActivity = new Date();
|
||||||
|
|
||||||
await this.saveSessionHistory(projectId);
|
await this.saveSessionHistory(projectId);
|
||||||
this.emit('messageAdded', projectId, message);
|
this.emit('messageAdded', projectId, message);
|
||||||
|
this.emit('displayMessageAdded', projectId, displayMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if there are more historical sessions to load
|
||||||
|
*/
|
||||||
|
hasMoreHistory(projectId: string): boolean {
|
||||||
|
const session = this.sessions.get(projectId);
|
||||||
|
if (!session) return false;
|
||||||
|
return session.loadedSessionCount < session.availableSessionNames.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the next older session and prepend to displayMessages
|
||||||
|
*/
|
||||||
|
async loadOlderSession(projectId: string): Promise<void> {
|
||||||
|
const session = this.sessions.get(projectId);
|
||||||
|
if (!session || !this.hasMoreHistory(projectId) || session.isLoadingMoreHistory) return;
|
||||||
|
|
||||||
|
session.isLoadingMoreHistory = true;
|
||||||
|
this.emit('loadingMoreHistoryChanged', projectId, true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const config = this.getConfig();
|
||||||
|
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||||
|
|
||||||
|
// Get the next older session (counting from the end)
|
||||||
|
const nextIndex = session.availableSessionNames.length - session.loadedSessionCount - 1;
|
||||||
|
if (nextIndex < 0) return;
|
||||||
|
|
||||||
|
const olderSessionName = session.availableSessionNames[nextIndex];
|
||||||
|
const olderMessages = await dotAI.readSessionHistory(olderSessionName);
|
||||||
|
|
||||||
|
if (olderMessages.length > 0) {
|
||||||
|
// Create display messages with sessionId
|
||||||
|
const newDisplayMessages: DisplayMessage[] = olderMessages.map(msg => ({
|
||||||
|
...msg as AIMessage,
|
||||||
|
sessionId: olderSessionName,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Prepend to displayMessages
|
||||||
|
session.displayMessages = [...newDisplayMessages, ...session.displayMessages];
|
||||||
|
session.loadedSessionCount++;
|
||||||
|
|
||||||
|
this.emit('displayMessagesPrepended', projectId, newDisplayMessages);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to load older session:', error);
|
||||||
|
} finally {
|
||||||
|
session.isLoadingMoreHistory = false;
|
||||||
|
this.emit('loadingMoreHistoryChanged', projectId, false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -450,7 +553,7 @@ export class SessionManager {
|
|||||||
|
|
||||||
let accumulatedContent = '';
|
let accumulatedContent = '';
|
||||||
let accumulatedReasoningContent = '';
|
let accumulatedReasoningContent = '';
|
||||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
const accumulatedToolCalls: Map<number, OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall> = new Map();
|
||||||
let finishReason: string | null = null;
|
let finishReason: string | null = null;
|
||||||
|
|
||||||
// Process the stream
|
// Process the stream
|
||||||
@@ -491,20 +594,29 @@ export class SessionManager {
|
|||||||
const toolCallDelta = delta.tool_calls[i];
|
const toolCallDelta = delta.tool_calls[i];
|
||||||
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
||||||
|
|
||||||
accumulatedToolCalls[index] ??= {
|
let toolCall = accumulatedToolCalls.get(index);
|
||||||
|
|
||||||
|
if (!toolCall) {
|
||||||
|
toolCall = {
|
||||||
id: '',
|
id: '',
|
||||||
type: 'function',
|
type: 'function',
|
||||||
function: { name: '', arguments: '' }
|
function: { name: '', arguments: '' },
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const toolCall = accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
|
||||||
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
|
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
|
||||||
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
|
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
|
||||||
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
|
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
|
||||||
|
|
||||||
|
accumulatedToolCalls.set(index, toolCall);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session.streamingMessage) {
|
if (session.streamingMessage && accumulatedToolCalls.size > 0) {
|
||||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
const sortedToolCalls = [...accumulatedToolCalls.entries()]
|
||||||
|
.sort((a, b) => a[0] - b[0])
|
||||||
|
.map(entry => entry[1]);
|
||||||
|
|
||||||
|
session.streamingMessage.tool_calls = sortedToolCalls;
|
||||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -528,7 +640,7 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fix tool calls with empty arguments or names
|
// Fix tool calls with empty arguments or names
|
||||||
for (const toolCall of accumulatedToolCalls) {
|
for (const toolCall of accumulatedToolCalls.values()) {
|
||||||
if (toolCall.type === 'function') {
|
if (toolCall.type === 'function') {
|
||||||
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
||||||
|
|
||||||
@@ -549,7 +661,7 @@ export class SessionManager {
|
|||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: accumulatedContent,
|
content: accumulatedContent,
|
||||||
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
|
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
|
||||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
...(accumulatedToolCalls.size > 0 && { tool_calls: [...accumulatedToolCalls.values()] })
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check if the assistant message is empty (no content, reasoning, or tool calls)
|
// Check if the assistant message is empty (no content, reasoning, or tool calls)
|
||||||
@@ -575,8 +687,8 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handle tool calls
|
// Handle tool calls
|
||||||
if (accumulatedToolCalls?.length) {
|
if (accumulatedToolCalls?.size) {
|
||||||
for (const toolCall of accumulatedToolCalls) {
|
for (const toolCall of accumulatedToolCalls.values()) {
|
||||||
if (toolCall.type !== 'function') continue;
|
if (toolCall.type !== 'function') continue;
|
||||||
|
|
||||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||||
@@ -690,7 +802,7 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start a new session (clear messages but keep configuration)
|
* Start a new session (clear AI messages but keep display history)
|
||||||
*/
|
*/
|
||||||
async startNewSession(projectId: string): Promise<void> {
|
async startNewSession(projectId: string): Promise<void> {
|
||||||
const session = this.sessions.get(projectId);
|
const session = this.sessions.get(projectId);
|
||||||
@@ -698,9 +810,13 @@ export class SessionManager {
|
|||||||
|
|
||||||
this.stopGeneration(projectId);
|
this.stopGeneration(projectId);
|
||||||
|
|
||||||
|
// Generate new session name - new messages will automatically get this sessionId
|
||||||
|
const newSessionName = DotAI.generateSessionName();
|
||||||
|
|
||||||
|
// Clear only the AI prompt messages (not display messages)
|
||||||
session.messages = [];
|
session.messages = [];
|
||||||
session.streamingMessage = undefined;
|
session.streamingMessage = undefined;
|
||||||
session.sessionName = DotAI.generateSessionName();
|
session.sessionName = newSessionName;
|
||||||
session.lastActivity = new Date();
|
session.lastActivity = new Date();
|
||||||
session.totalCost = 0;
|
session.totalCost = 0;
|
||||||
session.lastInputTokens = 0;
|
session.lastInputTokens = 0;
|
||||||
|
|||||||
+39
-2
@@ -58,10 +58,36 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
|||||||
= openai.chat.completions.create.bind(openai.chat.completions);
|
= openai.chat.completions.create.bind(openai.chat.completions);
|
||||||
|
|
||||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||||
// OpenRouter usage accounting
|
// OpenRouter-specific hacks
|
||||||
|
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||||
|
// Usage accounting field to get token usage and cost per request
|
||||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||||
if (provider.id === 'openrouter') {
|
|
||||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||||
|
|
||||||
|
// Prompt caching for Claude models
|
||||||
|
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||||
|
if (body.model.startsWith("anthropic/")) {
|
||||||
|
// First normalize the message history to use content blocks
|
||||||
|
body.messages = structuredClone(body.messages);
|
||||||
|
body.messages = body.messages.map((m) => {
|
||||||
|
if (m.role !== "function" && typeof m.content === "string") {
|
||||||
|
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||||
|
} else {
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||||
|
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||||
|
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||||
|
|
||||||
|
if (systemMessage) {
|
||||||
|
addCacheControl(systemMessage);
|
||||||
|
}
|
||||||
|
for (const msg of lastTwoMessages) {
|
||||||
|
addCacheControl(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return createCompletion(body, options);
|
return createCompletion(body, options);
|
||||||
@@ -69,3 +95,14 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
|||||||
|
|
||||||
return openai;
|
return openai;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
||||||
|
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
||||||
|
if (Array.isArray(msg.content)) {
|
||||||
|
const lastTextBlock = msg.content.findLast((b) => b.type === "text");
|
||||||
|
if (lastTextBlock) {
|
||||||
|
(lastTextBlock as { cache_control?: { type: "ephemeral" } })
|
||||||
|
.cache_control = { type: "ephemeral" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -23,6 +23,14 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
|||||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||||
tosURL: "https://openrouter.ai/terms",
|
tosURL: "https://openrouter.ai/terms",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "opencode",
|
||||||
|
name: "OpenCode Zen",
|
||||||
|
baseURL: "https://opencode.ai/zen/v1",
|
||||||
|
apiKeysURL: "https://opencode.ai/auth",
|
||||||
|
tosURL: "https://opencode.ai/legal/terms-of-service",
|
||||||
|
proxy: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "ppq",
|
id: "ppq",
|
||||||
name: "PayPerQ",
|
name: "PayPerQ",
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
export * from './signing';
|
|
||||||
export * from './keystore';
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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);
|
|
||||||
}
|
|
||||||
@@ -1,905 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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,12 +129,6 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
|
|||||||
baseDomain: z.string().optional(),
|
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', [
|
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
|
||||||
shakespeareDeployProviderSchema,
|
shakespeareDeployProviderSchema,
|
||||||
netlifyProviderSchema,
|
netlifyProviderSchema,
|
||||||
@@ -142,7 +136,6 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
|
|||||||
nsiteProviderSchema,
|
nsiteProviderSchema,
|
||||||
cloudflareProviderSchema,
|
cloudflareProviderSchema,
|
||||||
denoDeployProviderSchema,
|
denoDeployProviderSchema,
|
||||||
apkBuilderProviderSchema,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const deploySettingsSchema = z.object({
|
const deploySettingsSchema = z.object({
|
||||||
|
|||||||
@@ -1,203 +0,0 @@
|
|||||||
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,4 +5,3 @@ export * from './VercelAdapter';
|
|||||||
export * from './NsiteAdapter';
|
export * from './NsiteAdapter';
|
||||||
export * from './CloudflareAdapter';
|
export * from './CloudflareAdapter';
|
||||||
export * from './DenoDeployAdapter';
|
export * from './DenoDeployAdapter';
|
||||||
export * from './APKBuilderAdapter';
|
|
||||||
+1
-43
@@ -75,50 +75,9 @@ export interface DenoDeployConfig {
|
|||||||
corsProxy?: string;
|
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 {
|
export interface PresetDeployProvider {
|
||||||
id: string;
|
id: string;
|
||||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder';
|
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
|
||||||
name: string;
|
name: string;
|
||||||
description: string;
|
description: string;
|
||||||
baseURL?: string;
|
baseURL?: string;
|
||||||
@@ -129,6 +88,5 @@ export interface PresetDeployProvider {
|
|||||||
accountIdURL?: string;
|
accountIdURL?: string;
|
||||||
organizationIdLabel?: string;
|
organizationIdLabel?: string;
|
||||||
organizationIdURL?: string;
|
organizationIdURL?: string;
|
||||||
buildServerUrlLabel?: string;
|
|
||||||
proxy?: boolean;
|
proxy?: boolean;
|
||||||
}
|
}
|
||||||
@@ -60,14 +60,4 @@ export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
|
|||||||
organizationIdURL: 'https://dash.deno.com/orgs',
|
organizationIdURL: 'https://dash.deno.com/orgs',
|
||||||
proxy: true,
|
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) {
|
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
|
||||||
this.proxy = proxy;
|
this.proxy = proxy;
|
||||||
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
|
this.fetch = fetch ?? globalThis.fetch;
|
||||||
}
|
}
|
||||||
|
|
||||||
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
|
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
|
||||||
|
|||||||
@@ -1,117 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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,
|
UnzipCommand,
|
||||||
WcCommand,
|
WcCommand,
|
||||||
WhoamiCommand,
|
WhoamiCommand,
|
||||||
WhichCommand,
|
WhichCommand
|
||||||
} from "../commands";
|
} from "../commands";
|
||||||
|
|
||||||
interface ShellToolParams {
|
interface ShellToolParams {
|
||||||
|
|||||||
+7
-18
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Anonymous",
|
"anonymous": "Anonymous",
|
||||||
"logIn": "Log in",
|
"logIn": "Log in",
|
||||||
"signUp": "Sign up",
|
"signUp": "Sign up",
|
||||||
|
"newChat": "New Chat",
|
||||||
|
"loadOlderMessages": "Load older messages",
|
||||||
"preferencesDescription": "Manage your general application preferences and appearance settings.",
|
"preferencesDescription": "Manage your general application preferences and appearance settings.",
|
||||||
"theme": "Theme",
|
"theme": "Theme",
|
||||||
"themeDescription": "Choose between light, dark, or system theme preference.",
|
"themeDescription": "Choose between light, dark, or system theme preference.",
|
||||||
@@ -54,12 +56,9 @@
|
|||||||
"showcaseModerator": "Showcase Moderator",
|
"showcaseModerator": "Showcase Moderator",
|
||||||
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
|
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
|
||||||
"filesystemPaths": "Filesystem Paths",
|
"filesystemPaths": "Filesystem Paths",
|
||||||
"projectsDirectory": "Projects Directory",
|
"projectsDirectory": "Projects",
|
||||||
"projectsDirectoryDescription": "Filesystem path where projects are stored",
|
"configDirectory": "Config",
|
||||||
"configDirectory": "Config Directory",
|
"temporaryDirectory": "Temporary",
|
||||||
"configDirectoryDescription": "Filesystem path where configuration files are stored",
|
|
||||||
"temporaryDirectory": "Temporary Directory",
|
|
||||||
"temporaryDirectoryDescription": "Filesystem path for temporary files",
|
|
||||||
"sentryDsn": "Sentry DSN",
|
"sentryDsn": "Sentry DSN",
|
||||||
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
||||||
"shareErrorReports": "Share error reports",
|
"shareErrorReports": "Share error reports",
|
||||||
@@ -484,8 +483,7 @@
|
|||||||
"skills": "Skills",
|
"skills": "Skills",
|
||||||
"noSkillsFound": "No skills found in this plugin.",
|
"noSkillsFound": "No skills found in this plugin.",
|
||||||
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
||||||
"pluginsDirectory": "Plugins Directory",
|
"pluginsDirectory": "Plugins",
|
||||||
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
|
|
||||||
"discoverPlugins": "Discover Plugins",
|
"discoverPlugins": "Discover Plugins",
|
||||||
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
|
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
|
||||||
"searchPlugins": "Search plugins...",
|
"searchPlugins": "Search plugins...",
|
||||||
@@ -526,21 +524,12 @@
|
|||||||
"discoveringTools": "Discovering tools...",
|
"discoveringTools": "Discovering tools...",
|
||||||
"toolsDiscovered": "{{count}} tool(s) discovered",
|
"toolsDiscovered": "{{count}} tool(s) discovered",
|
||||||
"toolDiscoveryFailed": "Failed to discover tools from this server",
|
"toolDiscoveryFailed": "Failed to discover tools from this server",
|
||||||
"filesystemPaths": "Filesystem Paths",
|
|
||||||
"projectsDirectory": "Projects Directory",
|
|
||||||
"projectsDirectoryDescription": "Directory where projects are stored in the virtual filesystem.",
|
|
||||||
"configDirectory": "Config Directory",
|
|
||||||
"configDirectoryDescription": "Directory where configuration files are stored in the virtual filesystem.",
|
|
||||||
"temporaryDirectory": "Temporary Directory",
|
|
||||||
"temporaryDirectoryDescription": "Directory for temporary files in the virtual filesystem.",
|
|
||||||
"deleting": "Deleting...",
|
"deleting": "Deleting...",
|
||||||
"modified": "Modified",
|
|
||||||
"restoreToDefault": "Restore to default",
|
"restoreToDefault": "Restore to default",
|
||||||
"restoredToDefault": "Restored to Default",
|
"restoredToDefault": "Restored to Default",
|
||||||
"templateUpdateFailed": "Template Update Failed",
|
"templateUpdateFailed": "Template Update Failed",
|
||||||
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
|
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
|
||||||
"templatesDirectory": "Templates Directory",
|
"templatesDirectory": "Templates",
|
||||||
"templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.",
|
|
||||||
"terminal": "Terminal",
|
"terminal": "Terminal",
|
||||||
"templateName": "Template Name",
|
"templateName": "Template Name",
|
||||||
"templateDescription": "Description",
|
"templateDescription": "Description",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Maras Suna",
|
"anonymous": "Maras Suna",
|
||||||
"logIn": "Shiga",
|
"logIn": "Shiga",
|
||||||
"signUp": "Yi Rajista",
|
"signUp": "Yi Rajista",
|
||||||
|
"newChat": "Sabon Tattaunawa",
|
||||||
|
"loadOlderMessages": "Loda saƙonni masu tsufa",
|
||||||
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
|
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
|
||||||
"theme": "Jigogi",
|
"theme": "Jigogi",
|
||||||
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Onye na-amaghị aha",
|
"anonymous": "Onye na-amaghị aha",
|
||||||
"logIn": "Banye",
|
"logIn": "Banye",
|
||||||
"signUp": "Debanye aha",
|
"signUp": "Debanye aha",
|
||||||
|
"newChat": "Nkata Ọhụrụ",
|
||||||
|
"loadOlderMessages": "Bulite ozi ochie",
|
||||||
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
|
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
|
||||||
"theme": "Isiokwu",
|
"theme": "Isiokwu",
|
||||||
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Anônimo",
|
"anonymous": "Anônimo",
|
||||||
"logIn": "Entrar",
|
"logIn": "Entrar",
|
||||||
"signUp": "Cadastrar",
|
"signUp": "Cadastrar",
|
||||||
|
"newChat": "Nova Conversa",
|
||||||
|
"loadOlderMessages": "Carregar mensagens anteriores",
|
||||||
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
|
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
|
||||||
"theme": "Tema",
|
"theme": "Tema",
|
||||||
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Alainidamọ",
|
"anonymous": "Alainidamọ",
|
||||||
"logIn": "Wọle",
|
"logIn": "Wọle",
|
||||||
"signUp": "Forukọsilẹ",
|
"signUp": "Forukọsilẹ",
|
||||||
|
"newChat": "Ọrọ Tuntun",
|
||||||
|
"loadOlderMessages": "Gbe awọn ifiranṣẹ atijọ",
|
||||||
"preferencesDescription": "Ṣakoso awọn ayanfẹ ohun elo rẹ ati awọn eto iwoye.",
|
"preferencesDescription": "Ṣakoso awọn ayanfẹ ohun elo rẹ ati awọn eto iwoye.",
|
||||||
"theme": "Akori",
|
"theme": "Akori",
|
||||||
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "匿名",
|
"anonymous": "匿名",
|
||||||
"logIn": "登录",
|
"logIn": "登录",
|
||||||
"signUp": "注册",
|
"signUp": "注册",
|
||||||
|
"newChat": "新对话",
|
||||||
|
"loadOlderMessages": "加载更早的消息",
|
||||||
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
|
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
|
||||||
"theme": "主题",
|
"theme": "主题",
|
||||||
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { CreditsBadge } from '@/components/CreditsBadge';
|
|||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
|
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
|
||||||
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
|
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
|
||||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||||
@@ -45,6 +46,7 @@ export function AISettings() {
|
|||||||
const { settings, updateSettings, setProvider, removeProvider, setProviders, isLoading } = useAISettings();
|
const { settings, updateSettings, setProvider, removeProvider, setProviders, isLoading } = useAISettings();
|
||||||
const { user } = useCurrentUser();
|
const { user } = useCurrentUser();
|
||||||
const { config, defaultConfig, updateConfig } = useAppContext();
|
const { config, defaultConfig, updateConfig } = useAppContext();
|
||||||
|
const openRouterOAuth = useOpenRouterOAuth();
|
||||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||||
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
||||||
|
|
||||||
@@ -54,6 +56,7 @@ export function AISettings() {
|
|||||||
const [selectedPreset, setSelectedPreset] = useState<PresetProvider | null>(null);
|
const [selectedPreset, setSelectedPreset] = useState<PresetProvider | null>(null);
|
||||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||||
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
|
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
|
||||||
|
const [forceManualEntry, setForceManualEntry] = useState(false);
|
||||||
|
|
||||||
// Drag and drop sensors
|
// Drag and drop sensors
|
||||||
const sensors = useSensors(
|
const sensors = useSensors(
|
||||||
@@ -256,9 +259,18 @@ export function AISettings() {
|
|||||||
{selectedPreset && (
|
{selectedPreset && (
|
||||||
<AddAIProviderDialog
|
<AddAIProviderDialog
|
||||||
open={addDialogOpen}
|
open={addDialogOpen}
|
||||||
onOpenChange={setAddDialogOpen}
|
onOpenChange={(open) => {
|
||||||
|
setAddDialogOpen(open);
|
||||||
|
if (!open) {
|
||||||
|
// Reset force manual entry when dialog closes
|
||||||
|
setForceManualEntry(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
preset={selectedPreset}
|
preset={selectedPreset}
|
||||||
isLoggedIntoNostr={!!user}
|
isLoggedIntoNostr={!!user}
|
||||||
|
oauthHook={selectedPreset.id === 'openrouter' ? openRouterOAuth : null}
|
||||||
|
forceManualEntry={forceManualEntry}
|
||||||
|
onSetForceManualEntry={setForceManualEntry}
|
||||||
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
|
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import type { PresetDeployProvider } from '@/lib/deploy/types';
|
|||||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
||||||
import { AddProviderDialog } from '@/components/AddProviderDialog';
|
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||||
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
|
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
|
||||||
import {
|
import {
|
||||||
DndContext,
|
DndContext,
|
||||||
@@ -181,7 +181,7 @@ export function DeploySettings() {
|
|||||||
setAddDialogOpen(true);
|
setAddDialogOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => {
|
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string) => {
|
||||||
// For Shakespeare, just check if user is logged in
|
// For Shakespeare, just check if user is logged in
|
||||||
if (preset.requiresNostr && !user) {
|
if (preset.requiresNostr && !user) {
|
||||||
return;
|
return;
|
||||||
@@ -260,18 +260,6 @@ export function DeploySettings() {
|
|||||||
organizationId: organizationId.trim(),
|
organizationId: organizationId.trim(),
|
||||||
...(preset.proxy && { proxy: true }),
|
...(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 {
|
} else {
|
||||||
return; // Unknown type
|
return; // Unknown type
|
||||||
}
|
}
|
||||||
@@ -290,8 +278,6 @@ export function DeploySettings() {
|
|||||||
|
|
||||||
const handleRemoveProvider = (index: number) => {
|
const handleRemoveProvider = (index: number) => {
|
||||||
removeProvider(index);
|
removeProvider(index);
|
||||||
setDialogOpen(false);
|
|
||||||
setSelectedProviderIndex(null);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUpdateProvider = (index: number, provider: DeployProvider) => {
|
const handleUpdateProvider = (index: number, provider: DeployProvider) => {
|
||||||
@@ -398,7 +384,7 @@ export function DeploySettings() {
|
|||||||
|
|
||||||
{/* Add Preset Provider Dialog */}
|
{/* Add Preset Provider Dialog */}
|
||||||
{selectedPreset && (
|
{selectedPreset && (
|
||||||
<AddProviderDialog
|
<AddDeployProviderDialog
|
||||||
open={addDialogOpen}
|
open={addDialogOpen}
|
||||||
onOpenChange={setAddDialogOpen}
|
onOpenChange={setAddDialogOpen}
|
||||||
preset={selectedPreset}
|
preset={selectedPreset}
|
||||||
@@ -411,8 +397,8 @@ export function DeploySettings() {
|
|||||||
onSetForceManualEntry={(force) =>
|
onSetForceManualEntry={(force) =>
|
||||||
setForceManualEntry(prev => ({ ...prev, [selectedPreset.id]: force }))
|
setForceManualEntry(prev => ({ ...prev, [selectedPreset.id]: force }))
|
||||||
}
|
}
|
||||||
onAdd={(apiKey, accountId, organizationId, buildServerUrl) =>
|
onAdd={(apiKey, accountId, organizationId) =>
|
||||||
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId, buildServerUrl)
|
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||||
|
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
|
||||||
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Bot } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function OpenRouterOAuth() {
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { handleCallback } = useOpenRouterOAuth();
|
||||||
|
const { isLoading: isSettingsLoading } = useAISettings();
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Wait for AI settings to be initialized
|
||||||
|
if (isSettingsLoading) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const code = searchParams.get('code');
|
||||||
|
const state = searchParams.get('state');
|
||||||
|
const error = searchParams.get('error');
|
||||||
|
const errorDescription = searchParams.get('error_description');
|
||||||
|
const storedCodeVerifier = localStorage.getItem('openrouter_oauth_code_verifier');
|
||||||
|
|
||||||
|
// Handle OAuth errors
|
||||||
|
if (error) {
|
||||||
|
toast({
|
||||||
|
title: "OpenRouter OAuth Error",
|
||||||
|
description: errorDescription || error,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
navigate('/settings/ai');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle successful OAuth callback
|
||||||
|
if (code && storedCodeVerifier) {
|
||||||
|
handleCallback(code, state || '').then((success) => {
|
||||||
|
if (success) {
|
||||||
|
toast({
|
||||||
|
title: "OpenRouter Connected",
|
||||||
|
description: "Successfully connected to OpenRouter. You can now use OpenRouter models.",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
toast({
|
||||||
|
title: "Connection Failed",
|
||||||
|
description: "Failed to connect to OpenRouter. Please try again.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Always redirect to AI settings after handling the callback
|
||||||
|
navigate('/settings/ai');
|
||||||
|
});
|
||||||
|
} else if (code && !storedCodeVerifier) {
|
||||||
|
// Missing code verifier - likely an incomplete PKCE flow
|
||||||
|
toast({
|
||||||
|
title: "Authentication Error",
|
||||||
|
description: "OAuth flow is incomplete. Please try connecting to OpenRouter again.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
// Clean up any remaining OAuth data
|
||||||
|
localStorage.removeItem('openrouter_oauth_state');
|
||||||
|
localStorage.removeItem('openrouter_oauth_code_verifier');
|
||||||
|
navigate('/settings/ai');
|
||||||
|
} else {
|
||||||
|
// No code parameter - redirect to AI settings
|
||||||
|
navigate('/settings/ai');
|
||||||
|
}
|
||||||
|
}, [searchParams, handleCallback, toast, navigate, isSettingsLoading]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardContent className="py-12 px-8 text-center">
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<Bot className="h-12 w-12 text-primary" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h1 className="text-xl font-semibold">Connecting to OpenRouter</h1>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Processing your OpenRouter authentication...
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -257,6 +257,7 @@ export function SystemSettings() {
|
|||||||
icon={Settings}
|
icon={Settings}
|
||||||
titleKey="systemSettings"
|
titleKey="systemSettings"
|
||||||
descriptionKey="systemSettingsDescription"
|
descriptionKey="systemSettingsDescription"
|
||||||
|
className="space-y-2"
|
||||||
>
|
>
|
||||||
{/* Service Worker Configuration */}
|
{/* Service Worker Configuration */}
|
||||||
<Accordion type="single" collapsible className="w-full">
|
<Accordion type="single" collapsible className="w-full">
|
||||||
@@ -767,7 +768,7 @@ export function SystemSettings() {
|
|||||||
</div>
|
</div>
|
||||||
</AccordionTrigger>
|
</AccordionTrigger>
|
||||||
<AccordionContent className="px-4 pb-4">
|
<AccordionContent className="px-4 pb-4">
|
||||||
<div className="py-1 space-y-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 py-1">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
|
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
|
||||||
@@ -804,9 +805,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('projectsDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -845,9 +843,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('configDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -886,9 +881,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('temporaryDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -927,9 +919,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('pluginsDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -968,9 +957,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('templatesDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</AccordionContent>
|
</AccordionContent>
|
||||||
|
|||||||
Reference in new issue
Block a user