Compare commits

..
Author SHA1 Message Date
Derek RossandClaude Opus 4.5 a3a019a1fd Use blob URL instead of query string API key for APK download
Fetches APK using X-API-Key header and returns blob URL instead of
exposing API key in the download URL query string. This is more
secure as API keys are not logged or leaked via Referer headers.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-04 01:42:08 -05:00
Derek RossandClaude Opus 4.5 c7bbbe5659 Fix lint errors: indentation and unused variables
- Fix indentation in AddProviderDialog.tsx for ExternalInput block
- Prefix unused variables with underscore in signing.ts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-04 01:26:30 -05:00
Derek RossandClaude Opus 4.5 75502fdb7f Merge origin/main into feature/apk-builder
Resolves merge conflicts by integrating APK Builder support with the
new PresetDeployProvider type system from main. Adds 'apkbuilder' type
to the PresetDeployProvider union and includes APK Builder in the
PRESET_DEPLOY_PROVIDERS array.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-04 01:13:15 -05:00
Derek RossandClaude Opus 4.5 0b80f424c1 Remove APK signing debug logging
Clean up console.log statements from signing.ts now that
v1 and v2 signature implementation is working correctly.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-04 00:42:17 -05:00
Derek RossandClaude Opus 4.5 4c56e37212 Fix CORS proxy for APK Builder API key requests
Use Shakespeare's built-in corsProxy config and proxyUrl function
instead of hardcoded corsproxy.io which had an incorrect URL format.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-04 00:34:12 -05:00
Derek RossandClaude Opus 4.5 fb6d2cac82 Fix crash when removing APK Builder provider
Close dialog and reset selected index when removing a provider
to prevent accessing undefined array element.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-04 00:20:24 -05:00
Derek RossandClaude Opus 4.5 8660f4ad96 Add NIP-98 authentication for APK Builder API keys
Users can now request API keys from build servers using Nostr
authentication. The AddProviderDialog includes a key button that
initiates NIP-98 auth with the configured build server URL.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-04 00:12:52 -05:00
Derek RossandClaude Opus 4.5 e8cfcb7383 Move APK build server to separate repository
Moved to ../android-build-server/ for independent maintenance.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-03 23:52:31 -05:00
Derek RossandClaude Opus 4.5 d85b4d833e Add browser-based APK signing with v1 and v2 signature schemes
Implement complete APK signing in the browser using node-forge:
- JAR signing (v1) with MANIFEST.MF, CERT.SF, and CERT.RSA
- APK Signature Scheme v2 for Android 7.0+ compatibility
- Zipalign for 4-byte alignment (required for Android 11+)
- PKCS#12 keystore support for key import/export
- Key generation and persistence in localStorage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-03 23:48:30 -05:00
Derek RossandClaude Opus 4.5 4d8a3772b2 Remove zip terminal command
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-03 22:14:43 -05:00
Derek Ross 841554dd8a Merge apk-build-server into apk-builder 2026-01-03 17:01:21 -05:00
Derek RossandClaude Opus 4.5 7509103256 Add Android Keystore protection for Nostr private keys in APK builds
- Add @capacitor-community/secure-storage plugin to Capacitor dependencies
- Inject localStorage shim that intercepts 'nostr:*' keys
- Redirect sensitive keys to Android Keystore via SecureStorage plugin
- Users' nsec keys are now encrypted at rest using hardware-backed security

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-03 17:01:02 -05:00
Derek RossandClaude Opus 4.5 23b3c80f67 Add APK build server setup scripts
- setup-apk-build-service.sh: Docker-based Capacitor build server
- apk-builder-nginx.conf: nginx reverse proxy configuration

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-03 16:37:24 -05:00
Derek RossandClaude Opus 4.5 22d6ea7eef Fix git fetch binding and improve APK Builder UX
- Fix fetch context binding to prevent "Illegal invocation" error in dev
- Show "built" instead of "deployed" for APK Builder success message
- Use Android favicon for APK Builder provider icon

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-03 15:58:22 -05:00
Derek RossandClaude Opus 4.5 72c9fc6989 Add APK Builder deploy provider
Adds support for building Android APKs from web projects via a self-hosted
Capacitor-based build service.

- Add APKBuilderAdapter for communicating with build server
- Add APKBuilderDeployForm component for app name/package ID config
- Add zip command for creating archives in terminal
- Integrate APK Builder into deploy settings and deploy flow

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
2026-01-03 15:35:12 -05:00
68 changed files with 3171 additions and 1831 deletions

No files matched your search

+3 -43
View File
@@ -15,7 +15,6 @@ The OAuth system consists of three main components:
- **GitHub** - Git repository hosting (with PKCE support)
- **Netlify** - Static site deployment
- **Vercel** - Static site deployment
- **OpenRouter** - AI model routing (with PKCE support)
## File Structure
@@ -25,13 +24,11 @@ src/
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
│ ├── useVercelOAuth.ts # Vercel-specific configuration
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
│ └── useVercelOAuth.ts # Vercel-specific configuration
├── pages/
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
│ └── VercelOAuth.tsx # Vercel OAuth callback page
└── AppRouter.tsx # Routes for OAuth callbacks
```
@@ -193,7 +190,6 @@ const config: OAuthConfig = {
- ✅ GitHub - Supports PKCE (enabled)
- ❌ Netlify - Doesn't support PKCE (disabled)
- ❌ Vercel - Doesn't support PKCE (disabled)
- ✅ OpenRouter - Requires PKCE (enabled)
### Scope Parameter
@@ -203,42 +199,6 @@ The `scope` parameter is optional in the OAuth configuration. Some providers (li
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
- ❌ Netlify - No scope parameter (permissions set in app settings)
- ✅ 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
@@ -284,7 +244,7 @@ export function useNewProviderOAuth() {
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.provider.com/user' });
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
-9
View File
@@ -1,9 +0,0 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"nostr": {
"type": "local",
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
}
}
}
+42 -343
View File
@@ -20,7 +20,6 @@
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@opensecret/react": "^1.5.4",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -69,6 +68,7 @@
"jszip": "^3.10.1",
"lucide-react": "^0.562.0",
"mime": "^4.1.0",
"node-forge": "^1.3.3",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
@@ -108,6 +108,7 @@
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/node-forge": "^1.3.14",
"@types/nunjucks": "^3.2.6",
"@types/path-browserify": "^1.0.3",
"@types/prismjs": "^1.26.5",
@@ -2813,9 +2814,9 @@
"license": "BSD-2-Clause"
},
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.25.2",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.2.tgz",
"integrity": "sha512-LZFeo4F9M5qOhC/Uc1aQSrBHxMrvxett+9KLHt7OhcExtoiRN9DKgbZffMP/nxjutWDQpfMDfP3nkHI4X9ijww==",
"version": "1.25.1",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.1.tgz",
"integrity": "sha512-yO28oVFFC7EBoiKdAn+VqRm+plcfv4v0xp6osG/VsCB0NlPZWi87ajbCZZ8f/RvOFLEu7//rSRmuZZ7lMoe3gQ==",
"license": "MIT",
"dependencies": {
"@hono/node-server": "^1.19.7",
@@ -3021,173 +3022,6 @@
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
"integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
},
"node_modules/@opensecret/react": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/@opensecret/react/-/react-1.5.4.tgz",
"integrity": "sha512-nIrb1NfKIJ1G8IK+b8OnjXvPgc/C3GkLVbZVF9HCh6WBDV2yimg8B7Eo6Pqu5mUtiFrQslFL9UbeDj4Py0mbGA==",
"license": "MIT",
"dependencies": {
"@peculiar/x509": "^1.12.2",
"@stablelib/base64": "^2.0.0",
"@stablelib/chacha20poly1305": "^2.0.0",
"@stablelib/random": "^2.0.0",
"cbor2": "^1.7.0",
"tweetnacl": "^1.0.3",
"zod": "^3.23.8"
},
"peerDependencies": {
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
}
},
"node_modules/@peculiar/asn1-cms": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.6.0.tgz",
"integrity": "sha512-2uZqP+ggSncESeUF/9Su8rWqGclEfEiz1SyU02WX5fUONFfkjzS2Z/F1Li0ofSmf4JqYXIOdCAZqIXAIBAT1OA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"@peculiar/asn1-x509-attr": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-csr": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.6.0.tgz",
"integrity": "sha512-BeWIu5VpTIhfRysfEp73SGbwjjoLL/JWXhJ/9mo4vXnz3tRGm+NGm3KNcRzQ9VMVqwYS2RHlolz21svzRXIHPQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-ecc": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.6.0.tgz",
"integrity": "sha512-FF3LMGq6SfAOwUG2sKpPXblibn6XnEIKa+SryvUl5Pik+WR9rmRA3OCiwz8R3lVXnYnyRkSZsSLdml8H3UiOcw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pfx": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.6.0.tgz",
"integrity": "sha512-rtUvtf+tyKGgokHHmZzeUojRZJYPxoD/jaN1+VAB4kKR7tXrnDCA/RAWXAIhMJJC+7W27IIRGe9djvxKgsldCQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-pkcs8": "^2.6.0",
"@peculiar/asn1-rsa": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pkcs8": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.6.0.tgz",
"integrity": "sha512-KyQ4D8G/NrS7Fw3XCJrngxmjwO/3htnA0lL9gDICvEQ+GJ+EPFqldcJQTwPIdvx98Tua+WjkdKHSC0/Km7T+lA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pkcs9": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.6.0.tgz",
"integrity": "sha512-b78OQ6OciW0aqZxdzliXGYHASeCvvw5caqidbpQRYW2mBtXIX2WhofNXTEe7NyxTb0P6J62kAAWLwn0HuMF1Fw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-pfx": "^2.6.0",
"@peculiar/asn1-pkcs8": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"@peculiar/asn1-x509-attr": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-rsa": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.6.0.tgz",
"integrity": "sha512-Nu4C19tsrTsCp9fDrH+sdcOKoVfdfoQQ7S3VqjJU6vedR7tY3RLkQ5oguOIB3zFW33USDUuYZnPEQYySlgha4w==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-schema": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.6.0.tgz",
"integrity": "sha512-xNLYLBFTBKkCzEZIw842BxytQQATQv+lDTCEMZ8C196iJcJJMBUZxrhSTxLaohMyKK8QlzRNTRkUmanucnDSqg==",
"license": "MIT",
"dependencies": {
"asn1js": "^3.0.6",
"pvtsutils": "^1.3.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-x509": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.6.0.tgz",
"integrity": "sha512-uzYbPEpoQiBoTq0/+jZtpM6Gq6zADBx+JNFP3yqRgziWBxQ/Dt/HcuvRfm9zJTPdRcBqPNdaRHTVwpyiq6iNMA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"asn1js": "^3.0.6",
"pvtsutils": "^1.3.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-x509-attr": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.6.0.tgz",
"integrity": "sha512-MuIAXFX3/dc8gmoZBkwJWxUWOSvG4MMDntXhrOZpJVMkYX+MYc/rUAU2uJOved9iJEoiUx7//3D8oG83a78UJA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/x509": {
"version": "1.14.3",
"resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",
"integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-csr": "^2.6.0",
"@peculiar/asn1-ecc": "^2.6.0",
"@peculiar/asn1-pkcs9": "^2.6.0",
"@peculiar/asn1-rsa": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"pvtsutils": "^1.3.6",
"reflect-metadata": "^0.2.2",
"tslib": "^2.8.1",
"tsyringe": "^4.10.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
@@ -4553,9 +4387,9 @@
"license": "MIT"
},
"node_modules/@remix-run/router": {
"version": "1.23.2",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
"integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
"integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
@@ -5203,89 +5037,6 @@
"node": ">=18.0.0"
}
},
"node_modules/@stablelib/aead": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@stablelib/aead/-/aead-2.0.0.tgz",
"integrity": "sha512-U/RMANRxbT/ahIpYsPSiFwDFNjADHdnCFfmo09MO1ai2XmerPAOPtMl0qmX7XVvygnACC6ijKDyHBoT2rGyElg==",
"license": "MIT"
},
"node_modules/@stablelib/base64": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-2.0.1.tgz",
"integrity": "sha512-P2z89A7N1ETt6RxgpVdDT2xlg8cnm3n6td0lY9gyK7EiWK3wdq388yFX/hLknkCC0we05OZAD1rfxlQJUbl5VQ==",
"license": "MIT"
},
"node_modules/@stablelib/binary": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/binary/-/binary-2.0.1.tgz",
"integrity": "sha512-U9iAO8lXgEDONsA0zPPSgcf3HUBNAqHiJmSHgZz62OvC3Hi2Bhc5kTnQ3S1/L+sthDTHtCMhcEiklmIly6uQ3w==",
"license": "MIT",
"dependencies": {
"@stablelib/int": "^2.0.1"
}
},
"node_modules/@stablelib/chacha": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/chacha/-/chacha-2.0.1.tgz",
"integrity": "sha512-lS1FqtNqofxe2vLkRsLli2m3x/XanUyAYRphLhdHumKeIsLbjbCXdCq3Pf/eWiO7G3QlSG5ViqnoVjktzfLWMg==",
"license": "MIT",
"dependencies": {
"@stablelib/binary": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/chacha20poly1305": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/chacha20poly1305/-/chacha20poly1305-2.0.1.tgz",
"integrity": "sha512-kOoBsXbDPVRlelzXl+5WViycgM19lD7lF3Bc3KWI+DzId0Stc2HlxAfSc+Xpn3RgqSCl1ZNTXr33LegqBhBBaw==",
"license": "MIT",
"dependencies": {
"@stablelib/aead": "^2.0.0",
"@stablelib/binary": "^2.0.1",
"@stablelib/chacha": "^2.0.1",
"@stablelib/constant-time": "^2.0.1",
"@stablelib/poly1305": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/constant-time": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/constant-time/-/constant-time-2.0.1.tgz",
"integrity": "sha512-0NWPogffRm+UWBH0+iM5otZmNrVe5OHFIvyoNIVankMAYOQzMwcdVALOVPrB5Ho0dST+Oc3H8/hPh65Z8R/uew==",
"license": "MIT"
},
"node_modules/@stablelib/int": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/int/-/int-2.0.1.tgz",
"integrity": "sha512-Ht63fQp3wz/F8U4AlXEPb7hfJOIILs8Lq55jgtD7KueWtyjhVuzcsGLSTAWtZs3XJDZYdF1WcSKn+kBtbzupww==",
"license": "MIT"
},
"node_modules/@stablelib/poly1305": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/poly1305/-/poly1305-2.0.1.tgz",
"integrity": "sha512-D8xfZcL/5zeVARJ9I2fZOUCnZvsJx8G4JDQvD+ecsnaCildPtqZDwqqjtOc4cfHAdScrMjOzUVsssjXUTBw3YQ==",
"license": "MIT",
"dependencies": {
"@stablelib/constant-time": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/random": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/random/-/random-2.0.1.tgz",
"integrity": "sha512-W6GAtXEEs7r+dSbuBsvoFmlyL3gLxle41tQkjKu17dDWtDdjhVUbtRfRCQcCUeczwkgjQxMPopgwYEvxXtHXGw==",
"license": "MIT",
"dependencies": {
"@stablelib/binary": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/wipe": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/wipe/-/wipe-2.0.1.tgz",
"integrity": "sha512-1eU2K9EgOcV4qc9jcP6G72xxZxEm5PfeI5H55l08W95b4oRJaqhmlWRc4xZAm6IVSKhVNxMi66V67hCzzuMTAg==",
"license": "MIT"
},
"node_modules/@std/encoding": {
"name": "@jsr/std__encoding",
"version": "1.0.10",
@@ -5864,6 +5615,16 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/node-forge": {
"version": "1.3.14",
"resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz",
"integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/nunjucks": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/@types/nunjucks/-/nunjucks-3.2.6.tgz",
@@ -6568,20 +6329,6 @@
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
"license": "MIT"
},
"node_modules/asn1js": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.7.tgz",
"integrity": "sha512-uLvq6KJu04qoQM6gvBfKFjlh6Gl0vOKQuR5cJMDHQkmwfMOQeN3F3SHCv9SNYSL+CRoHvOGFfllDlVz03GQjvQ==",
"license": "BSD-3-Clause",
"dependencies": {
"pvtsutils": "^1.3.6",
"pvutils": "^1.1.3",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -7047,15 +6794,6 @@
],
"license": "CC-BY-4.0"
},
"node_modules/cbor2": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/cbor2/-/cbor2-1.12.0.tgz",
"integrity": "sha512-3Cco8XQhi27DogSp9Ri6LYNZLi/TBY/JVnDe+mj06NkBjW/ZYOtekaEU4wZ4xcRMNrFkDv8KNtOAqHyDfz3lYg==",
"license": "MIT",
"engines": {
"node": ">=18.7"
}
},
"node_modules/ccount": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
@@ -9474,9 +9212,9 @@
"license": "MIT"
},
"node_modules/hono": {
"version": "4.11.4",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.4.tgz",
"integrity": "sha512-U7tt8JsyrxSRKspfhtLET79pU8K+tInj5QZXs1jSugO1Vq5dFj3kmZsRldo29mTBfcjDRVRXrEZ6LS63Cog9ZA==",
"version": "4.11.1",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.1.tgz",
"integrity": "sha512-KsFcH0xxHes0J4zaQgWbYwmz3UPOOskdqZmItstUG93+Wk1ePBLkLGwbP9zlmh1BFUiL8Qp+Xfu9P7feJWpGNg==",
"license": "MIT",
"peer": true,
"engines": {
@@ -12015,6 +11753,15 @@
"node": ">= 0.6"
}
},
"node_modules/node-forge": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.3.tgz",
"integrity": "sha512-rLvcdSyRCyouf6jcOIPe/BgwG/d7hKjzMKOas33/pHEr6gbq18IK9zV7DiPvzsz0oBJPme6qr6H6kGZuI9/DZg==",
"license": "(BSD-3-Clause OR GPL-2.0)",
"engines": {
"node": ">= 6.13.0"
}
},
"node_modules/node-releases": {
"version": "2.0.26",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.26.tgz",
@@ -12804,24 +12551,6 @@
"node": ">=6"
}
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.8.1"
}
},
"node_modules/pvutils": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.5.tgz",
"integrity": "sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==",
"license": "MIT",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/qrcode": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
@@ -12840,9 +12569,9 @@
}
},
"node_modules/qs": {
"version": "6.14.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
"integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
"version": "6.14.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
"integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
@@ -13108,12 +12837,12 @@
}
},
"node_modules/react-router": {
"version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz",
"integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==",
"version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz",
"integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.2"
"@remix-run/router": "1.23.0"
},
"engines": {
"node": ">=14.0.0"
@@ -13123,13 +12852,13 @@
}
},
"node_modules/react-router-dom": {
"version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz",
"integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==",
"version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
"integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.2",
"react-router": "6.30.3"
"@remix-run/router": "1.23.0",
"react-router": "6.30.0"
},
"engines": {
"node": ">=14.0.0"
@@ -13273,12 +13002,6 @@
"node": ">=8"
}
},
"node_modules/reflect-metadata": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"license": "Apache-2.0"
},
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -14996,24 +14719,6 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsyringe": {
"version": "4.10.0",
"resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",
"integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",
"license": "MIT",
"dependencies": {
"tslib": "^1.9.3"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/tsyringe/node_modules/tslib": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
"license": "0BSD"
},
"node_modules/turndown": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.1.tgz",
@@ -15023,12 +14728,6 @@
"@mixmark-io/domino": "^2.2.0"
}
},
"node_modules/tweetnacl": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
"license": "Unlicense"
},
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
+2 -1
View File
@@ -31,7 +31,6 @@
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@opensecret/react": "^1.5.4",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -80,6 +79,7 @@
"jszip": "^3.10.1",
"lucide-react": "^0.562.0",
"mime": "^4.1.0",
"node-forge": "^1.3.3",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
@@ -119,6 +119,7 @@
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/node-forge": "^1.3.14",
"@types/nunjucks": "^3.2.6",
"@types/path-browserify": "^1.0.3",
"@types/prismjs": "^1.26.5",
+166
View File
@@ -0,0 +1,166 @@
# APK Build Service - Nginx Configuration
#
# Usage:
# 1. Copy to /etc/nginx/sites-available/apk-builder
# 2. Update server_name to your domain
# 3. Update SSL certificate paths (or use certbot)
# 4. sudo ln -s /etc/nginx/sites-available/apk-builder /etc/nginx/sites-enabled/
# 5. sudo nginx -t && sudo systemctl reload nginx
#
# For Let's Encrypt SSL:
# sudo certbot --nginx -d apk-builder.yourdomain.com
#
# Rate limiting zone (optional - uncomment to enable)
# limit_req_zone $binary_remote_addr zone=apk_build_limit:10m rate=5r/m;
upstream apk_builder {
server 127.0.0.1:3000;
keepalive 32;
}
# Redirect HTTP to HTTPS
server {
listen 80;
listen [::]:80;
server_name apk-builder.yourdomain.com;
# Let's Encrypt challenge
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$server_name$request_uri;
}
}
# HTTPS server
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name apk-builder.yourdomain.com;
# SSL Configuration
# Option 1: Let's Encrypt (recommended)
ssl_certificate /etc/letsencrypt/live/apk-builder.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/apk-builder.yourdomain.com/privkey.pem;
# Option 2: Self-signed (for testing only)
# ssl_certificate /etc/nginx/ssl/apk-builder.crt;
# ssl_certificate_key /etc/nginx/ssl/apk-builder.key;
# SSL Security Settings
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# Security Headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Allow large file uploads (for project ZIPs)
client_max_body_size 100M;
client_body_timeout 300s;
client_body_buffer_size 128k;
# Logging
access_log /var/log/nginx/apk-builder.access.log;
error_log /var/log/nginx/apk-builder.error.log;
# Health check endpoint (no auth, fast response)
location = /health {
proxy_pass http://apk_builder;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_read_timeout 10s;
}
# Build submission endpoint (longer timeouts)
location = /api/build {
# Optional rate limiting - uncomment to enable
# limit_req zone=apk_build_limit burst=2 nodelay;
# limit_req_status 429;
proxy_pass http://apk_builder;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
# Long timeout for upload processing
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
# Status polling endpoint
location ~ ^/api/build/[a-f0-9-]+/status$ {
proxy_pass http://apk_builder;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_connect_timeout 10s;
proxy_read_timeout 30s;
}
# APK download endpoint (large response, long timeout)
location ~ ^/api/build/[a-f0-9-]+/download$ {
proxy_pass http://apk_builder;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
# Long timeout for large APK downloads
proxy_connect_timeout 30s;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
# Buffering for large files
proxy_buffering on;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
# All other API endpoints
location /api/ {
proxy_pass http://apk_builder;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_connect_timeout 30s;
proxy_read_timeout 60s;
}
# Block all other paths
location / {
return 404 '{"error": "Not found"}';
add_header Content-Type application/json;
}
}
+6 -7
View File
@@ -24,13 +24,8 @@ export default {
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
if (hostname === 'github.com') {
if (url.hostname === 'github.com') {
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
return new Response(svg.replaceAll('#24292E', '#808080'), {
headers: { 'Content-Type': 'image/svg+xml' },
@@ -38,16 +33,20 @@ export default {
}
// AI-provider-specific hacks
let hostname = url.hostname;
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
hostname = 'ollama.com';
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
hostname = 'claude.ai';
} else if (url.host === 'generativelanguage.googleapis.com') {
hostname = 'gemini.google.com';
} else if (url.host === 'z.ai') {
} else if (url.host === 'api.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
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
},
+8 -9
View File
@@ -12,17 +12,16 @@ export default {
return new Response(null, {
status: 200,
headers: {
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
"access-control-allow-headers": "*", // Or specify specific headers
"access-control-max-age": "86400", // Cache preflight for 24 hours
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
"Access-Control-Allow-Headers": "*", // Or specify specific headers
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
}
});
}
const headers = new Headers(request.headers);
headers.set('user-agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
headers.delete('origin');
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
const targetResponse = await fetch(target, {
method: request.method,
@@ -32,9 +31,9 @@ export default {
const response = new Response(targetResponse.body, targetResponse);
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-headers", "*");
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-Headers", "*");
return response;
}
-2
View File
@@ -18,7 +18,6 @@ import AboutSettings from "./pages/AboutSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import NetlifyOAuth from "./pages/NetlifyOAuth";
import VercelOAuth from "./pages/VercelOAuth";
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -40,7 +39,6 @@ export function AppRouter() {
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
+6 -40
View File
@@ -1041,31 +1041,12 @@ export function AIProviderConfigDialog({
<div className="grid gap-2">
<Label htmlFor="provider-auth">{t('authentication')}</Label>
<Select
value={localProvider.nostr ? 'nostr' : localProvider.openSecret ? 'opensecret' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
if (value === 'nostr') {
setLocalProvider({
...localProvider,
nostr: true,
openSecret: undefined,
apiKey: undefined
});
} else if (value === 'opensecret') {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: localProvider.openSecret,
apiKey: localProvider.apiKey
});
} else {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: undefined,
apiKey: localProvider.apiKey
});
}
}}
value={localProvider.nostr ? 'nostr' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr') => setLocalProvider({
...localProvider,
nostr: value === 'nostr' || undefined,
apiKey: value === 'nostr' ? undefined : localProvider.apiKey
})}
>
<SelectTrigger>
<SelectValue />
@@ -1073,25 +1054,10 @@ export function AIProviderConfigDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{localProvider.openSecret && (
<div className="grid gap-2">
<Label htmlFor="provider-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="provider-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={localProvider.openSecret || ''}
onChange={(e) => setLocalProvider({ ...localProvider, openSecret: e.target.value })}
/>
</div>
)}
{!localProvider.nostr && (
<div className="grid gap-2">
<Label htmlFor="provider-apiKey">{t('apiKey')}</Label>
+4 -78
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Bot, ChevronDown } from 'lucide-react';
import { Bot } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { ExternalInput } from '@/components/ui/external-input';
@@ -12,31 +12,15 @@ import {
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { Link } from 'react-router-dom';
import type { PresetProvider } from '@/lib/aiProviderPresets';
interface OAuthHook {
isOAuthConfigured: boolean;
isLoading: boolean;
error: string | null;
initiateOAuth: () => void;
}
interface AddAIProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
preset: PresetProvider;
isLoggedIntoNostr: boolean;
oauthHook?: OAuthHook | null;
forceManualEntry?: boolean;
onSetForceManualEntry?: (force: boolean) => void;
onAdd: (apiKey: string) => void;
}
@@ -45,9 +29,6 @@ export function AddAIProviderDialog({
onOpenChange,
preset,
isLoggedIntoNostr,
oauthHook,
forceManualEntry = false,
onSetForceManualEntry,
onAdd,
}: AddAIProviderDialogProps) {
const { t } = useTranslation();
@@ -55,27 +36,16 @@ export function AddAIProviderDialog({
const [termsAgreed, setTermsAgreed] = useState(false);
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
const isOAuthLoading = oauthHook?.isLoading ?? false;
const oauthError = oauthHook?.error ?? null;
const handleAdd = () => {
onAdd(apiKey);
setApiKey('');
setTermsAgreed(false);
onOpenChange(false);
};
// Reset state when dialog closes
const handleOpenChange = (open: boolean) => {
if (!open) {
setApiKey('');
setTermsAgreed(false);
}
onOpenChange(open);
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
@@ -103,50 +73,6 @@ export function AddAIProviderDialog({
</Link>
</Button>
</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">
{!preset.nostr && preset.apiKeysURL && (
@@ -197,7 +123,7 @@ export function AddAIProviderDialog({
)}
</div>
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
{!showNostrLoginRequired && (
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
+3 -26
View File
@@ -50,8 +50,7 @@ export function AddCustomAIProviderDialog({
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr' | 'opensecret'>('api-key');
const [customOpenSecretUrl, setCustomOpenSecretUrl] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
const [customProxy, setCustomProxy] = useState(false);
const handleAdd = () => {
@@ -67,11 +66,6 @@ export function AddCustomAIProviderDialog({
provider.apiKey = customApiKey.trim();
} else if (customAuthMethod === 'nostr') {
provider.nostr = true;
} else if (customAuthMethod === 'opensecret') {
provider.openSecret = customOpenSecretUrl.trim();
if (customApiKey.trim()) {
provider.apiKey = customApiKey.trim();
}
}
if (customProxy) {
@@ -87,7 +81,6 @@ export function AddCustomAIProviderDialog({
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
setCustomOpenSecretUrl('');
setCustomProxy(false);
onOpenChange(false);
@@ -96,7 +89,6 @@ export function AddCustomAIProviderDialog({
const isValid = customProviderName.trim() &&
customProviderId.trim() &&
customBaseURL.trim() &&
(customAuthMethod !== 'opensecret' || customOpenSecretUrl.trim()) &&
!existingIds.includes(customProviderId.trim());
const idExists = existingIds.includes(customProviderId.trim());
@@ -164,7 +156,7 @@ export function AddCustomAIProviderDialog({
<Label htmlFor="custom-auth">{t('authentication')}</Label>
<Select
value={customAuthMethod}
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
onValueChange={(value: 'api-key' | 'nostr') => {
setCustomAuthMethod(value);
if (value === 'nostr') {
setCustomApiKey(''); // Clear API key when switching to Nostr auth
@@ -177,26 +169,11 @@ export function AddCustomAIProviderDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{customAuthMethod === 'opensecret' && (
<div className="grid gap-2">
<Label htmlFor="custom-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="custom-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={customOpenSecretUrl}
onChange={(e) => setCustomOpenSecretUrl(e.target.value)}
/>
</div>
)}
{(customAuthMethod === 'api-key' || customAuthMethod === 'opensecret') && (
{customAuthMethod === 'api-key' && (
<div className="grid gap-2">
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
<PasswordInput
+15 -8
View File
@@ -84,8 +84,8 @@ export function AddGitCredentialDialog({
</DialogHeader>
<div className="space-y-4 py-4">
{isOAuthConfigured && !forceManualEntry ? (
// Show OAuth button if OAuth is configured and not forced to manual
{preset.id === 'github' && isOAuthConfigured && !forceManualEntry ? (
// Special rendering for GitHub OAuth
<div className="space-y-3">
<div className="flex gap-0">
<Button
@@ -100,9 +100,16 @@ export function AddGitCredentialDialog({
Connecting...
</>
) : (
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
<>
<ExternalFavicon
url="https://github.com"
size={16}
fallback={<GitBranch size={16} />}
/>
<span className="truncate text-ellipsis overflow-hidden">
Connect to GitHub
</span>
</>
)}
</Button>
<DropdownMenu>
@@ -117,7 +124,7 @@ export function AddGitCredentialDialog({
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
Enter token manually
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -129,7 +136,7 @@ export function AddGitCredentialDialog({
)}
</div>
) : (
// Show manual token input
// Standard token input
<ExternalInput
type="password"
placeholder={t('enterToken')}
@@ -146,7 +153,7 @@ export function AddGitCredentialDialog({
)}
</div>
{!(isOAuthConfigured && !forceManualEntry) && (
{!(preset.id === 'github' && isOAuthConfigured && !forceManualEntry) && (
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ChevronDown } from 'lucide-react';
import { Rocket, ChevronDown, Key, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ExternalInput } from '@/components/ui/external-input';
import {
@@ -19,6 +19,9 @@ import {
} from '@/components/ui/dropdown-menu';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { Link } from 'react-router-dom';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { requestBuildServerApiKey } from '@/lib/nip98';
import type { PresetDeployProvider } from '@/lib/deploy/types';
interface OAuthHook {
@@ -28,7 +31,7 @@ interface OAuthHook {
initiateOAuth: () => void;
}
interface AddDeployProviderDialogProps {
interface AddProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
preset: PresetDeployProvider;
@@ -36,10 +39,10 @@ interface AddDeployProviderDialogProps {
oauthHook: OAuthHook | null;
forceManualEntry: boolean;
onSetForceManualEntry: (force: boolean) => void;
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
onAdd: (apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => void;
}
export function AddDeployProviderDialog({
export function AddProviderDialog({
open,
onOpenChange,
preset,
@@ -48,11 +51,16 @@ export function AddDeployProviderDialog({
forceManualEntry,
onSetForceManualEntry,
onAdd,
}: AddDeployProviderDialogProps) {
}: AddProviderDialogProps) {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { config } = useAppContext();
const [apiKey, setApiKey] = useState('');
const [accountId, setAccountId] = useState('');
const [organizationId, setOrganizationId] = useState('');
const [buildServerUrl, setBuildServerUrl] = useState('');
const [isGettingApiKey, setIsGettingApiKey] = useState(false);
const [apiKeyError, setApiKeyError] = useState<string | null>(null);
const showNostrLoginRequired = preset.requiresNostr && !isLoggedIntoNostr;
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
@@ -60,13 +68,38 @@ export function AddDeployProviderDialog({
const oauthError = oauthHook?.error ?? null;
const handleAdd = () => {
onAdd(apiKey, accountId, organizationId);
onAdd(apiKey, accountId, organizationId, buildServerUrl);
setApiKey('');
setAccountId('');
setOrganizationId('');
setBuildServerUrl('');
setApiKeyError(null);
onOpenChange(false);
};
const handleGetApiKey = async () => {
if (!buildServerUrl.trim() || !user?.signer) {
setApiKeyError('Build server URL and Nostr login required');
return;
}
setIsGettingApiKey(true);
setApiKeyError(null);
try {
const result = await requestBuildServerApiKey(
user.signer,
buildServerUrl.trim(),
preset.proxy ? config.corsProxy : undefined
);
setApiKey(result.apiKey);
} catch (error) {
setApiKeyError(error instanceof Error ? error.message : 'Failed to get API key');
} finally {
setIsGettingApiKey(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
@@ -112,9 +145,16 @@ export function AddDeployProviderDialog({
Connecting...
</>
) : (
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
<>
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Rocket size={16} />}
/>
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
</>
)}
</Button>
<DropdownMenu>
@@ -175,21 +215,78 @@ export function AddDeployProviderDialog({
urlTitle="Find ID"
/>
)}
<ExternalInput
type="password"
placeholder={preset.apiKeyLabel || t('enterApiKey')}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() &&
(preset.type !== 'cloudflare' || accountId.trim()) &&
(preset.type !== 'deno' || organizationId.trim())) {
handleAdd();
}
}}
url={preset.apiKeyURL}
urlTitle="Get Key"
/>
{preset.type === 'apkbuilder' && (
<>
<ExternalInput
type="text"
placeholder={preset.buildServerUrlLabel || 'Build Server URL'}
value={buildServerUrl}
onChange={(e) => {
setBuildServerUrl(e.target.value);
setApiKeyError(null);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
handleAdd();
}
}}
/>
<div className="flex gap-2">
<ExternalInput
type="password"
placeholder={preset.apiKeyLabel || 'API Key'}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
handleAdd();
}
}}
className="flex-1"
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleGetApiKey}
disabled={!buildServerUrl.trim() || !user?.signer || isGettingApiKey}
className="shrink-0"
title={!user?.signer ? 'Login to Nostr first' : 'Get API key using Nostr authentication'}
>
{isGettingApiKey ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Key className="h-4 w-4" />
)}
</Button>
</div>
{apiKeyError && (
<p className="text-xs text-destructive">{apiKeyError}</p>
)}
{!user?.signer && buildServerUrl.trim() && (
<p className="text-xs text-muted-foreground">
<Link to="/settings/nostr" className="underline">Login to Nostr</Link> to get an API key automatically
</p>
)}
</>
)}
{preset.type !== 'apkbuilder' && (
<ExternalInput
type="password"
placeholder={preset.apiKeyLabel || t('enterApiKey')}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() &&
(preset.type !== 'cloudflare' || accountId.trim()) &&
(preset.type !== 'deno' || organizationId.trim())) {
handleAdd();
}
}}
url={preset.apiKeyURL}
urlTitle="Get Key"
/>
)}
</>
)}
</div>
@@ -207,7 +304,8 @@ export function AddDeployProviderDialog({
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
(preset.type === 'cloudflare' && !accountId.trim()) ||
(preset.type === 'deno' && !organizationId.trim())
(preset.type === 'deno' && !organizationId.trim()) ||
(preset.type === 'apkbuilder' && !buildServerUrl.trim())
}
>
{t('add')}
+2 -2
View File
@@ -33,10 +33,10 @@ export function ExternalFavicon({
const parsedUrl = new URL(url);
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.|enclave\.)/, '');
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
// Normalize the URL to ensure it has a protocol
return faviconUrl({ template: config.faviconUrl, url: parsedUrl });
return faviconUrl(config.faviconUrl, parsedUrl);
} catch {
return;
}
+25 -16
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, Search, Coins } from 'lucide-react';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
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 { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { ExternalInput } from '@/components/ui/external-input';
import { PasswordInput } from '@/components/ui/password-input';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLoginActions } from '@/hooks/useLoginActions';
@@ -465,28 +465,37 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
{/* API Key Input Section */}
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
<div className="space-y-3 max-w-md mx-auto">
<h3 className="flex justify-center text-lg font-semibold gap-2">
<ExternalFavicon
url={selectedProvider.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<span>
<div className="text-center">
<h3 className="text-lg font-semibold">
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
</span>
</h3>
<ExternalInput
type="password"
</h3>
<p className="text-sm text-muted-foreground">
{selectedProvider.id === 'routstr' ? (
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')}
value={providerApiKey}
onChange={(e) => setProviderApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
if (e.key === 'Enter' && providerApiKey.trim()) {
handleContinueFromProviderSelection();
}
}}
url={selectedProvider.apiKeysURL}
urlTitle="Get Key"
/>
</div>
)}
+38
View File
@@ -125,6 +125,44 @@ export function ProviderConfigDialog({
/>
</div>
</>
) : localProvider.type === 'apkbuilder' ? (
<>
<div className="grid gap-2">
<Label htmlFor="provider-buildServerUrl">
{preset?.buildServerUrlLabel || 'Build Server URL'} <span className="text-destructive">*</span>
</Label>
<Input
id="provider-buildServerUrl"
placeholder="https://apk-builder.example.com"
value={localProvider.buildServerUrl || ''}
onChange={(e) => setLocalProvider({ ...localProvider, buildServerUrl: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-apiKey">
{preset?.apiKeyLabel || 'API Key'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="provider-apiKey"
placeholder="Enter API Key"
value={localProvider.apiKey}
onChange={(e) => setLocalProvider({ ...localProvider, apiKey: e.target.value })}
/>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="provider-proxy"
checked={localProvider.proxy || false}
onCheckedChange={(checked) => setLocalProvider({ ...localProvider, proxy: checked === true })}
/>
<Label
htmlFor="provider-proxy"
className="text-sm font-normal cursor-pointer"
>
Use CORS Proxy
</Label>
</div>
</>
) : localProvider.type === 'nsite' ? (
<>
<div className="grid gap-2">
@@ -1,246 +0,0 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import { MessageSquare, Minus, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { cn } from '@/lib/utils';
interface FloatingChatWidgetProps {
projectId: string;
isMinimized: boolean;
onToggleMinimize: () => void;
onClose: () => void;
onNewChat: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean;
isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
onDismissConsoleError?: () => void;
}
interface ChatSize {
width: number;
height: number;
}
const MIN_WIDTH = 320;
const MIN_HEIGHT = 380;
const MAX_WIDTH = 720;
const MAX_HEIGHT = 900;
const DEFAULT_WIDTH = 420;
const DEFAULT_HEIGHT = 520;
export function FloatingChatWidget({
projectId,
isMinimized,
onToggleMinimize,
onClose,
onNewChat,
onFirstInteraction,
onLoadingChange,
isLoading,
isBuildLoading,
consoleError,
onDismissConsoleError,
}: FloatingChatWidgetProps) {
const chatPaneRef = useRef<ChatPaneRef>(null);
const [size, setSize] = useLocalStorage<ChatSize>('shk:floatingChatSize', {
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
});
const [isResizing, setIsResizing] = useState(false);
const resizeStartRef = useRef<{ x: number; y: number; width: number; height: number } | null>(null);
// Handle keyboard escape to minimize
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !isMinimized) {
onToggleMinimize();
}
};
if (!isMinimized) {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}
}, [isMinimized, onToggleMinimize]);
// Resize handlers
const startResize = useCallback((e: React.PointerEvent, direction: 'right' | 'bottom' | 'top' | 'bottomLeft' | 'topRight') => {
e.preventDefault();
e.stopPropagation();
const target = e.currentTarget as HTMLElement;
target.setPointerCapture(e.pointerId);
setIsResizing(true);
document.body.style.userSelect = 'none';
resizeStartRef.current = {
x: e.clientX,
y: e.clientY,
width: size.width,
height: size.height,
};
const handlePointerMove = (moveEvent: PointerEvent) => {
if (!resizeStartRef.current) return;
const maxW = Math.min(MAX_WIDTH, window.innerWidth - 16);
const maxH = Math.min(MAX_HEIGHT, window.innerHeight - 16);
let newWidth = resizeStartRef.current.width;
let newHeight = resizeStartRef.current.height;
// Handle horizontal resizing (left edge for bottom-right anchored widget)
if (direction === 'right' || direction === 'bottomLeft' || direction === 'topRight') {
const deltaX = resizeStartRef.current.x - moveEvent.clientX;
newWidth = Math.max(MIN_WIDTH, Math.min(maxW, resizeStartRef.current.width + deltaX));
}
// Handle vertical resizing from bottom (grows downward)
if (direction === 'bottom' || direction === 'bottomLeft') {
const deltaY = resizeStartRef.current.y - moveEvent.clientY;
newHeight = Math.max(MIN_HEIGHT, Math.min(maxH, resizeStartRef.current.height + deltaY));
}
// Handle vertical resizing from top (grows upward, widget anchored at bottom)
if (direction === 'top' || direction === 'topRight') {
const deltaY = moveEvent.clientY - resizeStartRef.current.y;
newHeight = Math.max(MIN_HEIGHT, Math.min(maxH, resizeStartRef.current.height - deltaY));
}
setSize({ width: newWidth, height: newHeight });
};
const handlePointerUp = () => {
setIsResizing(false);
document.body.style.userSelect = '';
resizeStartRef.current = null;
window.removeEventListener('pointermove', handlePointerMove);
window.removeEventListener('pointerup', handlePointerUp);
};
window.addEventListener('pointermove', handlePointerMove);
window.addEventListener('pointerup', handlePointerUp);
}, [size, setSize]);
if (isMinimized) {
return (
<div className="fixed right-4 bottom-4 z-50">
<Button
onClick={onToggleMinimize}
size="icon"
className="h-14 w-14 rounded-full shadow-lg hover:shadow-xl transition-all duration-200"
aria-label="Open chat"
>
<MessageSquare className="h-6 w-6" />
</Button>
</div>
);
}
return (
<div
className={cn(
"fixed right-4 bottom-4 z-50",
"rounded-lg border shadow-2xl bg-background",
"flex flex-col overflow-hidden",
isResizing && "select-none"
)}
style={{
width: `${size.width}px`,
height: `${size.height}px`,
maxWidth: '92vw',
maxHeight: '70vh',
}}
>
{/* Header - Styled like ProjectSidebar */}
<div className="h-12 px-4 border-b flex-shrink-0 flex items-center justify-between bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur">
<div className="flex items-center gap-2">
<ShakespeareLogo className="w-5 h-5" />
<h2 className="text-base font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h2>
</div>
<div className="flex items-center gap-1">
<Button
onClick={onToggleMinimize}
variant="ghost"
size="icon"
className="h-8 w-8"
aria-label="Minimize chat"
>
<Minus className="h-4 w-4" />
</Button>
<Button
onClick={onClose}
variant="ghost"
size="icon"
className="h-8 w-8"
aria-label="Close floating chat"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Chat Body */}
<div className="flex-1 min-h-0 overflow-hidden">
<div className="h-full">
<ChatPane
ref={chatPaneRef}
projectId={projectId}
onNewChat={onNewChat}
onFirstInteraction={onFirstInteraction}
onLoadingChange={onLoadingChange}
isLoading={isLoading}
isBuildLoading={isBuildLoading}
consoleError={consoleError}
onDismissConsoleError={onDismissConsoleError}
/>
</div>
</div>
{/* Resize Handles */}
{/* Left edge (appears as "right" from widget perspective, but it's on the left side) */}
<div
className="absolute top-0 left-0 h-full w-2 cursor-ew-resize hover:bg-primary/10 active:bg-primary/20 transition-colors"
onPointerDown={(e) => startResize(e, 'right')}
style={{ touchAction: 'none' }}
/>
{/* Top edge */}
<div
className="absolute top-0 left-0 w-full h-2 cursor-ns-resize hover:bg-primary/10 active:bg-primary/20 transition-colors"
onPointerDown={(e) => startResize(e, 'top')}
style={{ touchAction: 'none' }}
/>
{/* Bottom edge */}
<div
className="absolute bottom-0 left-0 w-full h-2 cursor-ns-resize hover:bg-primary/10 active:bg-primary/20 transition-colors"
onPointerDown={(e) => startResize(e, 'bottom')}
style={{ touchAction: 'none' }}
/>
{/* Bottom-left corner */}
<div
className="absolute bottom-0 left-0 w-4 h-4 cursor-nesw-resize hover:bg-primary/20 active:bg-primary/30 transition-colors"
onPointerDown={(e) => startResize(e, 'bottomLeft')}
style={{ touchAction: 'none' }}
/>
{/* Top-right corner */}
<div
className="absolute top-0 right-0 w-4 h-4 cursor-nesw-resize hover:bg-primary/20 active:bg-primary/30 transition-colors"
onPointerDown={(e) => startResize(e, 'topRight')}
style={{ touchAction: 'none' }}
/>
</div>
);
}
@@ -0,0 +1,262 @@
import { useState, useEffect, useCallback } from 'react';
import { CheckCircle, XCircle, Loader2, Shield, Bug } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { proxyUrl } from '@/lib/proxyUrl';
import { cn } from '@/lib/utils';
import type { APKBuildType } from '@/lib/deploy/types';
interface APKBuilderDeployFormProps {
buildServerUrl: string;
apiKey: string;
projectId: string;
projectName?: string;
savedAppName?: string;
savedPackageId?: string;
savedBuildType?: APKBuildType;
onConfigChange: (appName: string, packageId: string, buildType: APKBuildType) => void;
corsProxy?: string;
}
interface ServerHealth {
status: 'ok' | 'error';
version?: string;
queue?: {
running: number;
queued: number;
};
}
export function APKBuilderDeployForm({
buildServerUrl,
apiKey,
projectId,
projectName,
savedAppName,
savedPackageId,
savedBuildType,
onConfigChange,
corsProxy,
}: APKBuilderDeployFormProps) {
const [appName, setAppName] = useState(savedAppName || projectName || projectId);
const [packageId, setPackageId] = useState(savedPackageId || '');
const [buildType, setBuildType] = useState<APKBuildType>(savedBuildType || 'debug');
const [packageIdError, setPackageIdError] = useState<string | null>(null);
const [serverHealth, setServerHealth] = useState<ServerHealth | null>(null);
const [isCheckingServer, setIsCheckingServer] = useState(true);
// Generate default package ID from project name
useEffect(() => {
if (!savedPackageId && !packageId) {
const safeName = (projectName || projectId)
.toLowerCase()
.replace(/[^a-z0-9]/g, '');
setPackageId(`com.app.${safeName}`);
}
}, [projectName, projectId, savedPackageId, packageId]);
// Check server health
const checkServerHealth = useCallback(async () => {
setIsCheckingServer(true);
try {
const url = `${buildServerUrl}/health`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const response = await fetch(targetUrl, {
headers: {
'X-API-Key': apiKey,
},
});
if (response.ok) {
const data = await response.json();
setServerHealth({ status: 'ok', ...data });
} else {
setServerHealth({ status: 'error' });
}
} catch {
setServerHealth({ status: 'error' });
} finally {
setIsCheckingServer(false);
}
}, [buildServerUrl, apiKey, corsProxy]);
useEffect(() => {
checkServerHealth();
}, [checkServerHealth]);
// Validate package ID
const validatePackageId = (value: string): boolean => {
// Android package ID rules:
// - Must have at least two segments (e.g., com.example)
// - Each segment must start with a letter
// - Can only contain letters, numbers, and underscores
const pattern = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/i;
return pattern.test(value);
};
// Handle package ID change with validation
const handlePackageIdChange = (value: string) => {
setPackageId(value);
if (value && !validatePackageId(value)) {
setPackageIdError('Package ID must be like "com.example.myapp" (letters, numbers, underscores)');
} else {
setPackageIdError(null);
}
};
// Notify parent of config changes
useEffect(() => {
if (appName && packageId && !packageIdError) {
onConfigChange(appName, packageId, buildType);
}
}, [appName, packageId, packageIdError, buildType, onConfigChange]);
return (
<div className="space-y-4">
{/* Server Status */}
<div className="rounded-lg border p-3">
<div className="flex items-center gap-2">
{isCheckingServer ? (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
) : serverHealth?.status === 'ok' ? (
<CheckCircle className="h-4 w-4 text-green-500" />
) : (
<XCircle className="h-4 w-4 text-red-500" />
)}
<div className="flex-1">
<p className="text-sm font-medium">
{isCheckingServer
? 'Checking build server...'
: serverHealth?.status === 'ok'
? 'Build server connected'
: 'Build server unavailable'}
</p>
{serverHealth?.status === 'ok' && serverHealth.queue && (
<p className="text-xs text-muted-foreground">
{serverHealth.queue.running > 0
? `${serverHealth.queue.running} build(s) in progress`
: 'Ready to build'}
{serverHealth.queue.queued > 0 && `, ${serverHealth.queue.queued} queued`}
</p>
)}
</div>
</div>
</div>
{serverHealth?.status === 'error' && (
<Alert variant="destructive">
<AlertDescription>
Cannot connect to build server. Check your server URL and API key in Deploy Settings.
</AlertDescription>
</Alert>
)}
{/* App Name */}
<div className="space-y-2">
<Label htmlFor="app-name">App Name</Label>
<Input
id="app-name"
value={appName}
onChange={(e) => setAppName(e.target.value)}
placeholder="My App"
/>
<p className="text-xs text-muted-foreground">
This name appears on the Android home screen
</p>
</div>
{/* Package ID */}
<div className="space-y-2">
<Label htmlFor="package-id">Package ID</Label>
<Input
id="package-id"
value={packageId}
onChange={(e) => handlePackageIdChange(e.target.value)}
placeholder="com.example.myapp"
className={packageIdError ? 'border-red-500' : ''}
/>
{packageIdError ? (
<p className="text-xs text-red-500">{packageIdError}</p>
) : (
<p className="text-xs text-muted-foreground">
Unique identifier for your app (e.g., com.yourcompany.appname)
</p>
)}
</div>
{/* Build Type Toggle */}
<div className="space-y-2">
<Label>Build Type</Label>
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => setBuildType('debug')}
className={cn(
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
"border-2 hover:scale-105 active:scale-95",
buildType === 'debug'
? "bg-primary text-primary-foreground border-primary shadow-sm"
: "bg-background text-foreground border-border hover:border-primary/50"
)}
>
<Bug className="h-3.5 w-3.5" />
<span>Debug</span>
</button>
<button
type="button"
onClick={() => setBuildType('release')}
className={cn(
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
"border-2 hover:scale-105 active:scale-95",
buildType === 'release'
? "bg-primary text-primary-foreground border-primary shadow-sm"
: "bg-background text-foreground border-border hover:border-primary/50"
)}
>
<Shield className="h-3.5 w-3.5" />
<span>Release</span>
</button>
</div>
</div>
{/* Build Info */}
<div className="rounded-lg bg-muted/50 p-3 space-y-1">
{buildType === 'debug' ? (
<>
<p className="text-xs text-muted-foreground">
<strong>Build type:</strong> Debug APK (for testing/sideloading)
</p>
<p className="text-xs text-muted-foreground">
Uses debug signing key. Install via USB or file transfer.
</p>
</>
) : (
<>
<p className="text-xs text-muted-foreground">
<strong>Build type:</strong> Release APK (unsigned)
</p>
<p className="text-xs text-muted-foreground">
Server builds unsigned APK. Signing will be done in your browser.
</p>
</>
)}
<p className="text-xs text-muted-foreground">
<strong>Output:</strong> Downloadable .apk file
</p>
</div>
{/* Release Signing Info */}
{buildType === 'release' && (
<Alert>
<Shield className="h-4 w-4" />
<AlertDescription className="text-xs">
Release builds require signing. You'll be prompted to configure your signing key after the build completes.
Your signing key never leaves your browser.
</AlertDescription>
</Alert>
)}
</div>
);
}
+595
View File
@@ -0,0 +1,595 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { Key, Upload, Plus, Download, Loader2, CheckCircle, AlertCircle, FileKey, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Checkbox } from '@/components/ui/checkbox';
import { cn } from '@/lib/utils';
import {
signApk,
generateSigningKey,
importKeyFromPkcs12,
exportKeyToPkcs12,
hasSavedKey,
getSavedKeyInfo,
loadSavedKey,
saveKey,
deleteSavedKey,
type SigningKey,
type StoredKeyInfo,
} from '@/lib/apk';
interface APKSignerProps {
unsignedApkUrl: string;
appName: string;
onComplete: (signedApkBlob: Blob) => void;
onCancel: () => void;
}
type KeySource = 'saved' | 'upload' | 'generate' | null;
type SigningStatus = 'idle' | 'loading-apk' | 'signing' | 'complete' | 'error';
export function APKSigner({ unsignedApkUrl, appName, onComplete, onCancel }: APKSignerProps) {
const [keySource, setKeySource] = useState<KeySource>(null);
const [signingKey, setSigningKey] = useState<SigningKey | null>(null);
const [status, setStatus] = useState<SigningStatus>('idle');
const [error, setError] = useState<string | null>(null);
const [progress, setProgress] = useState<string>('');
// Saved key state
const [savedKeyInfo, setSavedKeyInfo] = useState<StoredKeyInfo | null>(null);
const [savedKeyPassword, setSavedKeyPassword] = useState('');
const [saveKeyAfter, setSaveKeyAfter] = useState(true);
// Upload form state
const [uploadPassword, setUploadPassword] = useState('');
const [uploadFile, setUploadFile] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// Generate form state
const [generateName, setGenerateName] = useState(appName || 'My App');
const [generateOrg, setGenerateOrg] = useState('');
const [generatePassword, setGeneratePassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
// Check for saved key on mount
useEffect(() => {
if (hasSavedKey()) {
const info = getSavedKeyInfo();
setSavedKeyInfo(info);
}
}, []);
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setUploadFile(file);
setError(null);
}
}, []);
const handleLoadSavedKey = useCallback(() => {
if (!savedKeyPassword) {
setError('Please enter the password');
return;
}
try {
const key = loadSavedKey(savedKeyPassword);
setSigningKey(key);
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load saved key');
}
}, [savedKeyPassword]);
const handleDeleteSavedKey = useCallback(() => {
deleteSavedKey();
setSavedKeyInfo(null);
setKeySource(null);
}, []);
const handleImportKeystore = useCallback(async () => {
if (!uploadFile || !uploadPassword) {
setError('Please select a file and enter the password');
return;
}
try {
setStatus('loading-apk');
setProgress('Reading keystore...');
const arrayBuffer = await uploadFile.arrayBuffer();
const key = importKeyFromPkcs12(arrayBuffer, uploadPassword);
// Save key if requested
if (saveKeyAfter) {
saveKey(key, uploadPassword);
setSavedKeyInfo(getSavedKeyInfo());
}
setSigningKey(key);
setError(null);
setStatus('idle');
setProgress('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to import keystore');
setStatus('error');
}
}, [uploadFile, uploadPassword, saveKeyAfter]);
const handleGenerateKeystore = useCallback(() => {
if (!generateName.trim()) {
setError('Please enter an app/key name');
return;
}
if (!generatePassword) {
setError('Please enter a password');
return;
}
if (generatePassword !== confirmPassword) {
setError('Passwords do not match');
return;
}
if (generatePassword.length < 6) {
setError('Password must be at least 6 characters');
return;
}
try {
setProgress('Generating key pair...');
const key = generateSigningKey({
commonName: generateName.trim(),
organizationName: generateOrg.trim() || undefined,
});
// Save key if requested
if (saveKeyAfter) {
saveKey(key, generatePassword);
setSavedKeyInfo(getSavedKeyInfo());
}
setSigningKey(key);
setError(null);
setProgress('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to generate keystore');
}
}, [generateName, generateOrg, generatePassword, confirmPassword, saveKeyAfter]);
const handleDownloadKeystore = useCallback(() => {
if (!signingKey) return;
const password = keySource === 'generate' ? generatePassword : uploadPassword;
const p12Data = exportKeyToPkcs12(signingKey, password);
const blob = new Blob([p12Data], { type: 'application/x-pkcs12' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${appName.replace(/[^a-zA-Z0-9]/g, '_')}_release_key.p12`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, [signingKey, keySource, generatePassword, uploadPassword, appName]);
const handleSign = useCallback(async () => {
if (!signingKey) {
setError('No signing key configured');
return;
}
try {
setStatus('loading-apk');
setProgress('Downloading unsigned APK...');
setError(null);
// Fetch the unsigned APK
const response = await fetch(unsignedApkUrl);
if (!response.ok) {
throw new Error(`Failed to download APK: ${response.status} ${response.statusText}`);
}
const apkData = await response.arrayBuffer();
const sizeMB = (apkData.byteLength / 1024 / 1024).toFixed(2);
setProgress(`Downloaded ${sizeMB} MB. Signing APK...`);
setStatus('signing');
// Sign the APK
const signedApk = await signApk({
key: signingKey,
apkData,
});
setStatus('complete');
setProgress('');
onComplete(signedApk);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to sign APK');
setStatus('error');
}
}, [signingKey, unsignedApkUrl, onComplete]);
const renderKeySourceSelection = () => (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Key className="h-4 w-4 text-muted-foreground" />
<span className="font-medium text-sm">Configure Signing Key</span>
</div>
{/* Saved key option */}
{savedKeyInfo && (
<button
type="button"
onClick={() => setKeySource('saved')}
className={cn(
"w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left",
keySource === 'saved'
? "border-primary bg-primary/5"
: "border-border hover:border-primary/50"
)}
>
<div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10">
<Key className="h-5 w-5 text-primary" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{savedKeyInfo.commonName}</p>
<p className="text-xs text-muted-foreground">
Saved key • Expires {new Date(savedKeyInfo.expiresAt).getFullYear()}
</p>
</div>
<CheckCircle className="h-5 w-5 text-primary flex-shrink-0" />
</button>
)}
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => setKeySource('upload')}
className={cn(
"flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all",
keySource === 'upload'
? "border-primary bg-primary/5"
: "border-border hover:border-primary/50"
)}
>
<Upload className="h-6 w-6 text-muted-foreground" />
<span className="text-sm font-medium">Upload Keystore</span>
<span className="text-xs text-muted-foreground text-center">
Use existing .p12 or .pfx file
</span>
</button>
<button
type="button"
onClick={() => setKeySource('generate')}
className={cn(
"flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all",
keySource === 'generate'
? "border-primary bg-primary/5"
: "border-border hover:border-primary/50"
)}
>
<Plus className="h-6 w-6 text-muted-foreground" />
<span className="text-sm font-medium">Generate New</span>
<span className="text-xs text-muted-foreground text-center">
Create a new signing key
</span>
</button>
</div>
</div>
);
const renderSavedKeyForm = () => (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Key className="h-4 w-4 text-muted-foreground" />
<span className="font-medium text-sm">Use Saved Key</span>
</div>
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
Back
</Button>
</div>
{savedKeyInfo && (
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
<div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10">
<Key className="h-5 w-5 text-primary" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{savedKeyInfo.commonName}</p>
<p className="text-xs text-muted-foreground">
Expires {new Date(savedKeyInfo.expiresAt).getFullYear()}
</p>
</div>
<Button
variant="ghost"
size="icon"
onClick={handleDeleteSavedKey}
className="text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
)}
<div className="space-y-3">
<div className="space-y-2">
<Label htmlFor="saved-key-password">Password</Label>
<Input
id="saved-key-password"
type="password"
value={savedKeyPassword}
onChange={(e) => setSavedKeyPassword(e.target.value)}
placeholder="Enter password to unlock key"
/>
</div>
<Button
onClick={handleLoadSavedKey}
disabled={!savedKeyPassword}
className="w-full"
>
Unlock Key
</Button>
</div>
</div>
);
const renderUploadForm = () => (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Upload className="h-4 w-4 text-muted-foreground" />
<span className="font-medium text-sm">Upload Keystore</span>
</div>
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
Back
</Button>
</div>
<div className="space-y-3">
<div className="space-y-2">
<Label>Keystore File (.p12 / .pfx)</Label>
<div className="flex gap-2">
<Input
type="text"
value={uploadFile?.name || ''}
placeholder="Select a keystore file..."
readOnly
className="flex-1"
onClick={() => fileInputRef.current?.click()}
/>
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
Browse
</Button>
<input
ref={fileInputRef}
type="file"
accept=".p12,.pfx,.jks,.keystore"
className="hidden"
onChange={handleFileSelect}
/>
</div>
<p className="text-xs text-muted-foreground">
PKCS#12 format (.p12 / .pfx). For JKS files, convert first using keytool.
</p>
</div>
<div className="space-y-2">
<Label htmlFor="keystore-password">Keystore Password</Label>
<Input
id="keystore-password"
type="password"
value={uploadPassword}
onChange={(e) => setUploadPassword(e.target.value)}
placeholder="Enter keystore password"
/>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="save-upload-key"
checked={saveKeyAfter}
onCheckedChange={(checked) => setSaveKeyAfter(checked === true)}
/>
<Label htmlFor="save-upload-key" className="text-sm font-normal cursor-pointer">
Remember this key for future builds
</Label>
</div>
<Button
onClick={handleImportKeystore}
disabled={!uploadFile || !uploadPassword}
className="w-full"
>
Import Keystore
</Button>
</div>
</div>
);
const renderGenerateForm = () => (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4 text-muted-foreground" />
<span className="font-medium text-sm">Generate New Key</span>
</div>
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
Back
</Button>
</div>
<div className="space-y-3">
<div className="space-y-2">
<Label htmlFor="key-name">Name (Common Name)</Label>
<Input
id="key-name"
value={generateName}
onChange={(e) => setGenerateName(e.target.value)}
placeholder="My App"
/>
</div>
<div className="space-y-2">
<Label htmlFor="key-org">Organization (optional)</Label>
<Input
id="key-org"
value={generateOrg}
onChange={(e) => setGenerateOrg(e.target.value)}
placeholder="My Company"
/>
</div>
<div className="space-y-2">
<Label htmlFor="key-password">Password</Label>
<Input
id="key-password"
type="password"
value={generatePassword}
onChange={(e) => setGeneratePassword(e.target.value)}
placeholder="Enter password (min 6 characters)"
/>
</div>
<div className="space-y-2">
<Label htmlFor="key-confirm">Confirm Password</Label>
<Input
id="key-confirm"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="Confirm password"
/>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="save-generated-key"
checked={saveKeyAfter}
onCheckedChange={(checked) => setSaveKeyAfter(checked === true)}
/>
<Label htmlFor="save-generated-key" className="text-sm font-normal cursor-pointer">
Remember this key for future builds
</Label>
</div>
<Button
onClick={handleGenerateKeystore}
disabled={!generateName || !generatePassword || !confirmPassword}
className="w-full"
>
Generate Key
</Button>
</div>
</div>
);
const renderKeyReady = () => (
<div className="space-y-4">
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
Signing key ready: <strong>{signingKey?.alias}</strong>
</AlertDescription>
</Alert>
{keySource === 'generate' && (
<Alert>
<FileKey className="h-4 w-4" />
<AlertDescription className="space-y-2">
<p><strong>Important:</strong> Save your keystore file! You'll need it for future updates.</p>
<Button
variant="outline"
size="sm"
onClick={handleDownloadKeystore}
className="mt-2"
>
<Download className="h-4 w-4 mr-2" />
Download Keystore (.p12)
</Button>
</AlertDescription>
</Alert>
)}
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => {
setSigningKey(null);
setKeySource(null);
}}
className="flex-1"
>
Change Key
</Button>
<Button
onClick={handleSign}
disabled={status === 'loading-apk' || status === 'signing'}
className="flex-1"
>
{status === 'loading-apk' || status === 'signing' ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Signing...
</>
) : (
<>
<Key className="h-4 w-4 mr-2" />
Sign APK
</>
)}
</Button>
</div>
</div>
);
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{progress && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
{progress}
</div>
)}
<div className="rounded-lg border p-4">
{signingKey ? (
renderKeyReady()
) : keySource === 'saved' ? (
renderSavedKeyForm()
) : keySource === 'upload' ? (
renderUploadForm()
) : keySource === 'generate' ? (
renderGenerateForm()
) : (
renderKeySourceSelection()
)}
</div>
<div className="flex justify-end">
<Button variant="ghost" onClick={onCancel}>
Cancel
</Button>
</div>
</div>
);
}
@@ -63,10 +63,10 @@ export function CloudflareDeployForm({
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
const [subdomainResponse, workersResponse] = await Promise.all([
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: subdomainUrl }) : subdomainUrl, {
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: workersUrl }) : workersUrl, {
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
]);
+1 -1
View File
@@ -56,7 +56,7 @@ export function DenoDeployForm({
try {
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const response = await fetch(targetUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
+214 -31
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react';
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud, Shield, Download, CheckCircle } from 'lucide-react';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -15,7 +15,7 @@ import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { Link } from 'react-router-dom';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from '@/lib/deploy/types';
import type { APKBuildType, PresetDeployProvider } from '@/lib/deploy/types';
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
@@ -23,6 +23,8 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
import { APKBuilderDeployForm } from '@/components/deploy/APKBuilderDeployForm';
import { APKSigner } from '@/components/deploy/APKSigner';
import { cn } from '@/lib/utils';
import { DeployAdapter } from '@/lib/deploy/types';
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
@@ -31,6 +33,7 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
import { APKBuilderAdapter } from '@/lib/deploy/APKBuilderAdapter';
/**
* Normalize a URL string to ensure it has a protocol
@@ -101,6 +104,12 @@ interface DenoDeployFormData {
projectName: string;
}
interface APKBuilderFormData {
appName: string;
packageId: string;
buildType: APKBuildType;
}
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
@@ -114,6 +123,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
const [isDeploying, setIsDeploying] = useState(false);
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [signedApkBlob, setSignedApkBlob] = useState<Blob | null>(null);
const [error, setError] = useState<string | null>(null);
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
@@ -138,6 +148,11 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
projectName: projectName || projectId,
});
const [apkBuilderForm, setApkBuilderForm] = useState<APKBuilderFormData>({
appName: projectName || projectId,
packageId: '',
buildType: 'debug',
});
// Load project settings when component mounts
useEffect(() => {
@@ -261,6 +276,30 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'apkbuilder') {
const apkBuilderProvider = selectedProvider;
if (!apkBuilderProvider.buildServerUrl) {
throw new Error('APK Builder server URL is required');
}
if (!apkBuilderProvider.apiKey) {
throw new Error('APK Builder API key is required');
}
if (!apkBuilderForm.appName) {
throw new Error('App name is required');
}
if (!apkBuilderForm.packageId) {
throw new Error('Package ID is required');
}
adapter = new APKBuilderAdapter({
fs,
buildServerUrl: apkBuilderProvider.buildServerUrl,
apiKey: apkBuilderProvider.apiKey,
appName: apkBuilderForm.appName,
packageId: apkBuilderForm.packageId,
buildType: apkBuilderForm.buildType,
corsProxy: apkBuilderProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
@@ -320,6 +359,16 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'apkbuilder') {
await updateProjectSettings(selectedProviderId, {
type: 'apkbuilder',
url: result.url,
data: {
appName: apkBuilderForm.appName,
packageId: apkBuilderForm.packageId,
buildType: apkBuilderForm.buildType,
},
});
}
setDeployResult(result);
@@ -333,6 +382,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const handleClose = () => {
setSelectedProviderId('');
setDeployResult(null);
setSignedApkBlob(null);
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
@@ -341,9 +391,27 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
setApkBuilderForm({ appName: projectName || projectId, packageId: '', buildType: 'debug' });
onClose();
};
const handleSigningComplete = useCallback((blob: Blob) => {
setSignedApkBlob(blob);
}, []);
const handleDownloadSignedApk = useCallback(() => {
if (!signedApkBlob) return;
const url = URL.createObjectURL(signedApkBlob);
const a = document.createElement('a');
a.href = url;
a.download = `${apkBuilderForm.appName.replace(/[^a-zA-Z0-9]/g, '_')}_signed.apk`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, [signedApkBlob, apkBuilderForm.appName]);
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
setShakespeareForm({ subdomain });
}, []);
@@ -372,6 +440,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setDenoDeployForm({ projectName });
}, []);
const handleApkBuilderConfigChange = useCallback((appName: string, packageId: string, buildType: APKBuildType) => {
setApkBuilderForm({ appName, packageId, buildType });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
@@ -477,6 +549,28 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
);
}
if (selectedProvider.type === 'apkbuilder') {
const apkBuilderProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedAppName = savedConfig?.type === 'apkbuilder' ? savedConfig.data.appName : undefined;
const savedPackageId = savedConfig?.type === 'apkbuilder' ? savedConfig.data.packageId : undefined;
const savedBuildType = savedConfig?.type === 'apkbuilder' ? savedConfig.data.buildType : undefined;
return (
<APKBuilderDeployForm
buildServerUrl={apkBuilderProvider.buildServerUrl}
apiKey={apkBuilderProvider.apiKey}
projectId={projectId}
projectName={projectName}
savedAppName={savedAppName}
savedPackageId={savedPackageId}
savedBuildType={savedBuildType}
onConfigChange={handleApkBuilderConfigChange}
corsProxy={apkBuilderProvider.proxy ? config.corsProxy : undefined}
/>
);
}
return null;
};
@@ -491,36 +585,124 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
{deployResult ? (
<div className="space-y-4">
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
Your project has been successfully deployed!
</AlertDescription>
</Alert>
{/* Release APK signing flow */}
{selectedProvider?.type === 'apkbuilder' && apkBuilderForm.buildType === 'release' ? (
<>
{/* Step indicator */}
<div className="flex items-center gap-2 text-sm">
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-medium">
<CheckCircle className="h-3 w-3" />
</div>
<span className="text-muted-foreground line-through">Build</span>
<div className="flex-1 h-px bg-border" />
<div className={cn(
"flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium",
signedApkBlob
? "bg-primary text-primary-foreground"
: "bg-primary text-primary-foreground"
)}>
{signedApkBlob ? <CheckCircle className="h-3 w-3" /> : '2'}
</div>
<span className={signedApkBlob ? "text-muted-foreground line-through" : "font-medium"}>Sign</span>
<div className="flex-1 h-px bg-border" />
<div className={cn(
"flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium",
signedApkBlob
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground"
)}>
3
</div>
<span className={signedApkBlob ? "font-medium" : "text-muted-foreground"}>Download</span>
</div>
<div className="space-y-2">
<Label>Deployed URL</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
{signedApkBlob ? (
/* Signing complete - show download */
<>
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
APK signed successfully! Download your release-ready APK.
</AlertDescription>
</Alert>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
</div>
<div className="rounded-lg border p-4 space-y-4">
<div className="flex items-center justify-between">
<div>
<p className="font-medium text-sm">{apkBuilderForm.appName}_signed.apk</p>
<p className="text-xs text-muted-foreground">
{(signedApkBlob.size / 1024 / 1024).toFixed(2)} MB
</p>
</div>
<Button onClick={handleDownloadSignedApk}>
<Download className="h-4 w-4 mr-2" />
Download APK
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
</div>
</>
) : (
/* Show signing UI */
<>
<Alert>
<Shield className="h-4 w-4" />
<AlertDescription>
Release APK built! Sign it with your keystore to install on devices.
</AlertDescription>
</Alert>
<APKSigner
unsignedApkUrl={deployResult.url}
appName={apkBuilderForm.appName}
onComplete={handleSigningComplete}
onCancel={handleClose}
/>
</>
)}
</>
) : (
/* Standard success UI for debug APK and other providers */
<>
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
{selectedProvider?.type === 'apkbuilder'
? 'Your project has been successfully built!'
: 'Your project has been successfully deployed!'}
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>{selectedProvider?.type === 'apkbuilder' ? 'Download URL' : 'Deployed URL'}</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
</div>
</>
)}
</div>
) : (
<div className="space-y-4">
@@ -653,7 +835,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
(selectedProvider.type === 'apkbuilder' && (!apkBuilderForm.appName || !apkBuilderForm.packageId))
}
className="w-full"
>
+1 -1
View File
@@ -53,7 +53,7 @@ export function NetlifyDeployForm({
try {
const url = `${baseURL}/sites`;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const response = await fetch(targetUrl, {
headers: {
+20 -92
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react';
import { CloudUpload, Loader2, Check, AlertTriangle } from 'lucide-react';
import { CloudUpload, Loader2, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useGitStatus } from '@/hooks/useGitStatus';
@@ -16,8 +16,6 @@ interface GitSyncButtonProps {
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const [open, setOpen] = useState(false);
const [syncSuccess, setSyncSuccess] = useState(false);
const [showWarningPopover, setShowWarningPopover] = useState(false);
const warningDismissed = useRef(false);
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
const { getError, getState } = useGitSyncState();
@@ -28,18 +26,6 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const gitSyncState = getState(dir);
const isGitActionOccurring = gitSyncState?.isActive ?? false;
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
useEffect(() => {
@@ -52,29 +38,6 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
prevIsGitActionOccurring.current = isGitActionOccurring;
}, [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)
const renderIndicator = () => {
// Checkmark: sync just completed successfully - highest priority
@@ -115,61 +78,26 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
};
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}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn("size-8 p-0 group relative", className)}
aria-label="Sync with Git"
onClick={handleButtonClick}
>
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
{renderIndicator()}
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
</div>
</PopoverTrigger>
<PopoverContent
side="bottom"
align="center"
className="w-80 pointer-events-none z-40"
onOpenAutoFocus={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn("size-8 p-0 group relative", className)}
aria-label="Sync with Git"
>
<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>
</>
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
{renderIndicator()}
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
);
}
+1 -1
View File
@@ -154,7 +154,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
if (url.protocol === 'nostr:') {
const nostrUri = await NostrURI.parse(url.href);
return ngitWebUrl({ template: config.ngitWebUrl, nostrURI: nostrUri });
return ngitWebUrl(config.ngitWebUrl, nostrUri);
}
return null;
-1
View File
@@ -7,7 +7,6 @@ export interface AIProvider {
apiKey?: string;
nostr?: boolean;
proxy?: boolean;
openSecret?: string;
}
export interface MCPServer {
+8 -1
View File
@@ -50,7 +50,14 @@ export interface DenoDeployProvider extends BaseDeployProvider {
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export interface APKBuilderProvider extends BaseDeployProvider {
type: 'apkbuilder';
buildServerUrl: string;
apiKey: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | APKBuilderProvider;
export interface DeploySettings {
providers: DeployProvider[];
+1 -1
View File
@@ -30,7 +30,7 @@ export function useGitHubOAuth() {
redirectUri: window.location.origin + '/oauth/github',
usePKCE: true, // GitHub supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.github.com/user' });
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+1 -1
View File
@@ -30,7 +30,7 @@ export function useNetlifyOAuth() {
redirectUri: window.location.origin + '/oauth/netlify',
usePKCE: false, // Netlify doesn't support PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.netlify.com/api/v1/user' });
const userUrl = proxyUrl(corsProxy, 'https://api.netlify.com/api/v1/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+2 -2
View File
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
import { proxyUrl } from '@/lib/proxyUrl';
export interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
provider: 'github' | 'netlify' | 'vercel';
clientId: string;
clientSecret: string;
authorizeUrl: string;
@@ -169,7 +169,7 @@ export function useOAuth(config: OAuthConfig) {
}
// Exchange code for access token
const tokenUrl = proxyUrl({ template: corsProxy, url: config.tokenUrl });
const tokenUrl = proxyUrl(corsProxy, config.tokenUrl);
const tokenResponse = await fetch(tokenUrl, {
method: 'POST',
headers: {
-164
View File
@@ -1,164 +0,0 @@
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,
};
}
+12
View File
@@ -52,6 +52,16 @@ const denoDeployProjectConfigSchema = z.object({
}),
});
const apkBuilderProjectConfigSchema = z.object({
type: z.literal('apkbuilder'),
url: z.string(),
data: z.object({
appName: z.string(),
packageId: z.string(),
buildType: z.enum(['debug', 'release']).optional(),
}),
});
const projectProviderConfigSchema = z.discriminatedUnion('type', [
shakespeareProjectConfigSchema,
nsiteProjectConfigSchema,
@@ -59,6 +69,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
vercelProjectConfigSchema,
cloudflareProjectConfigSchema,
denoDeployProjectConfigSchema,
apkBuilderProjectConfigSchema,
]);
const projectDeploySettingsSchema = z.object({
@@ -72,6 +83,7 @@ export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
export type APKBuilderProjectConfig = z.infer<typeof apkBuilderProjectConfigSchema>;
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
+1 -1
View File
@@ -34,7 +34,7 @@ export function useVercelOAuth() {
redirectUri: window.location.origin + '/oauth/vercel',
usePKCE: false, // Vercel doesn't require PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.vercel.com/v2/user' });
const userUrl = proxyUrl(corsProxy, 'https://api.vercel.com/v2/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+14 -60
View File
@@ -450,7 +450,7 @@ export class SessionManager {
let accumulatedContent = '';
let accumulatedReasoningContent = '';
const accumulatedToolCalls: Map<number, OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall> = new Map();
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
let finishReason: string | null = null;
// Process the stream
@@ -491,29 +491,20 @@ export class SessionManager {
const toolCallDelta = delta.tool_calls[i];
const index = toolCallDelta.index ?? i; // Fix for Gemini models
let toolCall = accumulatedToolCalls.get(index);
if (!toolCall) {
toolCall = {
id: '',
type: 'function',
function: { name: '', arguments: '' },
};
}
accumulatedToolCalls[index] ??= {
id: '',
type: 'function',
function: { name: '', arguments: '' }
};
const toolCall = accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
accumulatedToolCalls.set(index, toolCall);
}
if (session.streamingMessage && accumulatedToolCalls.size > 0) {
const sortedToolCalls = [...accumulatedToolCalls.entries()]
.sort((a, b) => a[0] - b[0])
.map(entry => entry[1]);
session.streamingMessage.tool_calls = sortedToolCalls;
if (session.streamingMessage) {
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
}
}
@@ -537,7 +528,7 @@ export class SessionManager {
}
// Fix tool calls with empty arguments or names
for (const toolCall of accumulatedToolCalls.values()) {
for (const toolCall of accumulatedToolCalls) {
if (toolCall.type === 'function') {
toolCall.function.arguments = toolCall.function.arguments || '{}';
@@ -558,7 +549,7 @@ export class SessionManager {
role: 'assistant',
content: accumulatedContent,
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
...(accumulatedToolCalls.size > 0 && { tool_calls: [...accumulatedToolCalls.values()] })
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
};
// Check if the assistant message is empty (no content, reasoning, or tool calls)
@@ -584,8 +575,8 @@ export class SessionManager {
}
// Handle tool calls
if (accumulatedToolCalls?.size) {
for (const toolCall of accumulatedToolCalls.values()) {
if (accumulatedToolCalls?.length) {
for (const toolCall of accumulatedToolCalls) {
if (toolCall.type !== 'function') continue;
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
@@ -720,50 +711,13 @@ export class SessionManager {
this.emit('finishReasonChanged', projectId, null);
}
/**
* Check if content exceeds size/line limits
*/
private exceedsLimits(content: string): boolean {
const MAX_SIZE_BYTES = 50 * 1024; // 50 KiB
const MAX_LINES = 2000;
const sizeBytes = new Blob([content]).size;
const lineCount = content.split('\n').length;
return sizeBytes > MAX_SIZE_BYTES || lineCount > MAX_LINES;
}
/**
* Save content to tmpDir and return the file path
*/
private async saveToTmpFile(projectId: string, content: string, toolCallId: string): Promise<string> {
const config = this.getConfig();
const timestamp = Date.now();
const filename = `tool-output-${toolCallId}-${timestamp}.txt`;
const filepath = `${config.fsPathTmp}/${filename}`;
await this.fs.writeFile(filepath, content, 'utf8');
return filepath;
}
/**
* Helper to add tool messages and update conversation
*/
private async addToolMessage(projectId: string, toolCallId: string, content: string): Promise<void> {
let finalContent = content;
// Check if content exceeds limits
if (this.exceedsLimits(content)) {
// Save full content to tmp file
const filepath = await this.saveToTmpFile(projectId, content, toolCallId);
// Create placeholder message
finalContent = `The tool call succeeded but the output was truncated. Full output saved to: ${filepath}\nUse grep to search it for specific content, or text_editor_view with start_line/end_line to view specific sections.`;
}
const toolMessage: AIMessage = {
role: 'tool',
content: finalContent,
content,
tool_call_id: toolCallId
};
+9 -50
View File
@@ -12,21 +12,17 @@ import { proxyUrl } from './proxyUrl';
* If the provider has proxy enabled, requests will be proxied through the corsProxy.
*/
export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: string): OpenAI {
const openai = new OpenAI({
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true,
};
const openai = new OpenAI({
...baseConfig,
fetch: async (input, init) => {
let request = new Request(input, init);
// OpenSecret auth
// https://docs.opensecret.cloud/docs/maple-ai/
if (provider.openSecret) {
const { createCustomFetch } = await import('@opensecret/react');
return createCustomFetch({ apiKey: provider.apiKey, apiUrl: provider.openSecret })(input, init);
}
// Add OpenRouter headers
// https://openrouter.ai/docs/app-attribution
if (provider.id === 'openrouter') {
@@ -51,7 +47,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
// If proxy is enabled and we have a CORS proxy URL, modify the request URL
if (provider.proxy && corsProxy) {
request = new Request(proxyUrl({ template: corsProxy, url: request.url }), request);
request = new Request(proxyUrl(corsProxy, request.url), request);
}
return fetch(request);
@@ -62,51 +58,14 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
= openai.chat.completions.create.bind(openai.chat.completions);
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
// 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
// OpenRouter usage accounting
// https://openrouter.ai/docs/use-cases/usage-accounting
if (provider.id === 'openrouter') {
(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);
}) as typeof createCompletion;
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" };
}
}
};
}
-17
View File
@@ -6,7 +6,6 @@ export interface PresetProvider {
nostr?: boolean;
tosURL?: string;
proxy?: boolean;
openSecret?: string;
}
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
@@ -17,22 +16,6 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://ai.shakespeare.diy/terms",
nostr: true,
},
{
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: "maple",
name: "Maple AI",
baseURL: "https://enclave.trymaple.ai/v1",
apiKeysURL: "https://trymaple.ai/",
tosURL: "https://opensecret.cloud/terms",
openSecret: "https://enclave.trymaple.ai",
},
{
id: "openrouter",
name: "OpenRouter",
+2
View File
@@ -0,0 +1,2 @@
export * from './signing';
export * from './keystore';
+95
View File
@@ -0,0 +1,95 @@
/**
* Keystore persistence utilities
* Saves/loads signing keys from localStorage
*/
import type { SigningKey } from './signing';
import { importKeyFromPkcs12, exportKeyToPkcs12 } from './signing';
const STORAGE_KEY = 'shakespeare:apk-signing-key';
export interface StoredKeyInfo {
alias: string;
commonName: string;
createdAt: string;
expiresAt: string;
}
interface StoredKeyData {
p12Base64: string;
info: StoredKeyInfo;
}
/**
* Check if a signing key is saved in localStorage
*/
export function hasSavedKey(): boolean {
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored !== null;
} catch {
return false;
}
}
/**
* Get info about the saved key without loading it
*/
export function getSavedKeyInfo(): StoredKeyInfo | null {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (!stored) return null;
const data: StoredKeyData = JSON.parse(stored);
return data.info;
} catch {
return null;
}
}
/**
* Load a saved signing key from localStorage
* Requires the password to decrypt the PKCS#12 data
*/
export function loadSavedKey(password: string): SigningKey {
const stored = localStorage.getItem(STORAGE_KEY);
if (!stored) {
throw new Error('No saved signing key found');
}
const data: StoredKeyData = JSON.parse(stored);
const p12Buffer = Uint8Array.from(atob(data.p12Base64), c => c.charCodeAt(0));
return importKeyFromPkcs12(p12Buffer.buffer, password);
}
/**
* Save a signing key to localStorage
* The key is stored as encrypted PKCS#12 data
*/
export function saveKey(key: SigningKey, password: string): void {
const p12Data = exportKeyToPkcs12(key, password);
const p12Base64 = btoa(String.fromCharCode(...p12Data));
// Extract certificate info
const cert = key.certificate;
const commonName = cert.subject.getField('CN')?.value || key.alias;
const data: StoredKeyData = {
p12Base64,
info: {
alias: key.alias,
commonName: typeof commonName === 'string' ? commonName : key.alias,
createdAt: cert.validity.notBefore.toISOString(),
expiresAt: cert.validity.notAfter.toISOString(),
},
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}
/**
* Delete the saved signing key from localStorage
*/
export function deleteSavedKey(): void {
localStorage.removeItem(STORAGE_KEY);
}
+905
View File
@@ -0,0 +1,905 @@
/**
* Browser-based APK signing utility
* Implements JAR signing (v1) for Android APKs
*/
import JSZip from 'jszip';
import forge from 'node-forge';
export interface SigningKey {
privateKey: forge.pki.PrivateKey;
certificate: forge.pki.Certificate;
alias: string;
}
export interface SigningOptions {
key: SigningKey;
apkData: ArrayBuffer;
}
/**
* Zipalign implementation for 4-byte alignment
* Aligns uncompressed entries to the specified boundary
*/
function zipalign(data: Uint8Array, alignment: number): Uint8Array {
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
// Find End of Central Directory (EOCD)
let eocdOffset = -1;
for (let i = data.length - 22; i >= 0; i--) {
if (view.getUint32(i, true) === 0x06054b50) {
eocdOffset = i;
break;
}
}
if (eocdOffset === -1) throw new Error('Invalid ZIP: EOCD not found');
const cdOffset = view.getUint32(eocdOffset + 16, true);
const _cdSize = view.getUint32(eocdOffset + 12, true);
const entryCount = view.getUint16(eocdOffset + 10, true);
// Parse central directory to get file entries
interface Entry {
nameOffset: number;
nameLength: number;
extraLength: number;
commentLength: number;
compressionMethod: number;
localHeaderOffset: number;
compressedSize: number;
uncompressedSize: number;
}
const entries: Entry[] = [];
let pos = cdOffset;
for (let i = 0; i < entryCount; i++) {
if (view.getUint32(pos, true) !== 0x02014b50) throw new Error('Invalid central directory');
const compressionMethod = view.getUint16(pos + 10, true);
const compressedSize = view.getUint32(pos + 20, true);
const uncompressedSize = view.getUint32(pos + 24, true);
const nameLength = view.getUint16(pos + 28, true);
const extraLength = view.getUint16(pos + 30, true);
const commentLength = view.getUint16(pos + 32, true);
const localHeaderOffset = view.getUint32(pos + 42, true);
entries.push({
nameOffset: pos + 46,
nameLength,
extraLength,
commentLength,
compressionMethod,
localHeaderOffset,
compressedSize,
uncompressedSize,
});
pos += 46 + nameLength + extraLength + commentLength;
}
// Calculate new offsets and padding needed
interface AlignmentInfo {
entry: Entry;
localExtraLength: number;
newOffset: number;
paddingNeeded: number;
name: string;
}
const alignmentInfos: AlignmentInfo[] = [];
let currentOffset = 0;
for (const entry of entries) {
const localPos = entry.localHeaderOffset;
if (view.getUint32(localPos, true) !== 0x04034b50) throw new Error('Invalid local header');
const localNameLength = view.getUint16(localPos + 26, true);
const localExtraLength = view.getUint16(localPos + 28, true);
const _headerSize = 30 + localNameLength + localExtraLength;
const _dataOffset = localPos + _headerSize;
const nameBytes = data.slice(localPos + 30, localPos + 30 + localNameLength);
const name = new TextDecoder().decode(nameBytes);
// Only align uncompressed files (compression method 0 = STORE)
let paddingNeeded = 0;
if (entry.compressionMethod === 0 && entry.uncompressedSize > 0) {
const newDataOffset = currentOffset + 30 + localNameLength + localExtraLength;
const misalignment = newDataOffset % alignment;
if (misalignment !== 0) {
paddingNeeded = alignment - misalignment;
}
}
alignmentInfos.push({
entry,
localExtraLength,
newOffset: currentOffset,
paddingNeeded,
name,
});
currentOffset += 30 + localNameLength + localExtraLength + paddingNeeded + entry.compressedSize;
}
// Calculate new central directory offset
const _newCdOffset = currentOffset;
// Build new ZIP
const cdEntrySize = pos - cdOffset; // Total size of central directory entries
const newSize = currentOffset + cdEntrySize + 22;
const result = new Uint8Array(newSize);
const resultView = new DataView(result.buffer);
let writePos = 0;
// Write local file headers and data
for (const info of alignmentInfos) {
const entry = info.entry;
const oldLocalPos = entry.localHeaderOffset;
const oldNameLength = view.getUint16(oldLocalPos + 26, true);
const oldExtraLength = view.getUint16(oldLocalPos + 28, true);
const oldHeaderSize = 30 + oldNameLength + oldExtraLength;
// Copy local file header
result.set(data.slice(oldLocalPos, oldLocalPos + 30), writePos);
// Update extra field length to include padding
const newExtraLength = oldExtraLength + info.paddingNeeded;
resultView.setUint16(writePos + 28, newExtraLength, true);
// Copy filename
result.set(data.slice(oldLocalPos + 30, oldLocalPos + 30 + oldNameLength), writePos + 30);
// Copy original extra field
if (oldExtraLength > 0) {
result.set(
data.slice(oldLocalPos + 30 + oldNameLength, oldLocalPos + 30 + oldNameLength + oldExtraLength),
writePos + 30 + oldNameLength
);
}
// Padding is implicitly zero-filled (Uint8Array is initialized to 0)
writePos += 30 + oldNameLength + newExtraLength;
// Copy file data
const dataStart = oldLocalPos + oldHeaderSize;
result.set(data.slice(dataStart, dataStart + entry.compressedSize), writePos);
writePos += entry.compressedSize;
}
// Write central directory
const newCdStart = writePos;
for (let i = 0; i < alignmentInfos.length; i++) {
const info = alignmentInfos[i];
const entry = info.entry;
// Find this entry in original central directory
let oldCdPos = cdOffset;
for (let j = 0; j < i; j++) {
const e = entries[j];
oldCdPos += 46 + e.nameLength + e.extraLength + e.commentLength;
}
const cdEntryLength = 46 + entry.nameLength + entry.extraLength + entry.commentLength;
// Copy central directory entry
result.set(data.slice(oldCdPos, oldCdPos + cdEntryLength), writePos);
// Update local header offset
resultView.setUint32(writePos + 42, info.newOffset, true);
writePos += cdEntryLength;
}
// Write EOCD
result.set(data.slice(eocdOffset, eocdOffset + 22), writePos);
// Update central directory offset
resultView.setUint32(writePos + 16, newCdStart, true);
return result;
}
/**
* APK Signature Scheme v2 implementation
* Inserts a signing block between ZIP content and Central Directory
*/
function applyV2Signature(apk: Uint8Array, key: SigningKey): Uint8Array {
const view = new DataView(apk.buffer, apk.byteOffset, apk.byteLength);
// Find EOCD
let eocdOffset = -1;
for (let i = apk.length - 22; i >= 0; i--) {
if (view.getUint32(i, true) === 0x06054b50) {
eocdOffset = i;
break;
}
}
if (eocdOffset === -1) throw new Error('Invalid ZIP: EOCD not found');
const cdOffset = view.getUint32(eocdOffset + 16, true);
const _cdSize = view.getUint32(eocdOffset + 12, true);
// Section 1: ZIP entries (before CD)
const zipEntries = apk.slice(0, cdOffset);
// Section 3: Central Directory
const centralDir = apk.slice(cdOffset, eocdOffset);
// Section 4: EOCD
const eocd = apk.slice(eocdOffset);
// Calculate content digests using 1MB chunks
const CHUNK_SIZE = 1024 * 1024;
const digests: Uint8Array[] = [];
// Helper to compute SHA256
const sha256 = (data: Uint8Array): Uint8Array => {
const md = forge.md.sha256.create();
const len = data.length;
const chunkSize = 8192;
for (let i = 0; i < len; i += chunkSize) {
const end = Math.min(i + chunkSize, len);
let chunk = '';
for (let j = i; j < end; j++) {
chunk += String.fromCharCode(data[j]);
}
md.update(chunk);
}
return new Uint8Array(forge.util.binary.raw.decode(md.digest().getBytes()));
};
// Digest section 1 (ZIP entries)
for (let offset = 0; offset < zipEntries.length; offset += CHUNK_SIZE) {
const chunkEnd = Math.min(offset + CHUNK_SIZE, zipEntries.length);
const chunk = zipEntries.slice(offset, chunkEnd);
// Chunk format: 0xa5 + 4-byte little-endian length + data
const chunkData = new Uint8Array(5 + chunk.length);
chunkData[0] = 0xa5;
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
chunkData.set(chunk, 5);
digests.push(sha256(chunkData));
}
// Digest section 3 (Central Directory)
for (let offset = 0; offset < centralDir.length; offset += CHUNK_SIZE) {
const chunkEnd = Math.min(offset + CHUNK_SIZE, centralDir.length);
const chunk = centralDir.slice(offset, chunkEnd);
const chunkData = new Uint8Array(5 + chunk.length);
chunkData[0] = 0xa5;
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
chunkData.set(chunk, 5);
digests.push(sha256(chunkData));
}
// Pre-calculate signing block size to compute modified EOCD
// The signing block size depends on: certificate size, signature size (256 for RSA-2048), public key size
// We'll compute the actual size after building the blocks, but for now estimate
// Actually, we need to include EOCD with modified offset in the digest
// So we need to know the final signing block size first
// For RSA-2048: signature is 256 bytes
// We'll calculate the exact size by building the structure first without the actual signature
const certDerForSize = getCertificateDer(key.certificate);
const pubKeyDerForSize = getPublicKeyDer(key.certificate);
// Calculate signing block size components:
// digestsBlock: 4 (seq) + 4 (entry) + 4 (algo) + 4 (digest_len) + 32 (digest) = 48
// certsBlock: 4 + 4 + certDer.length
// attrsBlock: 4
// signedData: 4 + digestsBlock + certsBlock + attrsBlock
// sigsBlock: 4 (seq) + 4 (entry) + 4 (algo) + 4 (sig_len) + 256 (sig) = 272 (RSA-2048)
// pubKeyBlock: 4 + pubKeyDer.length
// signerBlock: 4 + signedData + sigsBlock + pubKeyBlock
// signersBlock: 4 + signerBlock
// v2Block: 8 (pair_size) + 4 (id) + signersBlock
// signingBlock: 8 + v2Block + 8 + 16
const digestsBlockSize = 4 + 4 + 4 + 4 + 32; // 48
const certsBlockSize = 4 + 4 + certDerForSize.length;
const attrsBlockSize = 4;
const signedDataSize = 4 + digestsBlockSize + certsBlockSize + attrsBlockSize;
const sigsBlockSize = 4 + 4 + 4 + 4 + 256; // 272 for RSA-2048 signature
const pubKeyBlockSize = 4 + pubKeyDerForSize.length;
const signerBlockSize = 4 + signedDataSize + sigsBlockSize + pubKeyBlockSize;
const signersBlockSize = 4 + signerBlockSize;
const v2BlockSize = 8 + 4 + signersBlockSize; // uint64 pair_size + uint32 ID + value
const signingBlockTotalSize = 8 + v2BlockSize + 8 + 16;
// For digest computation, EOCD's offset is treated as pointing to signing block start
// (which is the original cdOffset, where we'll insert the signing block)
// The actual file's EOCD will point to real CD, but digest uses signing block offset
const eocdForDigest = new Uint8Array(eocd);
// cdOffset is where signing block will be inserted, so EOCD offset = cdOffset for digest
new DataView(eocdForDigest.buffer).setUint32(16, cdOffset, true);
// Digest section 4 (EOCD with modified CD offset)
for (let offset = 0; offset < eocdForDigest.length; offset += CHUNK_SIZE) {
const chunkEnd = Math.min(offset + CHUNK_SIZE, eocdForDigest.length);
const chunk = eocdForDigest.slice(offset, chunkEnd);
const chunkData = new Uint8Array(5 + chunk.length);
chunkData[0] = 0xa5;
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
chunkData.set(chunk, 5);
digests.push(sha256(chunkData));
}
// Combine chunk digests into content digest
// Format: 0x5a + 4-byte count + all digests concatenated
const digestData = new Uint8Array(5 + digests.length * 32);
digestData[0] = 0x5a;
new DataView(digestData.buffer).setUint32(1, digests.length, true);
for (let i = 0; i < digests.length; i++) {
digestData.set(digests[i], 5 + i * 32);
}
const contentDigest = sha256(digestData);
// Build signed data
// Structure: sequence of length-prefixed digests, certificates, and additional attributes
const certDer = getCertificateDer(key.certificate);
// Digests: length-prefixed sequence of length-prefixed (algorithmId, digest) pairs
// Algorithm ID: 0x0103 = RSASSA-PKCS1-v1_5 with SHA-256
// Structure: sequence_length + [entry_length + algorithm_id + digest_length + digest]
const digestEntrySize = 4 + 4 + 32; // algorithm_id + digest_length + digest
const digestsBlock = new Uint8Array(4 + 4 + digestEntrySize);
let dPos = 0;
// Length of sequence
new DataView(digestsBlock.buffer).setUint32(dPos, 4 + digestEntrySize, true);
dPos += 4;
// Entry length
new DataView(digestsBlock.buffer).setUint32(dPos, digestEntrySize, true);
dPos += 4;
// Algorithm ID
new DataView(digestsBlock.buffer).setUint32(dPos, 0x0103, true);
dPos += 4;
// Digest length
new DataView(digestsBlock.buffer).setUint32(dPos, 32, true);
dPos += 4;
// Digest
digestsBlock.set(contentDigest, dPos);
// Certificates: length-prefixed sequence of DER-encoded certificates
const certsBlock = new Uint8Array(4 + 4 + certDer.length);
let cPos = 0;
// Length of sequence
new DataView(certsBlock.buffer).setUint32(cPos, 4 + certDer.length, true);
cPos += 4;
// Certificate length
new DataView(certsBlock.buffer).setUint32(cPos, certDer.length, true);
cPos += 4;
// Certificate
certsBlock.set(certDer, cPos);
// Additional attributes (empty for now)
const attrsBlock = new Uint8Array(4);
new DataView(attrsBlock.buffer).setUint32(0, 0, true);
// Combine into signed data content (without length prefix - that's added separately)
const signedDataContent = new Uint8Array(digestsBlock.length + certsBlock.length + attrsBlock.length);
let sdPos = 0;
signedDataContent.set(digestsBlock, sdPos);
sdPos += digestsBlock.length;
signedDataContent.set(certsBlock, sdPos);
sdPos += certsBlock.length;
signedDataContent.set(attrsBlock, sdPos);
// Sign the signed data content (RSA-PKCS1-v1_5 with SHA-256)
// The signing algorithm hashes internally, so we feed it the raw content
const md = forge.md.sha256.create();
// Convert to string in chunks to avoid stack overflow
const len = signedDataContent.length;
const chunkSize = 8192;
for (let i = 0; i < len; i += chunkSize) {
const end = Math.min(i + chunkSize, len);
let chunk = '';
for (let j = i; j < end; j++) {
chunk += String.fromCharCode(signedDataContent[j]);
}
md.update(chunk);
}
const rsaPrivateKey = key.privateKey as unknown as forge.pki.rsa.PrivateKey;
const signature = rsaPrivateKey.sign(md);
const signatureBytes = new Uint8Array(forge.util.binary.raw.decode(signature));
// Create length-prefixed signed data for the signer block
const signedData = new Uint8Array(4 + signedDataContent.length);
new DataView(signedData.buffer).setUint32(0, signedDataContent.length, true);
signedData.set(signedDataContent, 4);
// Build signatures block
// Structure: sequence_length + [entry_length + algorithm_id + signature_length + signature]
const sigEntrySize = 4 + 4 + signatureBytes.length; // algorithm_id + sig_length + signature
const sigsBlock = new Uint8Array(4 + 4 + sigEntrySize);
let sPos = 0;
// Length of sequence
new DataView(sigsBlock.buffer).setUint32(sPos, 4 + sigEntrySize, true);
sPos += 4;
// Entry length
new DataView(sigsBlock.buffer).setUint32(sPos, sigEntrySize, true);
sPos += 4;
// Algorithm ID
new DataView(sigsBlock.buffer).setUint32(sPos, 0x0103, true);
sPos += 4;
// Signature length
new DataView(sigsBlock.buffer).setUint32(sPos, signatureBytes.length, true);
sPos += 4;
// Signature
sigsBlock.set(signatureBytes, sPos);
// Get public key DER
const pubKeyDer = getPublicKeyDer(key.certificate);
const pubKeyBlock = new Uint8Array(4 + pubKeyDer.length);
new DataView(pubKeyBlock.buffer).setUint32(0, pubKeyDer.length, true);
pubKeyBlock.set(pubKeyDer, 4);
// Build signer block
const signerBlock = new Uint8Array(4 + signedData.length + sigsBlock.length + pubKeyBlock.length);
let signerPos = 0;
// Length prefix
new DataView(signerBlock.buffer).setUint32(signerPos, signedData.length + sigsBlock.length + pubKeyBlock.length, true);
signerPos += 4;
signerBlock.set(signedData, signerPos);
signerPos += signedData.length;
signerBlock.set(sigsBlock, signerPos);
signerPos += sigsBlock.length;
signerBlock.set(pubKeyBlock, signerPos);
// Build signers sequence (just one signer)
const signersBlock = new Uint8Array(4 + signerBlock.length);
new DataView(signersBlock.buffer).setUint32(0, signerBlock.length, true);
signersBlock.set(signerBlock, 4);
// Build v2 signature block (ID 0x7109871a)
// Format: uint64 pair_size + uint32 ID + value
const v2Block = new Uint8Array(8 + 4 + signersBlock.length);
// Pair size (uint64): ID (4 bytes) + value
new DataView(v2Block.buffer).setBigUint64(0, BigInt(4 + signersBlock.length), true);
// ID (uint32)
new DataView(v2Block.buffer).setUint32(8, 0x7109871a, true);
// Value (signers)
v2Block.set(signersBlock, 12);
// Build APK Signing Block
// Structure: 8-byte size + pairs + 8-byte size + 16-byte magic
const MAGIC = new Uint8Array([
0x41, 0x50, 0x4b, 0x20, 0x53, 0x69, 0x67, 0x20,
0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x34, 0x32,
]); // "APK Sig Block 42"
const pairsSize = v2Block.length;
const blockSize = pairsSize + 8 + 16; // pairs + second size + magic
const signingBlock = new Uint8Array(8 + blockSize);
let sbPos = 0;
// First size
new DataView(signingBlock.buffer).setBigUint64(sbPos, BigInt(blockSize), true);
sbPos += 8;
// Pairs (v2 block)
signingBlock.set(v2Block, sbPos);
sbPos += v2Block.length;
// Second size
new DataView(signingBlock.buffer).setBigUint64(sbPos, BigInt(blockSize), true);
sbPos += 8;
// Magic
signingBlock.set(MAGIC, sbPos);
// Verify size calculation matches actual size
if (signingBlockTotalSize !== signingBlock.length) {
throw new Error('V2 signing block size mismatch - digest will be invalid');
}
// Update EOCD with new CD offset (after signing block)
const newEocd = new Uint8Array(eocd);
new DataView(newEocd.buffer).setUint32(16, cdOffset + signingBlock.length, true);
// Build final APK
const result = new Uint8Array(zipEntries.length + signingBlock.length + centralDir.length + newEocd.length);
let rPos = 0;
result.set(zipEntries, rPos);
rPos += zipEntries.length;
result.set(signingBlock, rPos);
rPos += signingBlock.length;
result.set(centralDir, rPos);
rPos += centralDir.length;
result.set(newEocd, rPos);
return result;
}
/**
* Get certificate as DER bytes
*/
function getCertificateDer(cert: forge.pki.Certificate): Uint8Array {
const pem = forge.pki.certificateToPem(cert);
const base64 = pem
.replace(/-----BEGIN CERTIFICATE-----/, '')
.replace(/-----END CERTIFICATE-----/, '')
.replace(/\r?\n/g, '');
const der = forge.util.decode64(base64);
return new Uint8Array(forge.util.binary.raw.decode(der));
}
/**
* Get public key as DER bytes (SubjectPublicKeyInfo)
*/
function getPublicKeyDer(cert: forge.pki.Certificate): Uint8Array {
const pem = forge.pki.publicKeyToPem(cert.publicKey);
const base64 = pem
.replace(/-----BEGIN PUBLIC KEY-----/, '')
.replace(/-----END PUBLIC KEY-----/, '')
.replace(/\r?\n/g, '');
const der = forge.util.decode64(base64);
return new Uint8Array(forge.util.binary.raw.decode(der));
}
/**
* Sign an APK using JAR signing (v1 signature scheme)
* This creates META-INF/MANIFEST.MF, META-INF/CERT.SF, and META-INF/CERT.RSA
*/
export async function signApk(options: SigningOptions): Promise<Blob> {
const { key, apkData } = options;
// Load the APK (ZIP file)
const zip = await JSZip.loadAsync(apkData);
// Remove any existing signatures
zip.remove('META-INF/MANIFEST.MF');
zip.remove('META-INF/CERT.SF');
zip.remove('META-INF/CERT.RSA');
zip.remove('META-INF/CERT.DSA');
zip.remove('META-INF/CERT.EC');
// Remove any other signature files
const metaInfFiles = Object.keys(zip.files).filter(f =>
f.startsWith('META-INF/') && (f.endsWith('.SF') || f.endsWith('.RSA') || f.endsWith('.DSA') || f.endsWith('.EC'))
);
for (const file of metaInfFiles) {
zip.remove(file);
}
// Create MANIFEST.MF
const manifest = await createManifest(zip);
zip.file('META-INF/MANIFEST.MF', manifest, { compression: 'DEFLATE' });
// Create CERT.SF (signature file)
const signatureFile = createSignatureFile(manifest);
zip.file('META-INF/CERT.SF', signatureFile, { compression: 'DEFLATE' });
// Create CERT.RSA (PKCS#7 signature block)
const signatureBlock = createSignatureBlock(signatureFile, key);
zip.file('META-INF/CERT.RSA', signatureBlock, { compression: 'DEFLATE' });
// Generate the signed APK
// Don't use global compression - preserve original compression settings
// This is critical for resources.arsc which must be STORE (uncompressed) on Android 11+
const signedApkRaw = await zip.generateAsync({
type: 'arraybuffer',
// Use per-file compression to preserve original settings
// resources.arsc and .so files must stay uncompressed
});
// Apply zipalign to ensure 4-byte alignment for uncompressed files
// This is required for Android 11+ (API 30+)
const alignedApk = zipalign(new Uint8Array(signedApkRaw), 4);
// Apply APK Signature Scheme v2
// This is required for Android 7.0+ and mandatory for Android 11+
const v2SignedApk = applyV2Signature(alignedApk, key);
return new Blob([v2SignedApk], { type: 'application/vnd.android.package-archive' });
}
/**
* Create MANIFEST.MF with SHA-256 digests of all files
*/
async function createManifest(zip: JSZip): Promise<string> {
const lines: string[] = [
'Manifest-Version: 1.0',
'Created-By: Shakespeare APK Signer',
'',
];
// Get all files (excluding META-INF directory)
const files = Object.keys(zip.files)
.filter(name => !zip.files[name].dir && !name.startsWith('META-INF/'))
.sort();
for (const fileName of files) {
const file = zip.files[fileName];
const content = await file.async('uint8array');
const digest = sha256Base64(content);
lines.push(`Name: ${fileName}`);
lines.push(`SHA-256-Digest: ${digest}`);
lines.push('');
}
return lines.join('\r\n');
}
/**
* Create CERT.SF (signature file) with digests of manifest sections
*/
function createSignatureFile(manifest: string): string {
const lines: string[] = [
'Signature-Version: 1.0',
'Created-By: Shakespeare APK Signer',
`SHA-256-Digest-Manifest: ${sha256Base64(new TextEncoder().encode(manifest))}`,
'',
];
// Parse manifest sections and create digests for each
const sections = manifest.split('\r\n\r\n');
for (let i = 1; i < sections.length; i++) {
const section = sections[i];
if (!section.trim()) continue;
// Extract the Name attribute
const nameMatch = section.match(/^Name: (.+)$/m);
if (nameMatch) {
const sectionWithNewline = section + '\r\n\r\n';
const digest = sha256Base64(new TextEncoder().encode(sectionWithNewline));
lines.push(`Name: ${nameMatch[1]}`);
lines.push(`SHA-256-Digest: ${digest}`);
lines.push('');
}
}
return lines.join('\r\n');
}
/**
* Create CERT.RSA (PKCS#7 signature block)
*/
function createSignatureBlock(signatureFile: string, key: SigningKey): Uint8Array {
const { privateKey, certificate } = key;
// Create SHA-256 digest of the signature file
const md = forge.md.sha256.create();
md.update(signatureFile, 'utf8');
// Sign the digest directly with RSA
// Type assertion needed due to node-forge type definition issues
const rsaPrivateKey = privateKey as unknown as forge.pki.rsa.PrivateKey;
const signature = rsaPrivateKey.sign(md);
// Build PKCS#7 SignedData structure manually
// This avoids the recursion issues in forge.pkcs7
// Use PEM->DER conversion to avoid certificateToAsn1 recursion issues
const certPem = forge.pki.certificateToPem(certificate);
const certDerBase64 = certPem
.replace(/-----BEGIN CERTIFICATE-----/, '')
.replace(/-----END CERTIFICATE-----/, '')
.replace(/\r?\n/g, '');
const certDer = forge.util.decode64(certDerBase64);
const certAsn1 = forge.asn1.fromDer(certDer);
// Build issuer DN ASN.1
let issuerAsn1;
if (certificate.issuer.attributes.length > 0) {
issuerAsn1 = forge.pki.distinguishedNameToAsn1(certificate.issuer);
} else {
issuerAsn1 = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, []);
}
const signerInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
// version
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
forge.asn1.integerToDer(1).getBytes()),
// issuerAndSerialNumber
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
// issuer
issuerAsn1,
// serialNumber
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
forge.util.hexToBytes(certificate.serialNumber)),
]),
// digestAlgorithm (SHA-256)
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes()),
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
]),
// digestEncryptionAlgorithm (RSA)
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
forge.asn1.oidToDer('1.2.840.113549.1.1.1').getBytes()),
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
]),
// encryptedDigest (the signature)
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OCTETSTRING, false, signature),
]);
const signedData = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
// version
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
forge.asn1.integerToDer(1).getBytes()),
// digestAlgorithms
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes()),
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
]),
]),
// contentInfo (empty for detached signature)
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
forge.asn1.oidToDer('1.2.840.113549.1.7.1').getBytes()),
]),
// certificates (implicit tag 0)
forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [certAsn1]),
// signerInfos
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [signerInfo]),
]);
// Wrap in ContentInfo
const contentInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
// contentType (signedData)
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
forge.asn1.oidToDer('1.2.840.113549.1.7.2').getBytes()),
// content
forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [signedData]),
]);
const der = forge.asn1.toDer(contentInfo);
return new Uint8Array(forge.util.binary.raw.decode(der.getBytes()));
}
/**
* Calculate SHA-256 hash and return as base64
*/
function sha256Base64(data: Uint8Array): string {
const md = forge.md.sha256.create();
// forge.util.binary.raw.encode uses String.fromCharCode.apply which causes
// stack overflow for large arrays. Build string manually.
const len = data.length;
const chunkSize = 8192;
for (let i = 0; i < len; i += chunkSize) {
const end = Math.min(i + chunkSize, len);
let chunk = '';
for (let j = i; j < end; j++) {
chunk += String.fromCharCode(data[j]);
}
md.update(chunk);
}
const digest = md.digest();
return forge.util.encode64(digest.getBytes());
}
/**
* Generate a new signing key pair and self-signed certificate
*/
export function generateSigningKey(options: {
commonName: string;
organizationName?: string;
countryCode?: string;
validityYears?: number;
alias?: string;
}): SigningKey {
const {
commonName,
organizationName = 'Shakespeare',
countryCode = 'US',
validityYears = 25,
alias = 'key0',
} = options;
// Generate RSA key pair
const keys = forge.pki.rsa.generateKeyPair(2048);
// Create certificate
const cert = forge.pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = '01' + forge.util.bytesToHex(forge.random.getBytesSync(8));
// Set validity
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + validityYears);
// Set subject/issuer attributes
const attrs = [
{ name: 'commonName', value: commonName },
{ name: 'organizationName', value: organizationName },
{ name: 'countryName', value: countryCode },
];
cert.setSubject(attrs);
cert.setIssuer(attrs);
// Set extensions
cert.setExtensions([
{
name: 'basicConstraints',
cA: false,
},
{
name: 'keyUsage',
digitalSignature: true,
keyEncipherment: true,
},
{
name: 'extKeyUsage',
codeSigning: true,
},
]);
// Self-sign the certificate
cert.sign(keys.privateKey, forge.md.sha256.create());
return {
privateKey: keys.privateKey,
certificate: cert,
alias,
};
}
/**
* Export signing key to PKCS#12 format (.p12)
*/
export function exportKeyToPkcs12(key: SigningKey, password: string): Uint8Array {
// Type assertion needed due to node-forge type definition issues
const p12Asn1 = forge.pkcs12.toPkcs12Asn1(
key.privateKey as unknown as Parameters<typeof forge.pkcs12.toPkcs12Asn1>[0],
[key.certificate],
password,
{
friendlyName: key.alias,
algorithm: '3des', // Use 3DES for compatibility
}
);
const p12Der = forge.asn1.toDer(p12Asn1);
return new Uint8Array(forge.util.binary.raw.decode(p12Der.getBytes()));
}
/**
* Import signing key from PKCS#12 format (.p12 / .pfx)
*/
export function importKeyFromPkcs12(data: ArrayBuffer, password: string): SigningKey {
const p12Der = forge.util.binary.raw.encode(new Uint8Array(data));
const p12Asn1 = forge.asn1.fromDer(p12Der);
const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, password);
// Find the private key and certificate
let privateKey: forge.pki.PrivateKey | null = null;
let certificate: forge.pki.Certificate | null = null;
let alias = 'key0';
for (const safeContents of p12.safeContents) {
for (const safeBag of safeContents.safeBags) {
if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag && safeBag.key) {
privateKey = safeBag.key;
if (safeBag.attributes?.friendlyName?.[0]) {
alias = safeBag.attributes.friendlyName[0];
}
} else if (safeBag.type === forge.pki.oids.certBag && safeBag.cert) {
certificate = safeBag.cert;
}
}
}
if (!privateKey || !certificate) {
throw new Error('Could not find private key and certificate in PKCS#12 file');
}
return { privateKey, certificate, alias };
}
/**
* Check if data is a JKS (Java KeyStore) file and throw helpful error
* Note: JKS is a proprietary format. For best compatibility, convert to PKCS#12 first:
* keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12
*/
export function checkJksAndThrow(data: ArrayBuffer): never {
const view = new DataView(data);
// JKS magic number: 0xFEEDFEED
const magic = view.getUint32(0, false);
if (magic === 0xFEEDFEED) {
throw new Error(
'JKS format is not directly supported. Please convert to PKCS#12 format using:\n' +
'keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12'
);
}
throw new Error('Unknown keystore format. Please use PKCS#12 (.p12 / .pfx) format.');
}
-15
View File
@@ -260,19 +260,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// not a URL; continue
}
// Check if this is a file: dependency
const allDeps = {
...packageJson.dependencies,
...packageJson.devDependencies,
...packageJson.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Let fsPlugin handle file: dependencies
return;
}
// Determine importer lock path (breadcrumb)
const importerLockPath = getImporterLockPath(args.importer);
@@ -443,8 +430,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
if (contentType) {
if (contentType === "application/javascript") {
loader = "js";
} else if (contentType === "application/json") {
loader = "json";
} else if (contentType === "text/css") {
loader = "css";
} else if (contentType === "application/wasm") {
+9 -95
View File
@@ -10,21 +10,14 @@ interface TsConfig {
};
}
interface PackageJson {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
}
interface FsPluginOptions {
fs: JSRuntimeFS;
cwd: string;
tsconfig?: TsConfig;
packageJson?: PackageJson;
}
export function fsPlugin(options: FsPluginOptions): Plugin {
const { fs, cwd, tsconfig, packageJson } = options;
const { fs, cwd, tsconfig } = options;
return {
name: "fs",
@@ -37,65 +30,21 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
});
build.onResolve({ filter: /.*/ }, async (args) => {
// Skip resolving paths from external URLs (but not fs: namespace)
// Skip resolving paths from external URLs
if (/^https?:\/\//.test(args.importer)) {
return;
}
let resolved: string | undefined;
// Handle absolute paths
let resolved: string;
if (args.path.startsWith("/")) {
resolved = args.path;
}
// Handle @/ alias
else if (args.path.startsWith("@/")) {
} else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2));
}
// Handle relative paths
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
// Remove fs: prefix from importer if present
const importerPath = args.importer.replace(/^fs:/, '');
resolved = join(dirname(importerPath), args.path);
}
// Handle bare imports (e.g., "react", "@scope/package")
else if (args.path.match(/^[^./]/)) {
// Check if this is a file: dependency
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const allDeps = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
...packageJson?.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Extract the file path (e.g., "file:./path" -> "./path")
const filePath = depVersion.slice(5); // Remove "file:" prefix
const packagePath = join(cwd, filePath);
// Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file")
const subpath = args.path.slice(packageName.length);
resolved = join(packagePath, subpath);
} else {
return; // Let esmPlugin handle this
}
}
// Handle tsconfig baseUrl
else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
resolved = join(dirname(args.importer), args.path);
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
}
// Nothing matched, let other plugins handle it
else {
return;
}
if (!resolved) {
} else {
return;
}
@@ -165,43 +114,8 @@ async function tryFileVariants(
return basePath;
}
// If it's a directory, try package.json first, then index files
// If it's a directory, try index files
if (stat.isDirectory()) {
// Try to read package.json for entry point
try {
const packageJsonPath = join(basePath, "package.json");
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonText);
// Check for various entry point fields
const entryPoint = packageJson.exports?.['.']
|| packageJson.module
|| packageJson.main
|| 'index.js';
// Resolve the entry point
const entryPath = typeof entryPoint === 'string'
? join(basePath, entryPoint)
: join(basePath, 'index.js');
const entryStat = await statSafe(fs, entryPath);
if (entryStat.isFile()) {
return entryPath;
}
// Try with different extensions if the entry point doesn't exist
for (const ext of extensions) {
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
const entryExtStat = await statSafe(fs, entryWithExt);
if (entryExtStat.isFile()) {
return entryWithExt;
}
}
} catch {
// package.json doesn't exist or is invalid, fall through to index files
}
// Fall back to trying index files
for (const ext of extensions) {
const indexFile = join(basePath, "index" + ext);
const indexStat = await statSafe(fs, indexFile);
-59
View File
@@ -535,63 +535,4 @@ react@^18.0.0:
// Verify tsconfig.json was attempted to be read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/tsconfig.json', 'utf8');
});
it('should support file: dependencies in package.json', async () => {
const packageJsonWithFileDeps = JSON.stringify({
name: "test-project",
dependencies: {
"@bitchat/capacitor-ble-mesh": "file:./capacitor-bitchat-mesh",
"react": "^18.2.0"
}
});
// Mock required files
vi.mocked(mockFS.readFile)
.mockImplementation(async (path: string) => {
if (path.endsWith('package.json')) {
return packageJsonWithFileDeps;
}
if (path.endsWith('index.html')) {
return '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
}
if (path.endsWith('package-lock.json')) {
return '{"dependencies": {}}';
}
throw new Error(`File not found: ${path}`);
});
// Mock stat to indicate no public directory
vi.mocked(mockFS.stat)
.mockImplementation(async (path: string) => {
if (path === '/test/project/public') {
throw new Error('Directory not found');
}
return { isDirectory: () => false, isFile: () => true };
});
// Mock additional filesystem operations for buildProject
vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => {
if (path === '/test/project/dist') {
return [];
}
return [];
});
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await buildProject({
fs: mockFS,
projectPath: '/test/project',
domParser: mockDOMParser,
esmUrl: 'https://esm.shakespeare.diy',
});
// Should successfully build with file: dependencies
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// Verify package.json was read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
});
});
+1 -1
View File
@@ -130,7 +130,7 @@ async function bundle(
assetNames: "[name]-[hash]",
plugins: [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig, packageJson }),
fsPlugin({ fs, cwd: projectPath, tsconfig }),
esmPlugin({ packageJson, packageLock, target, esmUrl }),
],
define: {
+1 -1
View File
@@ -66,7 +66,7 @@ export class CurlCommand implements ShellCommand {
// Proxy the URL through configured CorsProxy
const originalUrl = url.toString();
const proxiedUrl = proxyUrl({ template: this.corsProxy, url: originalUrl });
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
// Prepare request
const requestInit: RequestInit = {
+7 -1
View File
@@ -37,7 +37,6 @@ const aiProviderSchema = z.object({
apiKey: z.string().optional(),
nostr: z.boolean().optional(),
proxy: z.boolean().optional(),
openSecret: z.string().url().optional(),
});
const providerModelSchema = z.string().regex(
@@ -130,6 +129,12 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
baseDomain: z.string().optional(),
});
const apkBuilderProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('apkbuilder'),
buildServerUrl: z.string().url(),
apiKey: z.string(),
});
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
@@ -137,6 +142,7 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
nsiteProviderSchema,
cloudflareProviderSchema,
denoDeployProviderSchema,
apkBuilderProviderSchema,
]);
const deploySettingsSchema = z.object({
+203
View File
@@ -0,0 +1,203 @@
import JSZip from 'jszip';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, APKBuilderDeployConfig, APKBuildType } from './types';
import { proxyUrl } from '../proxyUrl';
interface APKBuildStatus {
id: string;
status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled';
progress: number;
error?: string;
apkSize?: number;
logs?: string[];
}
/**
* APK Builder Deploy Adapter
* Builds Android APKs from web projects using a Capacitor build service
*/
export class APKBuilderAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private buildServerUrl: string;
private apiKey: string;
private appName: string;
private packageId: string;
private buildType: APKBuildType;
private corsProxy?: string;
private onProgress?: (status: APKBuildStatus) => void;
constructor(config: APKBuilderDeployConfig) {
this.fs = config.fs;
this.buildServerUrl = config.buildServerUrl.replace(/\/$/, '');
this.apiKey = config.apiKey;
this.appName = config.appName;
this.packageId = config.packageId;
this.buildType = config.buildType || 'debug';
this.corsProxy = config.corsProxy;
this.onProgress = config.onProgress;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectPath } = options;
const distPath = `${projectPath}/dist`;
// Verify dist exists
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No dist folder found. Build the project first using the Build button.');
}
// Create ZIP of dist folder
const zip = new JSZip();
const distFolder = zip.folder('dist');
if (!distFolder) {
throw new Error('Failed to create ZIP folder');
}
await this.addDirectoryToZip(distPath, distFolder);
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Submit build request
const buildId = await this.submitBuild(zipBlob);
// Poll for completion
const result = await this.waitForBuild(buildId);
return result;
}
private async submitBuild(zipBlob: Blob): Promise<string> {
const url = `${this.buildServerUrl}/api/build`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const formData = new FormData();
formData.append('project', zipBlob, 'project.zip');
formData.append('config', JSON.stringify({
appName: this.appName,
packageId: this.packageId,
buildType: this.buildType,
}));
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'X-API-Key': this.apiKey,
},
body: formData,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `Build submission failed: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data.buildId;
}
private async waitForBuild(buildId: string): Promise<DeployResult> {
const maxWait = 10 * 60 * 1000; // 10 minutes
const pollInterval = 3000; // 3 seconds
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
const status = await this.getStatus(buildId);
if (this.onProgress) {
this.onProgress(status);
}
if (status.status === 'complete') {
// Fetch APK with header auth and create blob URL
const apkBlobUrl = await this.downloadApk(buildId);
return {
url: apkBlobUrl,
metadata: {
buildId,
type: 'apk',
appName: this.appName,
packageId: this.packageId,
buildType: this.buildType,
apkSize: status.apkSize,
},
};
}
if (status.status === 'failed') {
throw new Error(status.error || 'APK build failed');
}
if (status.status === 'cancelled') {
throw new Error('APK build was cancelled');
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('APK build timed out after 10 minutes');
}
private async downloadApk(buildId: string): Promise<string> {
const url = `${this.buildServerUrl}/api/build/${buildId}/download`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'X-API-Key': this.apiKey,
},
});
if (!response.ok) {
throw new Error(`Failed to download APK: ${response.status} ${response.statusText}`);
}
const blob = await response.blob();
return URL.createObjectURL(blob);
}
private async getStatus(buildId: string): Promise<APKBuildStatus> {
const url = `${this.buildServerUrl}/api/build/${buildId}/status`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'X-API-Key': this.apiKey,
},
});
if (!response.ok) {
throw new Error(`Failed to get build status: ${response.status}`);
}
return response.json();
}
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fullPath, folder);
}
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
}
}
} catch {
console.warn(`Failed to read directory ${dirPath}`);
}
}
}
+5 -5
View File
@@ -140,7 +140,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async getWorkersSubdomain(): Promise<string> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -160,7 +160,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async enableWorkersDevSubdomain(scriptName: string): Promise<void> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -185,7 +185,7 @@ export class CloudflareAdapter implements DeployAdapter {
manifest: AssetManifest
): Promise<InitializeAssetsResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -211,7 +211,7 @@ export class CloudflareAdapter implements DeployAdapter {
hashToFile: Map<string, { path: string; info: FileInfo }>
): Promise<UploadResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const formData = new FormData();
@@ -251,7 +251,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async deployWorker(scriptName: string, assetsJwt: string): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
// Create a minimal worker script that serves static assets
// This is an assets-only worker - Cloudflare will automatically serve the uploaded assets
+3 -3
View File
@@ -96,7 +96,7 @@ export class DenoDeployAdapter implements DeployAdapter {
private async findProject(projectName: string): Promise<Project | null> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -116,7 +116,7 @@ export class DenoDeployAdapter implements DeployAdapter {
private async createProject(projectName: string): Promise<Project> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -143,7 +143,7 @@ export class DenoDeployAdapter implements DeployAdapter {
domain: string
): Promise<Deployment> {
const url = `${this.baseURL}/projects/${projectId}/deployments`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
// Create a minimal server script that serves static files
// For static sites, we use a simple file server entry point
+3 -3
View File
@@ -89,7 +89,7 @@ export class NetlifyAdapter implements DeployAdapter {
private async createSite(name: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -113,7 +113,7 @@ export class NetlifyAdapter implements DeployAdapter {
private async getSite(siteId: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites/${siteId}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -132,7 +132,7 @@ export class NetlifyAdapter implements DeployAdapter {
private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
const url = `${this.baseURL}/sites/${siteId}/deploys`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
+1 -1
View File
@@ -72,7 +72,7 @@ export class ShakespeareAdapter implements DeployAdapter {
// Apply proxy if configured
if (this.corsProxy) {
request = new Request(proxyUrl({ template: this.corsProxy, url: request.url }), request);
request = new Request(proxyUrl(this.corsProxy, request.url), request);
}
// Deploy
+1 -1
View File
@@ -68,7 +68,7 @@ export class VercelAdapter implements DeployAdapter {
}
// Apply proxy if configured
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: apiUrl }) : apiUrl;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, apiUrl) : apiUrl;
// Deploy to Vercel
const response = await fetch(targetUrl, {
+1
View File
@@ -5,3 +5,4 @@ export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
export * from './DenoDeployAdapter';
export * from './APKBuilderAdapter';
+43 -1
View File
@@ -75,9 +75,50 @@ export interface DenoDeployConfig {
corsProxy?: string;
}
/** Build type for APK */
export type APKBuildType = 'debug' | 'release';
/** Keystore configuration for release builds */
export interface KeystoreConfig {
/** Keystore data as base64 */
keystoreBase64: string;
/** Keystore password */
keystorePassword: string;
/** Key alias */
keyAlias: string;
/** Key password */
keyPassword: string;
}
export interface APKBuilderDeployConfig {
fs: JSRuntimeFS;
/** URL of the APK build server */
buildServerUrl: string;
/** API key for the build server */
apiKey: string;
/** Display name of the Android app */
appName: string;
/** Android package ID (e.g., com.example.myapp) */
packageId: string;
/** Build type: debug (default) or release */
buildType?: APKBuildType;
/** Keystore configuration for release builds (browser-based signing) */
keystoreConfig?: KeystoreConfig;
/** Optional CORS proxy */
corsProxy?: string;
/** Optional progress callback */
onProgress?: (status: {
id: string;
status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled';
progress: number;
error?: string;
logs?: string[];
}) => void;
}
export interface PresetDeployProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder';
name: string;
description: string;
baseURL?: string;
@@ -88,5 +129,6 @@ export interface PresetDeployProvider {
accountIdURL?: string;
organizationIdLabel?: string;
organizationIdURL?: string;
buildServerUrlLabel?: string;
proxy?: boolean;
}
+10
View File
@@ -60,4 +60,14 @@ export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
organizationIdURL: 'https://dash.deno.com/orgs',
proxy: true,
},
{
id: 'apkbuilder',
type: 'apkbuilder',
name: 'APK Builder',
description: 'Build Android APKs from your web app',
baseURL: 'https://android.com',
buildServerUrlLabel: 'Build Server URL',
apiKeyLabel: 'API Key',
proxy: true,
},
];
+5 -11
View File
@@ -1,21 +1,15 @@
import UriTemplate from 'uri-templates';
export interface FaviconUrlOpts {
template: string;
url: string | URL;
}
/**
* Generate a favicon URL from a template and input URL
* @param opts - Options object
* @param opts.template - URL template with placeholders like {hostname}, {origin}, etc.
* @param opts.url - The URL to extract parts from
* @param template - URL template with placeholders like {hostname}, {origin}, etc.
* @param url - The URL to extract parts from
* @returns The hydrated favicon URL
*/
export function faviconUrl(opts: FaviconUrlOpts): string {
const u = new URL(opts.url);
export function faviconUrl(template: string, url: string | URL): string {
const u = new URL(url);
return UriTemplate(opts.template).fill({
return UriTemplate(template).fill({
href: u.href,
origin: u.origin,
protocol: u.protocol,
+2 -2
View File
@@ -1107,7 +1107,7 @@ class GitHttp implements HttpClient {
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
this.proxy = proxy;
this.fetch = fetch ?? globalThis.fetch;
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
}
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
@@ -1115,7 +1115,7 @@ class GitHttp implements HttpClient {
const url = new URL(request.url);
const target = this.proxy
? proxyUrl({ template: this.proxy, url })
? proxyUrl(this.proxy, url)
: url.href;
const init: RequestInit = {
+6 -6
View File
@@ -9,7 +9,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl({ template, nostrURI });
const result = ngitWebUrl(template, nostrURI);
expect(result).toMatch(/^https:\/\/nostrhub\.io\/naddr1/);
});
@@ -20,7 +20,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl({ template, nostrURI });
const result = ngitWebUrl(template, nostrURI);
expect(result).toMatch(/^https:\/\/example\.com\/npub1/);
});
@@ -31,7 +31,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl({ template, nostrURI });
const result = ngitWebUrl(template, nostrURI);
expect(result).toBe(`https://example.com/${pubkey}`);
});
@@ -42,7 +42,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl({ template, nostrURI });
const result = ngitWebUrl(template, nostrURI);
expect(result).toBe('https://example.com/my-repo');
});
@@ -53,7 +53,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl({ template, nostrURI });
const result = ngitWebUrl(template, nostrURI);
expect(result).toMatch(/^https:\/\/example\.com\/npub1[^/]+\/my-repo$/);
});
@@ -65,7 +65,7 @@ describe('ngitWebUrl', () => {
const relay = 'wss://relay.example.com/';
const nostrURI = new NostrURI({ pubkey, identifier, relay });
const result = ngitWebUrl({ template, nostrURI });
const result = ngitWebUrl(template, nostrURI);
// The naddr should be longer when it includes relay information
expect(result).toMatch(/^https:\/\/nostrhub\.io\/naddr1/);
+8 -14
View File
@@ -2,26 +2,20 @@ import UriTemplate from 'uri-templates';
import { nip19 } from 'nostr-tools';
import { NostrURI } from './NostrURI';
export interface NgitWebUrlOpts {
template: string;
nostrURI: NostrURI;
}
/**
* Generate a Nostr Git web URL from a template and Nostr URI
* @param opts - Options object
* @param opts.template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
* @param opts.nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
* @param template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
* @param nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
* @returns The hydrated web URL
*/
export function ngitWebUrl(opts: NgitWebUrlOpts): string {
const naddr = opts.nostrURI.toNaddr();
const npub = nip19.npubEncode(opts.nostrURI.pubkey);
export function ngitWebUrl(template: string, nostrURI: NostrURI): string {
const naddr = nostrURI.toNaddr();
const npub = nip19.npubEncode(nostrURI.pubkey);
return UriTemplate(opts.template).fill({
return UriTemplate(template).fill({
naddr,
npub,
pubkey: opts.nostrURI.pubkey,
identifier: opts.nostrURI.identifier,
pubkey: nostrURI.pubkey,
identifier: nostrURI.identifier,
});
}
+117
View File
@@ -0,0 +1,117 @@
/**
* NIP-98 HTTP Auth utilities
* Creates signed events for HTTP authentication
*/
import type { NostrSigner, NostrEvent } from '@nostrify/nostrify';
import { proxyUrl } from './proxyUrl';
/**
* Create a NIP-98 auth event for HTTP requests
*/
export async function createNip98AuthEvent(
signer: NostrSigner,
url: string,
method: string,
payload?: string
): Promise<NostrEvent> {
const tags: string[][] = [
['u', url],
['method', method.toUpperCase()],
];
// Add payload hash if provided
if (payload) {
const encoder = new TextEncoder();
const data = encoder.encode(payload);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
tags.push(['payload', hashHex]);
}
const event = await signer.signEvent({
kind: 27235,
content: '',
tags,
created_at: Math.floor(Date.now() / 1000),
});
return event;
}
/**
* Create Authorization header value from NIP-98 event
*/
export function createNip98AuthHeader(event: NostrEvent): string {
const eventJson = JSON.stringify(event);
const base64 = btoa(eventJson);
return `Nostr ${base64}`;
}
/**
* Perform a NIP-98 authenticated request
*/
export async function nip98Fetch(
signer: NostrSigner,
url: string,
options: RequestInit = {}
): Promise<Response> {
const method = options.method || 'GET';
const body = options.body as string | undefined;
const event = await createNip98AuthEvent(signer, url, method, body);
const authHeader = createNip98AuthHeader(event);
return fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': authHeader,
},
});
}
/**
* Request an API key from a build server using NIP-98 auth
*/
export async function requestBuildServerApiKey(
signer: NostrSigner,
buildServerUrl: string,
corsProxy?: string
): Promise<{ apiKey: string; pubkey: string; isNew: boolean }> {
const authUrl = `${buildServerUrl.replace(/\/+$/, '')}/api/auth`;
// Create the auth event
const event = await createNip98AuthEvent(signer, authUrl, 'POST');
const authHeader = createNip98AuthHeader(event);
// Make the request (use CORS proxy if provided)
const targetUrl = corsProxy
? proxyUrl(corsProxy, authUrl)
: authUrl;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const error = await response.json().catch(() => ({ error: 'Request failed' }));
throw new Error(error.error || `HTTP ${response.status}`);
}
const data = await response.json();
if (!data.success || !data.apiKey) {
throw new Error(data.error || 'Failed to get API key');
}
return {
apiKey: data.apiKey,
pubkey: data.pubkey,
isNew: data.isNew,
};
}
+3 -8
View File
@@ -1,13 +1,8 @@
import UriTemplate from 'uri-templates';
export interface ProxyUrlOpts {
template: string;
url: string | URL;
}
export function proxyUrl(opts: ProxyUrlOpts): string {
const u = new URL(opts.url);
return UriTemplate(opts.template).fill({
export function proxyUrl(template: string, url: string | URL): string {
const u = new URL(url);
return UriTemplate(template).fill({
href: u.href,
origin: u.origin,
protocol: u.protocol,
+1 -1
View File
@@ -137,7 +137,7 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
}
} else if (firstImage.url) {
// Fetch the image from the URL
const imageUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: firstImage.url }) : firstImage.url;
const imageUrl = this.corsProxy ? proxyUrl(this.corsProxy, firstImage.url) : firstImage.url;
const imageResponse = await fetch(imageUrl);
if (!imageResponse.ok) {
+1 -1
View File
@@ -35,7 +35,7 @@ import {
UnzipCommand,
WcCommand,
WhoamiCommand,
WhichCommand
WhichCommand,
} from "../commands";
interface ShellToolParams {
+18 -5
View File
@@ -54,9 +54,12 @@
"showcaseModerator": "Showcase Moderator",
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
"filesystemPaths": "Filesystem Paths",
"projectsDirectory": "Projects",
"configDirectory": "Config",
"temporaryDirectory": "Temporary",
"projectsDirectory": "Projects Directory",
"projectsDirectoryDescription": "Filesystem path where projects are stored",
"configDirectory": "Config Directory",
"configDirectoryDescription": "Filesystem path where configuration files are stored",
"temporaryDirectory": "Temporary Directory",
"temporaryDirectoryDescription": "Filesystem path for temporary files",
"sentryDsn": "Sentry DSN",
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
"shareErrorReports": "Share error reports",
@@ -481,7 +484,8 @@
"skills": "Skills",
"noSkillsFound": "No skills found in this plugin.",
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
"pluginsDirectory": "Plugins",
"pluginsDirectory": "Plugins Directory",
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
"discoverPlugins": "Discover Plugins",
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
"searchPlugins": "Search plugins...",
@@ -522,12 +526,21 @@
"discoveringTools": "Discovering tools...",
"toolsDiscovered": "{{count}} tool(s) discovered",
"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...",
"modified": "Modified",
"restoreToDefault": "Restore to default",
"restoredToDefault": "Restored to Default",
"templateUpdateFailed": "Template Update Failed",
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
"templatesDirectory": "Templates",
"templatesDirectory": "Templates Directory",
"templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.",
"terminal": "Terminal",
"templateName": "Template Name",
"templateDescription": "Description",
+1 -16
View File
@@ -16,7 +16,6 @@ import { CreditsBadge } from '@/components/CreditsBadge';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
@@ -46,7 +45,6 @@ export function AISettings() {
const { settings, updateSettings, setProvider, removeProvider, setProviders, isLoading } = useAISettings();
const { user } = useCurrentUser();
const { config, defaultConfig, updateConfig } = useAppContext();
const openRouterOAuth = useOpenRouterOAuth();
const [showAdvanced, setShowAdvanced] = useState(false);
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
@@ -56,7 +54,6 @@ export function AISettings() {
const [selectedPreset, setSelectedPreset] = useState<PresetProvider | null>(null);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
const [forceManualEntry, setForceManualEntry] = useState(false);
// Drag and drop sensors
const sensors = useSensors(
@@ -118,9 +115,6 @@ export function AISettings() {
if (typeof preset.proxy === 'boolean') {
newProvider.proxy = preset.proxy;
}
if (preset.openSecret) {
newProvider.openSecret = preset.openSecret;
}
setProvider(newProvider);
};
@@ -262,18 +256,9 @@ export function AISettings() {
{selectedPreset && (
<AddAIProviderDialog
open={addDialogOpen}
onOpenChange={(open) => {
setAddDialogOpen(open);
if (!open) {
// Reset force manual entry when dialog closes
setForceManualEntry(false);
}
}}
onOpenChange={setAddDialogOpen}
preset={selectedPreset}
isLoggedIntoNostr={!!user}
oauthHook={selectedPreset.id === 'openrouter' ? openRouterOAuth : null}
forceManualEntry={forceManualEntry}
onSetForceManualEntry={setForceManualEntry}
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
/>
)}
+19 -5
View File
@@ -12,7 +12,7 @@ import type { PresetDeployProvider } from '@/lib/deploy/types';
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
import { AddProviderDialog } from '@/components/AddProviderDialog';
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
import {
DndContext,
@@ -181,7 +181,7 @@ export function DeploySettings() {
setAddDialogOpen(true);
};
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string) => {
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => {
// For Shakespeare, just check if user is logged in
if (preset.requiresNostr && !user) {
return;
@@ -260,6 +260,18 @@ export function DeploySettings() {
organizationId: organizationId.trim(),
...(preset.proxy && { proxy: true }),
};
} else if (preset.type === 'apkbuilder') {
if (!buildServerUrl?.trim() || !apiKey?.trim()) {
return;
}
newProvider = {
id: preset.id,
name: preset.name,
type: 'apkbuilder',
buildServerUrl: buildServerUrl.trim(),
apiKey: apiKey.trim(),
...(preset.proxy && { proxy: true }),
};
} else {
return; // Unknown type
}
@@ -278,6 +290,8 @@ export function DeploySettings() {
const handleRemoveProvider = (index: number) => {
removeProvider(index);
setDialogOpen(false);
setSelectedProviderIndex(null);
};
const handleUpdateProvider = (index: number, provider: DeployProvider) => {
@@ -384,7 +398,7 @@ export function DeploySettings() {
{/* Add Preset Provider Dialog */}
{selectedPreset && (
<AddDeployProviderDialog
<AddProviderDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
preset={selectedPreset}
@@ -397,8 +411,8 @@ export function DeploySettings() {
onSetForceManualEntry={(force) =>
setForceManualEntry(prev => ({ ...prev, [selectedPreset.id]: force }))
}
onAdd={(apiKey, accountId, organizationId) =>
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId)
onAdd={(apiKey, accountId, organizationId, buildServerUrl) =>
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId, buildServerUrl)
}
/>
)}
-96
View File
@@ -1,96 +0,0 @@
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>
);
}
+97 -197
View File
@@ -31,9 +31,6 @@ import { useGitAutosync } from '@/hooks/useGitAutosync';
import { useQueryClient } from '@tanstack/react-query';
import { cn } from '@/lib/utils';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { FloatingChatWidget } from '@/components/Shakespeare/FloatingChatWidget';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
export function ProjectView() {
const { projectId } = useParams<{ projectId: string }>();
@@ -62,16 +59,6 @@ export function ProjectView() {
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
// Floating chat state
const [isFloatingChatEnabled, setIsFloatingChatEnabled] = useLocalStorage(
'shk:floatingChatEnabled',
false
);
const [isFloatingChatMinimized, setIsFloatingChatMinimized] = useLocalStorage(
'shk:floatingChatMinimized',
false
);
const build = useBuildProject(projectId!);
const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!);
const { hasRunningSessions } = useProjectSessionStatus(projectId || '');
@@ -240,7 +227,7 @@ export function ProjectView() {
</div>
</div>
<div className="flex items-center gap-2 px-3">
<div className="flex items-center gap-4 px-3">
{project ? (
<>
<GitSyncButton
@@ -252,24 +239,6 @@ export function ProjectView() {
projectName={project.name}
disabled={isAnyLoading}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => {
setIsFloatingChatEnabled(true);
setIsFloatingChatMinimized(false);
}}
aria-label="Floating chat"
aria-pressed={isFloatingChatEnabled}
>
<MessageSquare className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Floating chat</TooltipContent>
</Tooltip>
</>
) : (
<>
@@ -420,23 +389,6 @@ export function ProjectView() {
/>
</>
)}
{/* Floating Chat Widget - Mobile */}
{isFloatingChatEnabled && project && (
<FloatingChatWidget
projectId={project.id}
isMinimized={isFloatingChatMinimized}
onToggleMinimize={() => setIsFloatingChatMinimized(!isFloatingChatMinimized)}
onClose={() => setIsFloatingChatEnabled(false)}
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
onDismissConsoleError={handleDismissConsoleError}
/>
)}
</div>
);
}
@@ -463,175 +415,123 @@ export function ProjectView() {
{/* Main Content Area */}
<div className="flex-1 flex flex-col overflow-hidden bg-background">
<div className="flex-1 overflow-hidden">
{isFloatingChatEnabled ? (
// Full-width preview/code when floating chat is enabled
<div className="h-full">
{project ? (
<PreviewPane
projectId={project.id}
activeTab={isPreviewable ? activeTab : 'code'}
onToggleView={isPreviewable ? () => setActiveTab(activeTab === 'preview' ? 'code' : 'preview') : undefined}
isPreviewable={isPreviewable}
/>
) : (
<div className="h-full p-4 space-y-4">
<Skeleton className="h-8 w-32" />
<Skeleton className="h-full w-full" />
</div>
)}
</div>
) : (
// Original resizable panel layout
<ResizablePanelGroup direction="horizontal" className="h-full">
{/* Chat Panel */}
<ResizablePanel defaultSize={35} minSize={25}>
<div className="h-full flex flex-col">
{/* Chat Header */}
<div className="h-12 px-4 border-b flex-shrink-0">
<div className="flex items-center justify-between h-12">
{/* Left side - Sidebar toggle (when collapsed) */}
<div className="flex items-center gap-3 overflow-hidden">
{!isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
className="h-8 w-8 p-0"
aria-label="Open sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
<ResizablePanelGroup direction="horizontal" className="h-full">
{/* Chat Panel */}
<ResizablePanel defaultSize={35} minSize={25}>
<div className="h-full flex flex-col">
{/* Chat Header */}
<div className="h-12 px-4 border-b flex-shrink-0">
<div className="flex items-center justify-between h-12">
{/* Left side - Sidebar toggle (when collapsed) */}
<div className="flex items-center gap-3 overflow-hidden">
{!isSidebarVisible && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(true)}
className="h-8 w-8 p-0"
aria-label="Open sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
{/* Project title */}
<div className="flex flex-1 min-w-0 truncate">
{project ? (
<ProjectTitleMenu
projectId={project.id}
projectName={project.name}
onNewChat={handleNewChat}
onGitHistory={() => setGitHistoryOpen(true)}
onDuplicate={() => setDuplicateDialogOpen(true)}
onDelete={() => setDeleteDialogOpen(true)}
onProjectDetails={() => setIsProjectDetailsOpen(true)}
isAILoading={isAILoading}
isAnyLoading={isAnyLoading || isDeleting}
className="text-lg"
/>
) : (
<Skeleton className="h-6 w-40" />
)}
</div>
</div>
{/* Right side - Deploy and Sync buttons */}
<div className="flex items-center gap-2">
{/* Project title */}
<div className="flex flex-1 min-w-0 truncate">
{project ? (
<>
<GitSyncButton
projectId={project.id}
className="h-8 w-8"
/>
<DeployButton
projectId={project.id}
projectName={project.name}
disabled={isAnyLoading}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setIsFloatingChatEnabled(true)}
aria-label="Floating chat"
aria-pressed={isFloatingChatEnabled}
>
<MessageSquare className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Floating chat</TooltipContent>
</Tooltip>
</>
<ProjectTitleMenu
projectId={project.id}
projectName={project.name}
onNewChat={handleNewChat}
onGitHistory={() => setGitHistoryOpen(true)}
onDuplicate={() => setDuplicateDialogOpen(true)}
onDelete={() => setDeleteDialogOpen(true)}
onProjectDetails={() => setIsProjectDetailsOpen(true)}
isAILoading={isAILoading}
isAnyLoading={isAnyLoading || isDeleting}
className="text-lg"
/>
) : (
<>
<Skeleton className="h-8 w-8 rounded" />
<Skeleton className="h-8 w-8 rounded" />
</>
<Skeleton className="h-6 w-40" />
)}
</div>
</div>
</div>
{/* Chat Content */}
<div className="flex-1 overflow-hidden">
{project ? (
<ChatPane
ref={chatPaneRef}
projectId={project.id}
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
onDismissConsoleError={handleDismissConsoleError}
/>
) : (
<div className="h-full p-4 space-y-4">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-8 w-3/4" />
<Skeleton className="h-8 w-1/2" />
<Skeleton className="h-32 w-full" />
</div>
)}
{/* Right side - Deploy and Sync buttons */}
<div className="flex items-center gap-2">
{project ? (
<>
<GitSyncButton
projectId={project.id}
className="h-8 w-8"
/>
<DeployButton
projectId={project.id}
projectName={project.name}
disabled={isAnyLoading}
/>
</>
) : (
<>
<Skeleton className="h-8 w-8 rounded" />
<Skeleton className="h-8 w-8 rounded" />
</>
)}
</div>
</div>
</div>
</ResizablePanel>
{/* Resizable Handle */}
<ResizableHandle withHandle />
{/* Preview/Code Panel */}
<ResizablePanel defaultSize={65} minSize={30}>
<div className="h-full">
{/* Chat Content */}
<div className="flex-1 overflow-hidden">
{project ? (
<PreviewPane
<ChatPane
ref={chatPaneRef}
projectId={project.id}
activeTab={isPreviewable ? activeTab : 'code'}
onToggleView={isPreviewable ? () => setActiveTab(activeTab === 'preview' ? 'code' : 'preview') : undefined}
isPreviewable={isPreviewable}
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
onDismissConsoleError={handleDismissConsoleError}
/>
) : (
<div className="h-full p-4 space-y-4">
<Skeleton className="h-8 w-32" />
<Skeleton className="h-full w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-8 w-3/4" />
<Skeleton className="h-8 w-1/2" />
<Skeleton className="h-32 w-full" />
</div>
)}
</div>
</ResizablePanel>
</ResizablePanelGroup>
)}
</div>
</ResizablePanel>
{/* Resizable Handle */}
<ResizableHandle withHandle />
{/* Preview/Code Panel */}
<ResizablePanel defaultSize={65} minSize={30}>
<div className="h-full">
{project ? (
<PreviewPane
projectId={project.id}
activeTab={isPreviewable ? activeTab : 'code'}
onToggleView={isPreviewable ? () => setActiveTab(activeTab === 'preview' ? 'code' : 'preview') : undefined}
isPreviewable={isPreviewable}
/>
) : (
<div className="h-full p-4 space-y-4">
<Skeleton className="h-8 w-32" />
<Skeleton className="h-full w-full" />
</div>
)}
</div>
</ResizablePanel>
</ResizablePanelGroup>
</div>
</div>
{/* Floating Chat Widget - Desktop */}
{isFloatingChatEnabled && project && (
<FloatingChatWidget
projectId={project.id}
isMinimized={isFloatingChatMinimized}
onToggleMinimize={() => setIsFloatingChatMinimized(!isFloatingChatMinimized)}
onClose={() => setIsFloatingChatEnabled(false)}
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
onDismissConsoleError={handleDismissConsoleError}
/>
)}
{/* Dialogs */}
{project && (
<>
+16 -2
View File
@@ -257,7 +257,6 @@ export function SystemSettings() {
icon={Settings}
titleKey="systemSettings"
descriptionKey="systemSettingsDescription"
className="space-y-2"
>
{/* Service Worker Configuration */}
<Accordion type="single" collapsible className="w-full">
@@ -768,7 +767,7 @@ export function SystemSettings() {
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 py-1">
<div className="py-1 space-y-4">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
@@ -805,6 +804,9 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('projectsDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
@@ -843,6 +845,9 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('configDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
@@ -881,6 +886,9 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('temporaryDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
@@ -919,6 +927,9 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('pluginsDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
@@ -957,6 +968,9 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('templatesDirectoryDescription')}
</p>
</div>
</div>
</AccordionContent>