mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 08:13:34 +00:00
Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f1b3e6b7e | ||
|
|
749d173cf4 | ||
|
|
a7b45b5068 | ||
|
|
d26d1051f1 | ||
|
|
d99a9e1c46 | ||
|
|
8be2ef7b22 | ||
|
|
75a0d637ce | ||
|
|
a84ba7385b | ||
|
|
2fdd9e6a49 | ||
|
|
67a77419df | ||
|
|
4676738a14 | ||
|
|
444dfbc5dd | ||
|
|
5d075e02ab | ||
|
|
6edc623c13 | ||
|
|
027cd819f8 | ||
|
|
ef55e80c35 | ||
|
|
3666aac2a1 | ||
|
|
f58f75ae8b | ||
|
|
22885e0978 | ||
|
|
a988238bb4 | ||
|
|
11197139f9 | ||
|
|
9ccad00888 | ||
|
|
32ff6570cf | ||
|
|
80bb72ef79 | ||
|
|
e45f167d2b | ||
|
|
7e755916c0 | ||
|
|
5915b96d98 | ||
|
|
b327607be3 | ||
|
|
e23b5031ee | ||
|
|
104a08c75a | ||
|
|
ddc23e3800 | ||
|
|
a1959369c5 | ||
|
|
6c4c1dab3b |
No files matched your search
+42
-2
@@ -15,6 +15,7 @@ The OAuth system consists of three main components:
|
||||
- **GitHub** - Git repository hosting (with PKCE support)
|
||||
- **Netlify** - Static site deployment
|
||||
- **Vercel** - Static site deployment
|
||||
- **OpenRouter** - AI model routing (with PKCE support)
|
||||
|
||||
## File Structure
|
||||
|
||||
@@ -24,11 +25,13 @@ src/
|
||||
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
||||
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
||||
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
||||
│ └── useVercelOAuth.ts # Vercel-specific configuration
|
||||
│ ├── useVercelOAuth.ts # Vercel-specific configuration
|
||||
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
|
||||
├── pages/
|
||||
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
||||
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
|
||||
│ └── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
|
||||
└── AppRouter.tsx # Routes for OAuth callbacks
|
||||
```
|
||||
|
||||
@@ -190,6 +193,7 @@ 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
|
||||
|
||||
@@ -199,6 +203,42 @@ 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
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"nostr": {
|
||||
"type": "local",
|
||||
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+51
-50
@@ -68,7 +68,6 @@
|
||||
"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,7 +107,6 @@
|
||||
"@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",
|
||||
@@ -197,6 +195,7 @@
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -1832,6 +1831,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
@@ -1855,6 +1855,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
@@ -1876,6 +1877,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
@@ -2814,9 +2816,9 @@
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.25.1",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.1.tgz",
|
||||
"integrity": "sha512-yO28oVFFC7EBoiKdAn+VqRm+plcfv4v0xp6osG/VsCB0NlPZWi87ajbCZZ8f/RvOFLEu7//rSRmuZZ7lMoe3gQ==",
|
||||
"version": "1.25.2",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.2.tgz",
|
||||
"integrity": "sha512-LZFeo4F9M5qOhC/Uc1aQSrBHxMrvxett+9KLHt7OhcExtoiRN9DKgbZffMP/nxjutWDQpfMDfP3nkHI4X9ijww==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@hono/node-server": "^1.19.7",
|
||||
@@ -4387,9 +4389,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@remix-run/router": {
|
||||
"version": "1.23.0",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
|
||||
"integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
|
||||
"version": "1.23.2",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
|
||||
"integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
@@ -5444,8 +5446,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
|
||||
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/chrome": {
|
||||
"version": "0.0.74",
|
||||
@@ -5615,16 +5616,6 @@
|
||||
"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",
|
||||
@@ -5667,6 +5658,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
|
||||
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.0.2"
|
||||
@@ -5678,6 +5670,7 @@
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
}
|
||||
@@ -5761,6 +5754,7 @@
|
||||
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.31.1",
|
||||
"@typescript-eslint/types": "8.31.1",
|
||||
@@ -6120,6 +6114,7 @@
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -6634,6 +6629,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.8.19",
|
||||
"caniuse-lite": "^1.0.30001751",
|
||||
@@ -6863,6 +6859,7 @@
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"anymatch": "~3.1.2",
|
||||
"braces": "~3.0.2",
|
||||
@@ -7622,8 +7619,7 @@
|
||||
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
|
||||
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dom-helpers": {
|
||||
"version": "5.2.1",
|
||||
@@ -7688,7 +7684,8 @@
|
||||
"version": "8.6.0",
|
||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
||||
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/embla-carousel-react": {
|
||||
"version": "8.6.0",
|
||||
@@ -7974,6 +7971,7 @@
|
||||
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.2.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -8239,6 +8237,7 @@
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
|
||||
"integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"accepts": "^2.0.0",
|
||||
"body-parser": "^2.2.0",
|
||||
@@ -9336,6 +9335,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.27.6"
|
||||
},
|
||||
@@ -10129,6 +10129,7 @@
|
||||
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"cssstyle": "^4.2.1",
|
||||
"data-urls": "^5.0.0",
|
||||
@@ -10513,7 +10514,6 @@
|
||||
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"lz-string": "bin/bin.js"
|
||||
}
|
||||
@@ -11753,15 +11753,6 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/node-forge": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.3.tgz",
|
||||
"integrity": "sha512-rLvcdSyRCyouf6jcOIPe/BgwG/d7hKjzMKOas33/pHEr6gbq18IK9zV7DiPvzsz0oBJPme6qr6H6kGZuI9/DZg==",
|
||||
"license": "(BSD-3-Clause OR GPL-2.0)",
|
||||
"engines": {
|
||||
"node": ">= 6.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/node-releases": {
|
||||
"version": "2.0.26",
|
||||
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.26.tgz",
|
||||
@@ -12276,6 +12267,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.8",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -12443,7 +12435,6 @@
|
||||
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1",
|
||||
"ansi-styles": "^5.0.0",
|
||||
@@ -12459,7 +12450,6 @@
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
@@ -12470,7 +12460,6 @@
|
||||
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
@@ -12483,8 +12472,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
|
||||
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/prismjs": {
|
||||
"version": "1.30.0",
|
||||
@@ -12569,9 +12557,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.14.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
|
||||
"integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
|
||||
"version": "6.14.1",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
|
||||
"integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"side-channel": "^1.1.0"
|
||||
@@ -12658,6 +12646,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -12684,6 +12673,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
@@ -12709,6 +12699,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
|
||||
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -12757,6 +12748,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
|
||||
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0",
|
||||
"@types/mdast": "^4.0.0",
|
||||
@@ -12837,12 +12829,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"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==",
|
||||
"version": "6.30.3",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz",
|
||||
"integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/router": "1.23.0"
|
||||
"@remix-run/router": "1.23.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
@@ -12852,13 +12844,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "6.30.0",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
|
||||
"integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
|
||||
"version": "6.30.3",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz",
|
||||
"integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/router": "1.23.0",
|
||||
"react-router": "6.30.0"
|
||||
"@remix-run/router": "1.23.2",
|
||||
"react-router": "6.30.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
@@ -13299,6 +13291,7 @@
|
||||
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "1.0.7"
|
||||
},
|
||||
@@ -14353,6 +14346,7 @@
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"arg": "^5.0.2",
|
||||
@@ -14556,6 +14550,7 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -14851,6 +14846,7 @@
|
||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -15378,6 +15374,7 @@
|
||||
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.4",
|
||||
@@ -15522,6 +15519,7 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -15993,6 +15991,7 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -16069,6 +16068,7 @@
|
||||
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"rollup": "dist/bin/rollup"
|
||||
},
|
||||
@@ -16517,6 +16517,7 @@
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
@@ -79,7 +79,6 @@
|
||||
"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,7 +118,6 @@
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
# APK Build Service - Nginx Configuration
|
||||
#
|
||||
# Usage:
|
||||
# 1. Copy to /etc/nginx/sites-available/apk-builder
|
||||
# 2. Update server_name to your domain
|
||||
# 3. Update SSL certificate paths (or use certbot)
|
||||
# 4. sudo ln -s /etc/nginx/sites-available/apk-builder /etc/nginx/sites-enabled/
|
||||
# 5. sudo nginx -t && sudo systemctl reload nginx
|
||||
#
|
||||
# For Let's Encrypt SSL:
|
||||
# sudo certbot --nginx -d apk-builder.yourdomain.com
|
||||
#
|
||||
|
||||
# Rate limiting zone (optional - uncomment to enable)
|
||||
# limit_req_zone $binary_remote_addr zone=apk_build_limit:10m rate=5r/m;
|
||||
|
||||
upstream apk_builder {
|
||||
server 127.0.0.1:3000;
|
||||
keepalive 32;
|
||||
}
|
||||
|
||||
# Redirect HTTP to HTTPS
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name apk-builder.yourdomain.com;
|
||||
|
||||
# Let's Encrypt challenge
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://$server_name$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
# HTTPS server
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name apk-builder.yourdomain.com;
|
||||
|
||||
# SSL Configuration
|
||||
# Option 1: Let's Encrypt (recommended)
|
||||
ssl_certificate /etc/letsencrypt/live/apk-builder.yourdomain.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/apk-builder.yourdomain.com/privkey.pem;
|
||||
|
||||
# Option 2: Self-signed (for testing only)
|
||||
# ssl_certificate /etc/nginx/ssl/apk-builder.crt;
|
||||
# ssl_certificate_key /etc/nginx/ssl/apk-builder.key;
|
||||
|
||||
# SSL Security Settings
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
|
||||
ssl_prefer_server_ciphers off;
|
||||
ssl_session_timeout 1d;
|
||||
ssl_session_cache shared:SSL:50m;
|
||||
ssl_session_tickets off;
|
||||
|
||||
# OCSP Stapling
|
||||
ssl_stapling on;
|
||||
ssl_stapling_verify on;
|
||||
resolver 8.8.8.8 8.8.4.4 valid=300s;
|
||||
resolver_timeout 5s;
|
||||
|
||||
# Security Headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
|
||||
# Allow large file uploads (for project ZIPs)
|
||||
client_max_body_size 100M;
|
||||
client_body_timeout 300s;
|
||||
client_body_buffer_size 128k;
|
||||
|
||||
# Logging
|
||||
access_log /var/log/nginx/apk-builder.access.log;
|
||||
error_log /var/log/nginx/apk-builder.error.log;
|
||||
|
||||
# Health check endpoint (no auth, fast response)
|
||||
location = /health {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 10s;
|
||||
}
|
||||
|
||||
# Build submission endpoint (longer timeouts)
|
||||
location = /api/build {
|
||||
# Optional rate limiting - uncomment to enable
|
||||
# limit_req zone=apk_build_limit burst=2 nodelay;
|
||||
# limit_req_status 429;
|
||||
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
# Long timeout for upload processing
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
# Status polling endpoint
|
||||
location ~ ^/api/build/[a-f0-9-]+/status$ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
|
||||
# APK download endpoint (large response, long timeout)
|
||||
location ~ ^/api/build/[a-f0-9-]+/download$ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
# Long timeout for large APK downloads
|
||||
proxy_connect_timeout 30s;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_send_timeout 600s;
|
||||
|
||||
# Buffering for large files
|
||||
proxy_buffering on;
|
||||
proxy_buffer_size 128k;
|
||||
proxy_buffers 4 256k;
|
||||
proxy_busy_buffers_size 256k;
|
||||
}
|
||||
|
||||
# All other API endpoints
|
||||
location /api/ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 30s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
# Block all other paths
|
||||
location / {
|
||||
return 404 '{"error": "Not found"}';
|
||||
add_header Content-Type application/json;
|
||||
}
|
||||
}
|
||||
+7
-6
@@ -24,8 +24,13 @@ export default {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
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 (url.hostname === 'github.com') {
|
||||
if (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' },
|
||||
@@ -33,20 +38,16 @@ 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 === 'api.z.ai') {
|
||||
} else if (url.host === '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`);
|
||||
},
|
||||
|
||||
+9
-8
@@ -12,16 +12,17 @@ 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.set('user-agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
headers.delete('origin');
|
||||
|
||||
const targetResponse = await fetch(target, {
|
||||
method: request.method,
|
||||
@@ -31,9 +32,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;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import { NWCProvider } from '@/contexts/NWCContext';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -142,6 +143,7 @@ export function App() {
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<NWCProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
@@ -161,6 +163,7 @@ export function App() {
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
|
||||
@@ -5,12 +5,14 @@ import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
import Explore from "./pages/Explore";
|
||||
import Settings from "./pages/Settings";
|
||||
import Preferences from "./pages/Preferences";
|
||||
import NostrSettings from "./pages/NostrSettings";
|
||||
import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DeploySettings from "./pages/DeploySettings";
|
||||
import WalletSettings from "./pages/WalletSettings";
|
||||
import SystemSettings from "./pages/SystemSettings";
|
||||
import StorageSettings from "./pages/StorageSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
@@ -18,6 +20,7 @@ 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";
|
||||
@@ -36,9 +39,11 @@ export function AppRouter() {
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/giftcard" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/explore" element={<Explore />} />
|
||||
<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 />} />
|
||||
@@ -46,6 +51,7 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="deploy" element={<DeploySettings />} />
|
||||
<Route path="wallet" element={<WalletSettings />} />
|
||||
<Route path="system" element={<SystemSettings />} />
|
||||
<Route path="storage" element={<StorageSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot } from 'lucide-react';
|
||||
import { Bot, ChevronDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
@@ -12,15 +12,31 @@ 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;
|
||||
}
|
||||
|
||||
@@ -29,6 +45,9 @@ export function AddAIProviderDialog({
|
||||
onOpenChange,
|
||||
preset,
|
||||
isLoggedIntoNostr,
|
||||
oauthHook,
|
||||
forceManualEntry = false,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddAIProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
@@ -36,16 +55,27 @@ 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={onOpenChange}>
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -73,6 +103,50 @@ 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 && (
|
||||
@@ -123,7 +197,7 @@ export function AddAIProviderDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!showNostrLoginRequired && (
|
||||
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
|
||||
+25
-123
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ChevronDown, Key, Loader2 } from 'lucide-react';
|
||||
import { Rocket, ChevronDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import {
|
||||
@@ -19,9 +19,6 @@ 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 {
|
||||
@@ -31,7 +28,7 @@ interface OAuthHook {
|
||||
initiateOAuth: () => void;
|
||||
}
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
interface AddDeployProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
preset: PresetDeployProvider;
|
||||
@@ -39,10 +36,10 @@ interface AddProviderDialogProps {
|
||||
oauthHook: OAuthHook | null;
|
||||
forceManualEntry: boolean;
|
||||
onSetForceManualEntry: (force: boolean) => void;
|
||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => void;
|
||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
|
||||
}
|
||||
|
||||
export function AddProviderDialog({
|
||||
export function AddDeployProviderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
preset,
|
||||
@@ -51,16 +48,11 @@ export function AddProviderDialog({
|
||||
forceManualEntry,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddProviderDialogProps) {
|
||||
}: AddDeployProviderDialogProps) {
|
||||
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;
|
||||
@@ -68,38 +60,13 @@ export function AddProviderDialog({
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
const handleAdd = () => {
|
||||
onAdd(apiKey, accountId, organizationId, buildServerUrl);
|
||||
onAdd(apiKey, accountId, organizationId);
|
||||
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">
|
||||
@@ -145,16 +112,9 @@ export function AddProviderDialog({
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ExternalFavicon
|
||||
url={preset.baseURL}
|
||||
size={16}
|
||||
fallback={<Rocket size={16} />}
|
||||
/>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
</>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
@@ -215,78 +175,21 @@ export function AddProviderDialog({
|
||||
urlTitle="Find ID"
|
||||
/>
|
||||
)}
|
||||
{preset.type === 'apkbuilder' && (
|
||||
<>
|
||||
<ExternalInput
|
||||
type="text"
|
||||
placeholder={preset.buildServerUrlLabel || 'Build Server URL'}
|
||||
value={buildServerUrl}
|
||||
onChange={(e) => {
|
||||
setBuildServerUrl(e.target.value);
|
||||
setApiKeyError(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.apiKeyLabel || 'API Key'}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleGetApiKey}
|
||||
disabled={!buildServerUrl.trim() || !user?.signer || isGettingApiKey}
|
||||
className="shrink-0"
|
||||
title={!user?.signer ? 'Login to Nostr first' : 'Get API key using Nostr authentication'}
|
||||
>
|
||||
{isGettingApiKey ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Key className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{apiKeyError && (
|
||||
<p className="text-xs text-destructive">{apiKeyError}</p>
|
||||
)}
|
||||
{!user?.signer && buildServerUrl.trim() && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<Link to="/settings/nostr" className="underline">Login to Nostr</Link> to get an API key automatically
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{preset.type !== 'apkbuilder' && (
|
||||
<ExternalInput
|
||||
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"
|
||||
/>
|
||||
)}
|
||||
<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>
|
||||
@@ -304,8 +207,7 @@ export function AddProviderDialog({
|
||||
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
||||
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
|
||||
(preset.type === 'cloudflare' && !accountId.trim()) ||
|
||||
(preset.type === 'deno' && !organizationId.trim()) ||
|
||||
(preset.type === 'apkbuilder' && !buildServerUrl.trim())
|
||||
(preset.type === 'deno' && !organizationId.trim())
|
||||
}
|
||||
>
|
||||
{t('add')}
|
||||
@@ -84,8 +84,8 @@ export function AddGitCredentialDialog({
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{preset.id === 'github' && isOAuthConfigured && !forceManualEntry ? (
|
||||
// Special rendering for GitHub OAuth
|
||||
{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
|
||||
@@ -100,16 +100,9 @@ export function AddGitCredentialDialog({
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ExternalFavicon
|
||||
url="https://github.com"
|
||||
size={16}
|
||||
fallback={<GitBranch size={16} />}
|
||||
/>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to GitHub
|
||||
</span>
|
||||
</>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
@@ -124,7 +117,7 @@ export function AddGitCredentialDialog({
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
||||
Enter API key
|
||||
Enter token manually
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
@@ -136,7 +129,7 @@ export function AddGitCredentialDialog({
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Standard token input
|
||||
// Show manual token input
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={t('enterToken')}
|
||||
@@ -153,7 +146,7 @@ export function AddGitCredentialDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!(preset.id === 'github' && isOAuthConfigured && !forceManualEntry) && (
|
||||
{!(isOAuthConfigured && !forceManualEntry) && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
|
||||
@@ -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, ExternalLink, Search, Coins } from 'lucide-react';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, 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 { PasswordInput } from '@/components/ui/password-input';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
@@ -465,37 +465,28 @@ 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">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold">
|
||||
<h3 className="flex justify-center text-lg font-semibold gap-2">
|
||||
<ExternalFavicon
|
||||
url={selectedProvider.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
/>
|
||||
<span>
|
||||
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
</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
|
||||
</span>
|
||||
</h3>
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
value={providerApiKey}
|
||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && providerApiKey.trim()) {
|
||||
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
|
||||
handleContinueFromProviderSelection();
|
||||
}
|
||||
}}
|
||||
url={selectedProvider.apiKeysURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders, Compass } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -367,6 +367,13 @@ export function ProjectSidebar({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigateAndClose('/explore')}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<Compass className="h-4 w-4" />
|
||||
{t('exploreApps')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setLabelsDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
|
||||
@@ -125,44 +125,6 @@ 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,14 +1,21 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useRef, useEffect, memo } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { GitBranch, Loader2, EllipsisVertical, Edit } from 'lucide-react';
|
||||
import { GitBranch, Loader2, EllipsisVertical, Edit, Code, ExternalLink } from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
|
||||
@@ -23,13 +30,26 @@ import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { detectFork } from '@/lib/detectFork';
|
||||
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useOGImage } from '@/hooks/useOGImage';
|
||||
import { ZapDialog } from '@/components/ZapDialog';
|
||||
import { Zap } from 'lucide-react';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
interface RepositoryCardProps {
|
||||
repo: Repository;
|
||||
/** Pre-fetched author metadata to avoid individual fetches */
|
||||
authorMetadata?: NostrMetadata;
|
||||
/** Callback when a tag is clicked - receives the tag value */
|
||||
onTagClick?: (tag: string) => void;
|
||||
}
|
||||
|
||||
export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
const { data: authorData } = useAuthor(repo.pubkey);
|
||||
function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagClick }: RepositoryCardProps) {
|
||||
// Only fetch author data if not preloaded
|
||||
const { data: authorData } = useAuthor(preloadedMetadata ? undefined : repo.pubkey);
|
||||
const metadata = preloadedMetadata ?? authorData?.metadata;
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { settings: gitSettings } = useGitSettings();
|
||||
const navigate = useNavigate();
|
||||
@@ -39,10 +59,41 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [isCloning, setIsCloning] = useState(false);
|
||||
const [editRepoOpen, setEditRepoOpen] = useState(false);
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const [eventViewerOpen, setEventViewerOpen] = useState(false);
|
||||
const [isInViewport, setIsInViewport] = useState(false);
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = authorData?.metadata?.picture;
|
||||
// Lazy load OG images - only fetch when card is in viewport
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setIsInViewport(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: '100px' } // Start loading slightly before visible
|
||||
);
|
||||
|
||||
if (cardRef.current) {
|
||||
observer.observe(cardRef.current);
|
||||
}
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const displayName = metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
const isOwnRepo = user?.pubkey === repo.pubkey;
|
||||
const hasLightning = !!(metadata?.lud16 || metadata?.lud06);
|
||||
const canZap = user && !isOwnRepo && hasLightning;
|
||||
|
||||
// Get OG metadata from first web URL - only when in viewport
|
||||
const firstWebUrl = repo.webUrls?.[0];
|
||||
const { data: ogMetadata } = useOGImage(isInViewport ? firstWebUrl : undefined);
|
||||
const ogImageUrl = ogMetadata?.image ?? null;
|
||||
const ogDescription = ogMetadata?.description ?? null;
|
||||
|
||||
// Construct Nostr clone URL
|
||||
const nostrURI = new NostrURI({
|
||||
@@ -109,52 +160,117 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'user-repositories', user?.pubkey] });
|
||||
};
|
||||
|
||||
// Check if we have a valid OG image to show
|
||||
const hasValidImage = ogImageUrl && !imageError;
|
||||
|
||||
return (
|
||||
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow">
|
||||
<Card ref={cardRef} className="h-full flex flex-col hover:shadow-lg transition-shadow">
|
||||
{/* Preview Image or Placeholder */}
|
||||
{hasValidImage && firstWebUrl ? (
|
||||
<a
|
||||
href={firstWebUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block aspect-video bg-muted overflow-hidden rounded-t-lg cursor-pointer hover:opacity-90 transition-opacity"
|
||||
>
|
||||
<img
|
||||
src={ogImageUrl}
|
||||
alt={`${repo.name} preview`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={() => setImageError(true)}
|
||||
/>
|
||||
</a>
|
||||
) : (
|
||||
<div className="aspect-video bg-gradient-to-br from-primary to-accent rounded-t-lg flex items-center justify-center">
|
||||
<Code className="h-12 w-12 text-white" />
|
||||
</div>
|
||||
)}
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
{/* Header with name and menu */}
|
||||
<div className="mb-4 flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<div className="flex items-end gap-2 mb-2">
|
||||
<h3 className="font-semibold text-lg leading-tight truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<span className="text-sm text-muted-foreground shrink-0">
|
||||
{formatRelativeTime(repo.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{isOwnRepo && (
|
||||
<div className="flex items-center -mt-1 -mr-2 shrink-0">
|
||||
{canZap && (
|
||||
<ZapDialog target={repo as unknown as Event}>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 text-amber-500 hover:text-amber-600 hover:bg-amber-500/10">
|
||||
<Zap className="h-4 w-4" />
|
||||
</Button>
|
||||
</ZapDialog>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 -mt-1 -mr-2 shrink-0">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<EllipsisVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Repository
|
||||
<DropdownMenuContent align="end">
|
||||
{firstWebUrl && (
|
||||
<DropdownMenuItem asChild className="gap-2">
|
||||
<a href={firstWebUrl} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
Open Website
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => setEventViewerOpen(true)} className="gap-2">
|
||||
<Code className="h-4 w-4" />
|
||||
View Event
|
||||
</DropdownMenuItem>
|
||||
{isOwnRepo && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Repository
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Author */}
|
||||
<div className="mb-4">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Avatar className="h-4 w-4">
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
<Avatar className="h-10 w-10">
|
||||
{profileImage && (
|
||||
<AvatarImage src={profileImage} alt={displayName} />
|
||||
)}
|
||||
<AvatarFallback className="text-[8px]">
|
||||
<AvatarFallback className="text-xs">
|
||||
{displayName.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate">{displayName}</span>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onTagClick?.(displayName);
|
||||
}}
|
||||
className="truncate font-medium text-base text-foreground hover:text-primary hover:underline transition-colors text-left"
|
||||
>
|
||||
{displayName}
|
||||
</button>
|
||||
{metadata?.nip05 && (
|
||||
<span className="text-sm text-muted-foreground shrink-0">{metadata.nip05}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
{repo.description && (
|
||||
{(repo.description || ogDescription) && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
|
||||
{repo.description}
|
||||
{repo.description || ogDescription}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -162,14 +278,21 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
{repo.repoTags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mb-4">
|
||||
{repo.repoTags.slice(0, 3).map((tag, index) => (
|
||||
<Badge key={index} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
<button
|
||||
key={index}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onTagClick?.(tag);
|
||||
}}
|
||||
className="text-sm text-primary hover:text-primary/80 hover:underline transition-colors font-medium"
|
||||
>
|
||||
#{tag}
|
||||
</button>
|
||||
))}
|
||||
{repo.repoTags.length > 3 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
+{repo.repoTags.length - 3}
|
||||
</Badge>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -212,6 +335,31 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
repoIdentifier={repo.repoId}
|
||||
onSuccess={handleRepoEditSuccess}
|
||||
/>
|
||||
|
||||
{/* Event Viewer Dialog */}
|
||||
<Dialog open={eventViewerOpen} onOpenChange={setEventViewerOpen}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Repository Event</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="overflow-y-auto flex-1 min-h-0">
|
||||
<pre className="text-xs p-4 rounded-lg overflow-x-auto">
|
||||
{JSON.stringify({
|
||||
id: repo.id,
|
||||
pubkey: repo.pubkey,
|
||||
created_at: repo.created_at,
|
||||
kind: repo.kind,
|
||||
tags: repo.tags,
|
||||
content: repo.content,
|
||||
sig: repo.sig,
|
||||
}, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Memoize to prevent re-renders when parent re-renders with same props
|
||||
export const RepositoryCard = memo(RepositoryCardInner);
|
||||
@@ -251,7 +251,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setComment('Zapped with MKStack!');
|
||||
setComment('Zapped from Shakespeare!');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
|
||||
@@ -1,262 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { CheckCircle, XCircle, Loader2, Shield, Bug } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { APKBuildType } from '@/lib/deploy/types';
|
||||
|
||||
interface APKBuilderDeployFormProps {
|
||||
buildServerUrl: string;
|
||||
apiKey: string;
|
||||
projectId: string;
|
||||
projectName?: string;
|
||||
savedAppName?: string;
|
||||
savedPackageId?: string;
|
||||
savedBuildType?: APKBuildType;
|
||||
onConfigChange: (appName: string, packageId: string, buildType: APKBuildType) => void;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
interface ServerHealth {
|
||||
status: 'ok' | 'error';
|
||||
version?: string;
|
||||
queue?: {
|
||||
running: number;
|
||||
queued: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function APKBuilderDeployForm({
|
||||
buildServerUrl,
|
||||
apiKey,
|
||||
projectId,
|
||||
projectName,
|
||||
savedAppName,
|
||||
savedPackageId,
|
||||
savedBuildType,
|
||||
onConfigChange,
|
||||
corsProxy,
|
||||
}: APKBuilderDeployFormProps) {
|
||||
const [appName, setAppName] = useState(savedAppName || projectName || projectId);
|
||||
const [packageId, setPackageId] = useState(savedPackageId || '');
|
||||
const [buildType, setBuildType] = useState<APKBuildType>(savedBuildType || 'debug');
|
||||
const [packageIdError, setPackageIdError] = useState<string | null>(null);
|
||||
const [serverHealth, setServerHealth] = useState<ServerHealth | null>(null);
|
||||
const [isCheckingServer, setIsCheckingServer] = useState(true);
|
||||
|
||||
// Generate default package ID from project name
|
||||
useEffect(() => {
|
||||
if (!savedPackageId && !packageId) {
|
||||
const safeName = (projectName || projectId)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]/g, '');
|
||||
setPackageId(`com.app.${safeName}`);
|
||||
}
|
||||
}, [projectName, projectId, savedPackageId, packageId]);
|
||||
|
||||
// Check server health
|
||||
const checkServerHealth = useCallback(async () => {
|
||||
setIsCheckingServer(true);
|
||||
try {
|
||||
const url = `${buildServerUrl}/health`;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: {
|
||||
'X-API-Key': apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setServerHealth({ status: 'ok', ...data });
|
||||
} else {
|
||||
setServerHealth({ status: 'error' });
|
||||
}
|
||||
} catch {
|
||||
setServerHealth({ status: 'error' });
|
||||
} finally {
|
||||
setIsCheckingServer(false);
|
||||
}
|
||||
}, [buildServerUrl, apiKey, corsProxy]);
|
||||
|
||||
useEffect(() => {
|
||||
checkServerHealth();
|
||||
}, [checkServerHealth]);
|
||||
|
||||
// Validate package ID
|
||||
const validatePackageId = (value: string): boolean => {
|
||||
// Android package ID rules:
|
||||
// - Must have at least two segments (e.g., com.example)
|
||||
// - Each segment must start with a letter
|
||||
// - Can only contain letters, numbers, and underscores
|
||||
const pattern = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/i;
|
||||
return pattern.test(value);
|
||||
};
|
||||
|
||||
// Handle package ID change with validation
|
||||
const handlePackageIdChange = (value: string) => {
|
||||
setPackageId(value);
|
||||
if (value && !validatePackageId(value)) {
|
||||
setPackageIdError('Package ID must be like "com.example.myapp" (letters, numbers, underscores)');
|
||||
} else {
|
||||
setPackageIdError(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Notify parent of config changes
|
||||
useEffect(() => {
|
||||
if (appName && packageId && !packageIdError) {
|
||||
onConfigChange(appName, packageId, buildType);
|
||||
}
|
||||
}, [appName, packageId, packageIdError, buildType, onConfigChange]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Server Status */}
|
||||
<div className="rounded-lg border p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{isCheckingServer ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : serverHealth?.status === 'ok' ? (
|
||||
<CheckCircle className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<XCircle className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium">
|
||||
{isCheckingServer
|
||||
? 'Checking build server...'
|
||||
: serverHealth?.status === 'ok'
|
||||
? 'Build server connected'
|
||||
: 'Build server unavailable'}
|
||||
</p>
|
||||
{serverHealth?.status === 'ok' && serverHealth.queue && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{serverHealth.queue.running > 0
|
||||
? `${serverHealth.queue.running} build(s) in progress`
|
||||
: 'Ready to build'}
|
||||
{serverHealth.queue.queued > 0 && `, ${serverHealth.queue.queued} queued`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{serverHealth?.status === 'error' && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
Cannot connect to build server. Check your server URL and API key in Deploy Settings.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* App Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="app-name">App Name</Label>
|
||||
<Input
|
||||
id="app-name"
|
||||
value={appName}
|
||||
onChange={(e) => setAppName(e.target.value)}
|
||||
placeholder="My App"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This name appears on the Android home screen
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Package ID */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="package-id">Package ID</Label>
|
||||
<Input
|
||||
id="package-id"
|
||||
value={packageId}
|
||||
onChange={(e) => handlePackageIdChange(e.target.value)}
|
||||
placeholder="com.example.myapp"
|
||||
className={packageIdError ? 'border-red-500' : ''}
|
||||
/>
|
||||
{packageIdError ? (
|
||||
<p className="text-xs text-red-500">{packageIdError}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Unique identifier for your app (e.g., com.yourcompany.appname)
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Build Type Toggle */}
|
||||
<div className="space-y-2">
|
||||
<Label>Build Type</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBuildType('debug')}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
|
||||
"border-2 hover:scale-105 active:scale-95",
|
||||
buildType === 'debug'
|
||||
? "bg-primary text-primary-foreground border-primary shadow-sm"
|
||||
: "bg-background text-foreground border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Bug className="h-3.5 w-3.5" />
|
||||
<span>Debug</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBuildType('release')}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
|
||||
"border-2 hover:scale-105 active:scale-95",
|
||||
buildType === 'release'
|
||||
? "bg-primary text-primary-foreground border-primary shadow-sm"
|
||||
: "bg-background text-foreground border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Shield className="h-3.5 w-3.5" />
|
||||
<span>Release</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Build Info */}
|
||||
<div className="rounded-lg bg-muted/50 p-3 space-y-1">
|
||||
{buildType === 'debug' ? (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Build type:</strong> Debug APK (for testing/sideloading)
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Uses debug signing key. Install via USB or file transfer.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Build type:</strong> Release APK (unsigned)
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Server builds unsigned APK. Signing will be done in your browser.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Output:</strong> Downloadable .apk file
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Release Signing Info */}
|
||||
{buildType === 'release' && (
|
||||
<Alert>
|
||||
<Shield className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">
|
||||
Release builds require signing. You'll be prompted to configure your signing key after the build completes.
|
||||
Your signing key never leaves your browser.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,595 +0,0 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { Key, Upload, Plus, Download, Loader2, CheckCircle, AlertCircle, FileKey, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
signApk,
|
||||
generateSigningKey,
|
||||
importKeyFromPkcs12,
|
||||
exportKeyToPkcs12,
|
||||
hasSavedKey,
|
||||
getSavedKeyInfo,
|
||||
loadSavedKey,
|
||||
saveKey,
|
||||
deleteSavedKey,
|
||||
type SigningKey,
|
||||
type StoredKeyInfo,
|
||||
} from '@/lib/apk';
|
||||
|
||||
interface APKSignerProps {
|
||||
unsignedApkUrl: string;
|
||||
appName: string;
|
||||
onComplete: (signedApkBlob: Blob) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
type KeySource = 'saved' | 'upload' | 'generate' | null;
|
||||
type SigningStatus = 'idle' | 'loading-apk' | 'signing' | 'complete' | 'error';
|
||||
|
||||
export function APKSigner({ unsignedApkUrl, appName, onComplete, onCancel }: APKSignerProps) {
|
||||
const [keySource, setKeySource] = useState<KeySource>(null);
|
||||
const [signingKey, setSigningKey] = useState<SigningKey | null>(null);
|
||||
const [status, setStatus] = useState<SigningStatus>('idle');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [progress, setProgress] = useState<string>('');
|
||||
|
||||
// Saved key state
|
||||
const [savedKeyInfo, setSavedKeyInfo] = useState<StoredKeyInfo | null>(null);
|
||||
const [savedKeyPassword, setSavedKeyPassword] = useState('');
|
||||
const [saveKeyAfter, setSaveKeyAfter] = useState(true);
|
||||
|
||||
// Upload form state
|
||||
const [uploadPassword, setUploadPassword] = useState('');
|
||||
const [uploadFile, setUploadFile] = useState<File | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Generate form state
|
||||
const [generateName, setGenerateName] = useState(appName || 'My App');
|
||||
const [generateOrg, setGenerateOrg] = useState('');
|
||||
const [generatePassword, setGeneratePassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
|
||||
// Check for saved key on mount
|
||||
useEffect(() => {
|
||||
if (hasSavedKey()) {
|
||||
const info = getSavedKeyInfo();
|
||||
setSavedKeyInfo(info);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setUploadFile(file);
|
||||
setError(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleLoadSavedKey = useCallback(() => {
|
||||
if (!savedKeyPassword) {
|
||||
setError('Please enter the password');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const key = loadSavedKey(savedKeyPassword);
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load saved key');
|
||||
}
|
||||
}, [savedKeyPassword]);
|
||||
|
||||
const handleDeleteSavedKey = useCallback(() => {
|
||||
deleteSavedKey();
|
||||
setSavedKeyInfo(null);
|
||||
setKeySource(null);
|
||||
}, []);
|
||||
|
||||
const handleImportKeystore = useCallback(async () => {
|
||||
if (!uploadFile || !uploadPassword) {
|
||||
setError('Please select a file and enter the password');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setStatus('loading-apk');
|
||||
setProgress('Reading keystore...');
|
||||
|
||||
const arrayBuffer = await uploadFile.arrayBuffer();
|
||||
const key = importKeyFromPkcs12(arrayBuffer, uploadPassword);
|
||||
|
||||
// Save key if requested
|
||||
if (saveKeyAfter) {
|
||||
saveKey(key, uploadPassword);
|
||||
setSavedKeyInfo(getSavedKeyInfo());
|
||||
}
|
||||
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
setStatus('idle');
|
||||
setProgress('');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import keystore');
|
||||
setStatus('error');
|
||||
}
|
||||
}, [uploadFile, uploadPassword, saveKeyAfter]);
|
||||
|
||||
const handleGenerateKeystore = useCallback(() => {
|
||||
if (!generateName.trim()) {
|
||||
setError('Please enter an app/key name');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!generatePassword) {
|
||||
setError('Please enter a password');
|
||||
return;
|
||||
}
|
||||
|
||||
if (generatePassword !== confirmPassword) {
|
||||
setError('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
if (generatePassword.length < 6) {
|
||||
setError('Password must be at least 6 characters');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setProgress('Generating key pair...');
|
||||
const key = generateSigningKey({
|
||||
commonName: generateName.trim(),
|
||||
organizationName: generateOrg.trim() || undefined,
|
||||
});
|
||||
|
||||
// Save key if requested
|
||||
if (saveKeyAfter) {
|
||||
saveKey(key, generatePassword);
|
||||
setSavedKeyInfo(getSavedKeyInfo());
|
||||
}
|
||||
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
setProgress('');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to generate keystore');
|
||||
}
|
||||
}, [generateName, generateOrg, generatePassword, confirmPassword, saveKeyAfter]);
|
||||
|
||||
const handleDownloadKeystore = useCallback(() => {
|
||||
if (!signingKey) return;
|
||||
|
||||
const password = keySource === 'generate' ? generatePassword : uploadPassword;
|
||||
const p12Data = exportKeyToPkcs12(signingKey, password);
|
||||
const blob = new Blob([p12Data], { type: 'application/x-pkcs12' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${appName.replace(/[^a-zA-Z0-9]/g, '_')}_release_key.p12`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}, [signingKey, keySource, generatePassword, uploadPassword, appName]);
|
||||
|
||||
const handleSign = useCallback(async () => {
|
||||
if (!signingKey) {
|
||||
setError('No signing key configured');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setStatus('loading-apk');
|
||||
setProgress('Downloading unsigned APK...');
|
||||
setError(null);
|
||||
|
||||
// Fetch the unsigned APK
|
||||
const response = await fetch(unsignedApkUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download APK: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const apkData = await response.arrayBuffer();
|
||||
const sizeMB = (apkData.byteLength / 1024 / 1024).toFixed(2);
|
||||
setProgress(`Downloaded ${sizeMB} MB. Signing APK...`);
|
||||
setStatus('signing');
|
||||
|
||||
// Sign the APK
|
||||
const signedApk = await signApk({
|
||||
key: signingKey,
|
||||
apkData,
|
||||
});
|
||||
|
||||
setStatus('complete');
|
||||
setProgress('');
|
||||
onComplete(signedApk);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to sign APK');
|
||||
setStatus('error');
|
||||
}
|
||||
}, [signingKey, unsignedApkUrl, onComplete]);
|
||||
|
||||
const renderKeySourceSelection = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Configure Signing Key</span>
|
||||
</div>
|
||||
|
||||
{/* Saved key option */}
|
||||
{savedKeyInfo && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('saved')}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left",
|
||||
keySource === 'saved'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10">
|
||||
<Key className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{savedKeyInfo.commonName}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Saved key • Expires {new Date(savedKeyInfo.expiresAt).getFullYear()}
|
||||
</p>
|
||||
</div>
|
||||
<CheckCircle className="h-5 w-5 text-primary flex-shrink-0" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('upload')}
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all",
|
||||
keySource === 'upload'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Upload className="h-6 w-6 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Upload Keystore</span>
|
||||
<span className="text-xs text-muted-foreground text-center">
|
||||
Use existing .p12 or .pfx file
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('generate')}
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all",
|
||||
keySource === 'generate'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Plus className="h-6 w-6 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Generate New</span>
|
||||
<span className="text-xs text-muted-foreground text-center">
|
||||
Create a new signing key
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderSavedKeyForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Use Saved Key</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{savedKeyInfo && (
|
||||
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10">
|
||||
<Key className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{savedKeyInfo.commonName}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Expires {new Date(savedKeyInfo.expiresAt).getFullYear()}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleDeleteSavedKey}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="saved-key-password">Password</Label>
|
||||
<Input
|
||||
id="saved-key-password"
|
||||
type="password"
|
||||
value={savedKeyPassword}
|
||||
onChange={(e) => setSavedKeyPassword(e.target.value)}
|
||||
placeholder="Enter password to unlock key"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleLoadSavedKey}
|
||||
disabled={!savedKeyPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Unlock Key
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderUploadForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Upload className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Upload Keystore</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label>Keystore File (.p12 / .pfx)</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
value={uploadFile?.name || ''}
|
||||
placeholder="Select a keystore file..."
|
||||
readOnly
|
||||
className="flex-1"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".p12,.pfx,.jks,.keystore"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
PKCS#12 format (.p12 / .pfx). For JKS files, convert first using keytool.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="keystore-password">Keystore Password</Label>
|
||||
<Input
|
||||
id="keystore-password"
|
||||
type="password"
|
||||
value={uploadPassword}
|
||||
onChange={(e) => setUploadPassword(e.target.value)}
|
||||
placeholder="Enter keystore password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="save-upload-key"
|
||||
checked={saveKeyAfter}
|
||||
onCheckedChange={(checked) => setSaveKeyAfter(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="save-upload-key" className="text-sm font-normal cursor-pointer">
|
||||
Remember this key for future builds
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleImportKeystore}
|
||||
disabled={!uploadFile || !uploadPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Import Keystore
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderGenerateForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Generate New Key</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-name">Name (Common Name)</Label>
|
||||
<Input
|
||||
id="key-name"
|
||||
value={generateName}
|
||||
onChange={(e) => setGenerateName(e.target.value)}
|
||||
placeholder="My App"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-org">Organization (optional)</Label>
|
||||
<Input
|
||||
id="key-org"
|
||||
value={generateOrg}
|
||||
onChange={(e) => setGenerateOrg(e.target.value)}
|
||||
placeholder="My Company"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-password">Password</Label>
|
||||
<Input
|
||||
id="key-password"
|
||||
type="password"
|
||||
value={generatePassword}
|
||||
onChange={(e) => setGeneratePassword(e.target.value)}
|
||||
placeholder="Enter password (min 6 characters)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-confirm">Confirm Password</Label>
|
||||
<Input
|
||||
id="key-confirm"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="Confirm password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="save-generated-key"
|
||||
checked={saveKeyAfter}
|
||||
onCheckedChange={(checked) => setSaveKeyAfter(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="save-generated-key" className="text-sm font-normal cursor-pointer">
|
||||
Remember this key for future builds
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleGenerateKeystore}
|
||||
disabled={!generateName || !generatePassword || !confirmPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Generate Key
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderKeyReady = () => (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Signing key ready: <strong>{signingKey?.alias}</strong>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{keySource === 'generate' && (
|
||||
<Alert>
|
||||
<FileKey className="h-4 w-4" />
|
||||
<AlertDescription className="space-y-2">
|
||||
<p><strong>Important:</strong> Save your keystore file! You'll need it for future updates.</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownloadKeystore}
|
||||
className="mt-2"
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Download Keystore (.p12)
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setSigningKey(null);
|
||||
setKeySource(null);
|
||||
}}
|
||||
className="flex-1"
|
||||
>
|
||||
Change Key
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSign}
|
||||
disabled={status === 'loading-apk' || status === 'signing'}
|
||||
className="flex-1"
|
||||
>
|
||||
{status === 'loading-apk' || status === 'signing' ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Signing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Sign APK
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{progress && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{progress}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border p-4">
|
||||
{signingKey ? (
|
||||
renderKeyReady()
|
||||
) : keySource === 'saved' ? (
|
||||
renderSavedKeyForm()
|
||||
) : keySource === 'upload' ? (
|
||||
renderUploadForm()
|
||||
) : keySource === 'generate' ? (
|
||||
renderGenerateForm()
|
||||
) : (
|
||||
renderKeySourceSelection()
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud, Shield, Download, CheckCircle } from 'lucide-react';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -13,9 +13,13 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { APKBuildType, PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
@@ -23,8 +27,6 @@ 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';
|
||||
@@ -33,7 +35,6 @@ 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
|
||||
@@ -104,12 +105,6 @@ 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();
|
||||
@@ -119,11 +114,12 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { git } = useGit();
|
||||
|
||||
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);
|
||||
|
||||
@@ -148,11 +144,6 @@ 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(() => {
|
||||
@@ -276,30 +267,6 @@ 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');
|
||||
}
|
||||
@@ -359,19 +326,68 @@ 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);
|
||||
|
||||
// Update repository announcement with deployment URL if using Nostr git
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const remoteUrl = await git.getRemoteURL(projectPath, 'origin');
|
||||
|
||||
if (remoteUrl && remoteUrl.startsWith('nostr://') && user) {
|
||||
const nostrURI = await NostrURI.parse(remoteUrl);
|
||||
|
||||
// Query for existing repository announcement
|
||||
const existingRepos = await nostr.query(
|
||||
[{ kinds: [30617], authors: [user.pubkey], '#d': [nostrURI.identifier], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(5000) }
|
||||
);
|
||||
|
||||
if (existingRepos.length > 0) {
|
||||
const existingEvent = existingRepos[0];
|
||||
|
||||
// Extract existing data from the event
|
||||
const description = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1];
|
||||
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
|
||||
const existingWebUrls = webTag ? webTag.slice(1) : [];
|
||||
const cloneTag = existingEvent.tags.find(([tagName]) => tagName === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1) : [];
|
||||
const relaysTag = existingEvent.tags.find(([tagName]) => tagName === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1) : [];
|
||||
const tTags = existingEvent.tags
|
||||
.filter(([tagName]) => tagName === 't')
|
||||
.map(([, value]) => value);
|
||||
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
|
||||
const earliestCommit = eucTag?.[1];
|
||||
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1];
|
||||
|
||||
// Add deployment URL if not already present
|
||||
const deploymentUrl = result.url;
|
||||
const updatedWebUrls = existingWebUrls.includes(deploymentUrl)
|
||||
? existingWebUrls
|
||||
: [...existingWebUrls, deploymentUrl];
|
||||
|
||||
// Create updated repository announcement event
|
||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||
repoId: nostrURI.identifier,
|
||||
name,
|
||||
description,
|
||||
webUrls: updatedWebUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
tTags: tTags.length > 0 ? tTags : undefined,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
// Publish the updated event
|
||||
await publishEvent(eventTemplate);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Silently fail - updating web tag is not critical for deployment
|
||||
console.warn('Failed to update repository announcement with deployment URL:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Deployment failed');
|
||||
} finally {
|
||||
@@ -382,7 +398,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const handleClose = () => {
|
||||
setSelectedProviderId('');
|
||||
setDeployResult(null);
|
||||
setSignedApkBlob(null);
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
@@ -391,27 +406,9 @@ 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 });
|
||||
}, []);
|
||||
@@ -440,10 +437,6 @@ 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;
|
||||
|
||||
@@ -549,28 +542,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'apkbuilder') {
|
||||
const apkBuilderProvider = selectedProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedAppName = savedConfig?.type === 'apkbuilder' ? savedConfig.data.appName : undefined;
|
||||
const savedPackageId = savedConfig?.type === 'apkbuilder' ? savedConfig.data.packageId : undefined;
|
||||
const savedBuildType = savedConfig?.type === 'apkbuilder' ? savedConfig.data.buildType : undefined;
|
||||
|
||||
return (
|
||||
<APKBuilderDeployForm
|
||||
buildServerUrl={apkBuilderProvider.buildServerUrl}
|
||||
apiKey={apkBuilderProvider.apiKey}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedAppName={savedAppName}
|
||||
savedPackageId={savedPackageId}
|
||||
savedBuildType={savedBuildType}
|
||||
onConfigChange={handleApkBuilderConfigChange}
|
||||
corsProxy={apkBuilderProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -585,124 +556,36 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
{deployResult ? (
|
||||
<div className="space-y-4">
|
||||
{/* Release APK signing flow */}
|
||||
{selectedProvider?.type === 'apkbuilder' && apkBuilderForm.buildType === 'release' ? (
|
||||
<>
|
||||
{/* Step indicator */}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-medium">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
</div>
|
||||
<span className="text-muted-foreground line-through">Build</span>
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
<div className={cn(
|
||||
"flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium",
|
||||
signedApkBlob
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-primary text-primary-foreground"
|
||||
)}>
|
||||
{signedApkBlob ? <CheckCircle className="h-3 w-3" /> : '2'}
|
||||
</div>
|
||||
<span className={signedApkBlob ? "text-muted-foreground line-through" : "font-medium"}>Sign</span>
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
<div className={cn(
|
||||
"flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium",
|
||||
signedApkBlob
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted text-muted-foreground"
|
||||
)}>
|
||||
3
|
||||
</div>
|
||||
<span className={signedApkBlob ? "font-medium" : "text-muted-foreground"}>Download</span>
|
||||
</div>
|
||||
<Alert>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Your project has been successfully deployed!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{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="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>
|
||||
|
||||
<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 className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
@@ -835,8 +718,7 @@ 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 === 'apkbuilder' && (!apkBuilderForm.appName || !apkBuilderForm.packageId))
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
|
||||
}
|
||||
className="w-full"
|
||||
>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { CloudUpload, Loader2, Check } from 'lucide-react';
|
||||
import { CloudUpload, Loader2, Check, AlertTriangle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
@@ -16,6 +16,8 @@ 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();
|
||||
@@ -26,6 +28,18 @@ 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(() => {
|
||||
@@ -38,6 +52,29 @@ 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
|
||||
@@ -78,26 +115,61 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
};
|
||||
|
||||
return (
|
||||
<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"
|
||||
<>
|
||||
{/* 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()}
|
||||
>
|
||||
<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 className="space-y-3 pointer-events-auto">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="size-5 text-primary shrink-0" />
|
||||
<h4 className="font-semibold text-sm">Your project files are not safe</h4>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your project files are stored in your browser session and could be deleted. Sync with git to back up your project.
|
||||
</p>
|
||||
<Button
|
||||
onClick={handleButtonClick}
|
||||
className="w-full"
|
||||
size="sm"
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -50,14 +50,7 @@ export interface DenoDeployProvider extends BaseDeployProvider {
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface APKBuilderProvider extends BaseDeployProvider {
|
||||
type: 'apkbuilder';
|
||||
buildServerUrl: string;
|
||||
apiKey: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | APKBuilderProvider;
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
|
||||
|
||||
export interface DeploySettings {
|
||||
providers: DeployProvider[];
|
||||
|
||||
@@ -13,7 +13,7 @@ export function useFollowedRepositories(followedPubkeys: string[] = []) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
|
||||
queryKey: ['nostr', 'followed-repositories', followedPubkeys],
|
||||
queryFn: async (): Promise<Repository[]> => {
|
||||
if (followedPubkeys.length === 0) {
|
||||
return [];
|
||||
@@ -50,10 +50,19 @@ export function useFollowedRepositories(followedPubkeys: string[] = []) {
|
||||
|
||||
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
|
||||
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
|
||||
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
|
||||
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
|
||||
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
|
||||
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
|
||||
|
||||
// Extract multi-value tags correctly (all values are in a single tag per NIP-34)
|
||||
const webTag = event.tags.find(tag => tag[0] === 'web');
|
||||
const webUrls = webTag ? webTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const cloneTag = event.tags.find(tag => tag[0] === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const relaysTag = event.tags.find(tag => tag[0] === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const maintainersTag = event.tags.find(tag => tag[0] === 'maintainers');
|
||||
const maintainers = maintainersTag ? maintainersTag.slice(1).filter(Boolean) : [];
|
||||
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
|
||||
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
|
||||
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
export interface OAuthConfig {
|
||||
provider: 'github' | 'netlify' | 'vercel';
|
||||
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
authorizeUrl: string;
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
export interface OGMetadata {
|
||||
image: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch Open Graph metadata from a web URL using CORS proxy
|
||||
* @param webUrl - The web URL to fetch OG metadata from
|
||||
* @returns Query result with OG image URL and description
|
||||
*/
|
||||
export function useOGImage(webUrl?: string) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['og-metadata', webUrl],
|
||||
queryFn: async (): Promise<OGMetadata> => {
|
||||
if (!webUrl) {
|
||||
return { image: null, description: null };
|
||||
}
|
||||
|
||||
try {
|
||||
// Use CORS proxy to fetch the HTML
|
||||
const proxiedUrl = proxyUrl(config.corsProxy, webUrl);
|
||||
const response = await fetch(proxiedUrl, {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return { image: null, description: null };
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
|
||||
// Extract OG image
|
||||
let ogImage: string | null = null;
|
||||
const ogImageMeta = doc.querySelector('meta[property="og:image"]')?.getAttribute('content');
|
||||
if (ogImageMeta) {
|
||||
try {
|
||||
ogImage = new URL(ogImageMeta, webUrl).href;
|
||||
} catch {
|
||||
ogImage = ogImageMeta.startsWith('http') ? ogImageMeta : null;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to twitter:image if og:image not found
|
||||
if (!ogImage) {
|
||||
const twitterImage = doc.querySelector('meta[name="twitter:image"]')?.getAttribute('content');
|
||||
if (twitterImage) {
|
||||
try {
|
||||
ogImage = new URL(twitterImage, webUrl).href;
|
||||
} catch {
|
||||
ogImage = twitterImage.startsWith('http') ? twitterImage : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract OG description
|
||||
let ogDescription: string | null = null;
|
||||
const ogDescriptionMeta = doc.querySelector('meta[property="og:description"]')?.getAttribute('content');
|
||||
if (ogDescriptionMeta) {
|
||||
ogDescription = ogDescriptionMeta.trim();
|
||||
}
|
||||
|
||||
// Fallback to twitter:description if og:description not found
|
||||
if (!ogDescription) {
|
||||
const twitterDescription = doc.querySelector('meta[name="twitter:description"]')?.getAttribute('content');
|
||||
if (twitterDescription) {
|
||||
ogDescription = twitterDescription.trim();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
image: ogImage,
|
||||
description: ogDescription || null,
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch OG metadata:', error);
|
||||
return { image: null, description: null };
|
||||
}
|
||||
},
|
||||
enabled: !!webUrl,
|
||||
staleTime: 1000 * 60 * 60, // 1 hour
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface OpenRouterTokenResponse {
|
||||
key: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for OpenRouter OAuth authentication with PKCE.
|
||||
* OpenRouter uses a custom OAuth flow that differs from standard OAuth 2.0.
|
||||
* It uses PKCE without requiring client credentials.
|
||||
*/
|
||||
export function useOpenRouterOAuth() {
|
||||
const { setProvider, isLoading: isSettingsLoading } = useAISettings();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// OpenRouter doesn't require client credentials - it uses PKCE only
|
||||
const isOAuthConfigured = true;
|
||||
|
||||
// Generate a cryptographically secure random string for PKCE code verifier
|
||||
const generateCodeVerifier = (): string => {
|
||||
const array = new Uint8Array(32);
|
||||
crypto.getRandomValues(array);
|
||||
return btoa(String.fromCharCode(...array))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
};
|
||||
|
||||
// Create SHA-256 hash of the code verifier for PKCE code challenge
|
||||
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(codeVerifier);
|
||||
const digest = await crypto.subtle.digest('SHA-256', data);
|
||||
return btoa(String.fromCharCode(...new Uint8Array(digest)))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Initiates the OAuth flow by redirecting to OpenRouter's authorization page.
|
||||
*/
|
||||
const initiateOAuth = useCallback(async () => {
|
||||
try {
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
const storagePrefix = 'openrouter_oauth';
|
||||
|
||||
// Store state for later verification
|
||||
localStorage.setItem(`${storagePrefix}_state`, state);
|
||||
|
||||
// Generate PKCE parameters
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||
|
||||
localStorage.setItem(`${storagePrefix}_code_verifier`, codeVerifier);
|
||||
|
||||
// Build authorization URL
|
||||
const redirectUri = window.location.origin + '/oauth/openrouter';
|
||||
const params = new URLSearchParams({
|
||||
callback_url: redirectUri,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
|
||||
// Redirect to OpenRouter's authorization page
|
||||
window.location.href = `https://openrouter.ai/auth?${params.toString()}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to initiate OpenRouter OAuth:', error);
|
||||
setError('Failed to generate PKCE parameters. Please try again.');
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Handles the OAuth callback after the user authorizes the application.
|
||||
* Exchanges the authorization code for an API key.
|
||||
*/
|
||||
const handleCallback = useCallback(async (
|
||||
code: string,
|
||||
_state: string
|
||||
): Promise<boolean> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const storagePrefix = 'openrouter_oauth';
|
||||
|
||||
try {
|
||||
// Get PKCE code verifier
|
||||
const codeVerifier = localStorage.getItem(`${storagePrefix}_code_verifier`);
|
||||
if (!codeVerifier) {
|
||||
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
|
||||
}
|
||||
|
||||
// Clean up stored values
|
||||
localStorage.removeItem(`${storagePrefix}_state`);
|
||||
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||
|
||||
// Exchange code for API key using OpenRouter's custom endpoint
|
||||
const tokenResponse = await fetch('https://openrouter.ai/api/v1/auth/keys', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
code: code,
|
||||
code_verifier: codeVerifier,
|
||||
code_challenge_method: 'S256',
|
||||
}),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
const errorText = await tokenResponse.text();
|
||||
throw new Error(`OpenRouter token exchange failed: ${tokenResponse.statusText} - ${errorText}`);
|
||||
}
|
||||
|
||||
const tokenData: OpenRouterTokenResponse = await tokenResponse.json();
|
||||
|
||||
if (!tokenData.key) {
|
||||
throw new Error('No API key received from OpenRouter');
|
||||
}
|
||||
|
||||
// Wait for settings to be initialized before storing
|
||||
if (isSettingsLoading) {
|
||||
throw new Error('Settings not initialized. Please try again.');
|
||||
}
|
||||
|
||||
// Create a new OpenRouter provider with the OAuth token
|
||||
const newProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: tokenData.key,
|
||||
};
|
||||
|
||||
// Add or update the OpenRouter provider in settings
|
||||
setProvider(newProvider);
|
||||
|
||||
setIsLoading(false);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('OpenRouter OAuth error:', error);
|
||||
|
||||
// Clean up any remaining OAuth data on error
|
||||
localStorage.removeItem(`${storagePrefix}_state`);
|
||||
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||
|
||||
setError(error instanceof Error ? error.message : 'OAuth authentication failed');
|
||||
setIsLoading(false);
|
||||
return false;
|
||||
}
|
||||
}, [setProvider, isSettingsLoading]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
isOAuthConfigured,
|
||||
initiateOAuth,
|
||||
handleCallback,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -52,16 +52,6 @@ const denoDeployProjectConfigSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
const apkBuilderProjectConfigSchema = z.object({
|
||||
type: z.literal('apkbuilder'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
appName: z.string(),
|
||||
packageId: z.string(),
|
||||
buildType: z.enum(['debug', 'release']).optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
shakespeareProjectConfigSchema,
|
||||
nsiteProjectConfigSchema,
|
||||
@@ -69,7 +59,6 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
vercelProjectConfigSchema,
|
||||
cloudflareProjectConfigSchema,
|
||||
denoDeployProjectConfigSchema,
|
||||
apkBuilderProjectConfigSchema,
|
||||
]);
|
||||
|
||||
const projectDeploySettingsSchema = z.object({
|
||||
@@ -83,7 +72,6 @@ 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>;
|
||||
|
||||
|
||||
@@ -55,10 +55,19 @@ export function useUserRepositories(userPubkey?: string) {
|
||||
try {
|
||||
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
|
||||
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
|
||||
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
|
||||
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
|
||||
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
|
||||
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
|
||||
|
||||
// Extract multi-value tags correctly (all values are in a single tag per NIP-34)
|
||||
const webTag = event.tags.find(tag => tag[0] === 'web');
|
||||
const webUrls = webTag ? webTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const cloneTag = event.tags.find(tag => tag[0] === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const relaysTag = event.tags.find(tag => tag[0] === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const maintainersTag = event.tags.find(tag => tag[0] === 'maintainers');
|
||||
const maintainers = maintainersTag ? maintainersTag.slice(1).filter(Boolean) : [];
|
||||
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
|
||||
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
|
||||
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
|
||||
|
||||
+22
-13
@@ -450,7 +450,7 @@ export class SessionManager {
|
||||
|
||||
let accumulatedContent = '';
|
||||
let accumulatedReasoningContent = '';
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
const accumulatedToolCalls: Map<number, OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall> = new Map();
|
||||
let finishReason: string | null = null;
|
||||
|
||||
// Process the stream
|
||||
@@ -491,20 +491,29 @@ export class SessionManager {
|
||||
const toolCallDelta = delta.tool_calls[i];
|
||||
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
||||
|
||||
accumulatedToolCalls[index] ??= {
|
||||
id: '',
|
||||
type: 'function',
|
||||
function: { name: '', arguments: '' }
|
||||
};
|
||||
let toolCall = accumulatedToolCalls.get(index);
|
||||
|
||||
if (!toolCall) {
|
||||
toolCall = {
|
||||
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) {
|
||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
||||
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;
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
@@ -528,7 +537,7 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Fix tool calls with empty arguments or names
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
for (const toolCall of accumulatedToolCalls.values()) {
|
||||
if (toolCall.type === 'function') {
|
||||
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
||||
|
||||
@@ -549,7 +558,7 @@ export class SessionManager {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
...(accumulatedToolCalls.size > 0 && { tool_calls: [...accumulatedToolCalls.values()] })
|
||||
};
|
||||
|
||||
// Check if the assistant message is empty (no content, reasoning, or tool calls)
|
||||
@@ -575,8 +584,8 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Handle tool calls
|
||||
if (accumulatedToolCalls?.length) {
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (accumulatedToolCalls?.size) {
|
||||
for (const toolCall of accumulatedToolCalls.values()) {
|
||||
if (toolCall.type !== 'function') continue;
|
||||
|
||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
|
||||
+41
-4
@@ -58,14 +58,51 @@ 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 usage accounting
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
if (provider.id === 'openrouter') {
|
||||
// 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
|
||||
(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" };
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -23,6 +23,14 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||
tosURL: "https://openrouter.ai/terms",
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode Zen",
|
||||
baseURL: "https://opencode.ai/zen/v1",
|
||||
apiKeysURL: "https://opencode.ai/auth",
|
||||
tosURL: "https://opencode.ai/legal/terms-of-service",
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: "ppq",
|
||||
name: "PayPerQ",
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from './signing';
|
||||
export * from './keystore';
|
||||
@@ -1,95 +0,0 @@
|
||||
/**
|
||||
* Keystore persistence utilities
|
||||
* Saves/loads signing keys from localStorage
|
||||
*/
|
||||
import type { SigningKey } from './signing';
|
||||
import { importKeyFromPkcs12, exportKeyToPkcs12 } from './signing';
|
||||
|
||||
const STORAGE_KEY = 'shakespeare:apk-signing-key';
|
||||
|
||||
export interface StoredKeyInfo {
|
||||
alias: string;
|
||||
commonName: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
interface StoredKeyData {
|
||||
p12Base64: string;
|
||||
info: StoredKeyInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a signing key is saved in localStorage
|
||||
*/
|
||||
export function hasSavedKey(): boolean {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
return stored !== null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get info about the saved key without loading it
|
||||
*/
|
||||
export function getSavedKeyInfo(): StoredKeyInfo | null {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (!stored) return null;
|
||||
|
||||
const data: StoredKeyData = JSON.parse(stored);
|
||||
return data.info;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a saved signing key from localStorage
|
||||
* Requires the password to decrypt the PKCS#12 data
|
||||
*/
|
||||
export function loadSavedKey(password: string): SigningKey {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (!stored) {
|
||||
throw new Error('No saved signing key found');
|
||||
}
|
||||
|
||||
const data: StoredKeyData = JSON.parse(stored);
|
||||
const p12Buffer = Uint8Array.from(atob(data.p12Base64), c => c.charCodeAt(0));
|
||||
|
||||
return importKeyFromPkcs12(p12Buffer.buffer, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a signing key to localStorage
|
||||
* The key is stored as encrypted PKCS#12 data
|
||||
*/
|
||||
export function saveKey(key: SigningKey, password: string): void {
|
||||
const p12Data = exportKeyToPkcs12(key, password);
|
||||
const p12Base64 = btoa(String.fromCharCode(...p12Data));
|
||||
|
||||
// Extract certificate info
|
||||
const cert = key.certificate;
|
||||
const commonName = cert.subject.getField('CN')?.value || key.alias;
|
||||
|
||||
const data: StoredKeyData = {
|
||||
p12Base64,
|
||||
info: {
|
||||
alias: key.alias,
|
||||
commonName: typeof commonName === 'string' ? commonName : key.alias,
|
||||
createdAt: cert.validity.notBefore.toISOString(),
|
||||
expiresAt: cert.validity.notAfter.toISOString(),
|
||||
},
|
||||
};
|
||||
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the saved signing key from localStorage
|
||||
*/
|
||||
export function deleteSavedKey(): void {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
@@ -1,905 +0,0 @@
|
||||
/**
|
||||
* Browser-based APK signing utility
|
||||
* Implements JAR signing (v1) for Android APKs
|
||||
*/
|
||||
import JSZip from 'jszip';
|
||||
import forge from 'node-forge';
|
||||
|
||||
export interface SigningKey {
|
||||
privateKey: forge.pki.PrivateKey;
|
||||
certificate: forge.pki.Certificate;
|
||||
alias: string;
|
||||
}
|
||||
|
||||
export interface SigningOptions {
|
||||
key: SigningKey;
|
||||
apkData: ArrayBuffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zipalign implementation for 4-byte alignment
|
||||
* Aligns uncompressed entries to the specified boundary
|
||||
*/
|
||||
function zipalign(data: Uint8Array, alignment: number): Uint8Array {
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
|
||||
// Find End of Central Directory (EOCD)
|
||||
let eocdOffset = -1;
|
||||
for (let i = data.length - 22; i >= 0; i--) {
|
||||
if (view.getUint32(i, true) === 0x06054b50) {
|
||||
eocdOffset = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocdOffset === -1) throw new Error('Invalid ZIP: EOCD not found');
|
||||
|
||||
const cdOffset = view.getUint32(eocdOffset + 16, true);
|
||||
const _cdSize = view.getUint32(eocdOffset + 12, true);
|
||||
const entryCount = view.getUint16(eocdOffset + 10, true);
|
||||
|
||||
// Parse central directory to get file entries
|
||||
interface Entry {
|
||||
nameOffset: number;
|
||||
nameLength: number;
|
||||
extraLength: number;
|
||||
commentLength: number;
|
||||
compressionMethod: number;
|
||||
localHeaderOffset: number;
|
||||
compressedSize: number;
|
||||
uncompressedSize: number;
|
||||
}
|
||||
const entries: Entry[] = [];
|
||||
let pos = cdOffset;
|
||||
for (let i = 0; i < entryCount; i++) {
|
||||
if (view.getUint32(pos, true) !== 0x02014b50) throw new Error('Invalid central directory');
|
||||
const compressionMethod = view.getUint16(pos + 10, true);
|
||||
const compressedSize = view.getUint32(pos + 20, true);
|
||||
const uncompressedSize = view.getUint32(pos + 24, true);
|
||||
const nameLength = view.getUint16(pos + 28, true);
|
||||
const extraLength = view.getUint16(pos + 30, true);
|
||||
const commentLength = view.getUint16(pos + 32, true);
|
||||
const localHeaderOffset = view.getUint32(pos + 42, true);
|
||||
entries.push({
|
||||
nameOffset: pos + 46,
|
||||
nameLength,
|
||||
extraLength,
|
||||
commentLength,
|
||||
compressionMethod,
|
||||
localHeaderOffset,
|
||||
compressedSize,
|
||||
uncompressedSize,
|
||||
});
|
||||
pos += 46 + nameLength + extraLength + commentLength;
|
||||
}
|
||||
|
||||
// Calculate new offsets and padding needed
|
||||
interface AlignmentInfo {
|
||||
entry: Entry;
|
||||
localExtraLength: number;
|
||||
newOffset: number;
|
||||
paddingNeeded: number;
|
||||
name: string;
|
||||
}
|
||||
const alignmentInfos: AlignmentInfo[] = [];
|
||||
let currentOffset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const localPos = entry.localHeaderOffset;
|
||||
if (view.getUint32(localPos, true) !== 0x04034b50) throw new Error('Invalid local header');
|
||||
|
||||
const localNameLength = view.getUint16(localPos + 26, true);
|
||||
const localExtraLength = view.getUint16(localPos + 28, true);
|
||||
const _headerSize = 30 + localNameLength + localExtraLength;
|
||||
const _dataOffset = localPos + _headerSize;
|
||||
|
||||
const nameBytes = data.slice(localPos + 30, localPos + 30 + localNameLength);
|
||||
const name = new TextDecoder().decode(nameBytes);
|
||||
|
||||
// Only align uncompressed files (compression method 0 = STORE)
|
||||
let paddingNeeded = 0;
|
||||
if (entry.compressionMethod === 0 && entry.uncompressedSize > 0) {
|
||||
const newDataOffset = currentOffset + 30 + localNameLength + localExtraLength;
|
||||
const misalignment = newDataOffset % alignment;
|
||||
if (misalignment !== 0) {
|
||||
paddingNeeded = alignment - misalignment;
|
||||
}
|
||||
}
|
||||
|
||||
alignmentInfos.push({
|
||||
entry,
|
||||
localExtraLength,
|
||||
newOffset: currentOffset,
|
||||
paddingNeeded,
|
||||
name,
|
||||
});
|
||||
|
||||
currentOffset += 30 + localNameLength + localExtraLength + paddingNeeded + entry.compressedSize;
|
||||
}
|
||||
|
||||
// Calculate new central directory offset
|
||||
const _newCdOffset = currentOffset;
|
||||
|
||||
// Build new ZIP
|
||||
const cdEntrySize = pos - cdOffset; // Total size of central directory entries
|
||||
const newSize = currentOffset + cdEntrySize + 22;
|
||||
const result = new Uint8Array(newSize);
|
||||
const resultView = new DataView(result.buffer);
|
||||
|
||||
let writePos = 0;
|
||||
|
||||
// Write local file headers and data
|
||||
for (const info of alignmentInfos) {
|
||||
const entry = info.entry;
|
||||
const oldLocalPos = entry.localHeaderOffset;
|
||||
const oldNameLength = view.getUint16(oldLocalPos + 26, true);
|
||||
const oldExtraLength = view.getUint16(oldLocalPos + 28, true);
|
||||
const oldHeaderSize = 30 + oldNameLength + oldExtraLength;
|
||||
|
||||
// Copy local file header
|
||||
result.set(data.slice(oldLocalPos, oldLocalPos + 30), writePos);
|
||||
|
||||
// Update extra field length to include padding
|
||||
const newExtraLength = oldExtraLength + info.paddingNeeded;
|
||||
resultView.setUint16(writePos + 28, newExtraLength, true);
|
||||
|
||||
// Copy filename
|
||||
result.set(data.slice(oldLocalPos + 30, oldLocalPos + 30 + oldNameLength), writePos + 30);
|
||||
|
||||
// Copy original extra field
|
||||
if (oldExtraLength > 0) {
|
||||
result.set(
|
||||
data.slice(oldLocalPos + 30 + oldNameLength, oldLocalPos + 30 + oldNameLength + oldExtraLength),
|
||||
writePos + 30 + oldNameLength
|
||||
);
|
||||
}
|
||||
|
||||
// Padding is implicitly zero-filled (Uint8Array is initialized to 0)
|
||||
|
||||
writePos += 30 + oldNameLength + newExtraLength;
|
||||
|
||||
// Copy file data
|
||||
const dataStart = oldLocalPos + oldHeaderSize;
|
||||
result.set(data.slice(dataStart, dataStart + entry.compressedSize), writePos);
|
||||
writePos += entry.compressedSize;
|
||||
}
|
||||
|
||||
// Write central directory
|
||||
const newCdStart = writePos;
|
||||
for (let i = 0; i < alignmentInfos.length; i++) {
|
||||
const info = alignmentInfos[i];
|
||||
const entry = info.entry;
|
||||
|
||||
// Find this entry in original central directory
|
||||
let oldCdPos = cdOffset;
|
||||
for (let j = 0; j < i; j++) {
|
||||
const e = entries[j];
|
||||
oldCdPos += 46 + e.nameLength + e.extraLength + e.commentLength;
|
||||
}
|
||||
|
||||
const cdEntryLength = 46 + entry.nameLength + entry.extraLength + entry.commentLength;
|
||||
|
||||
// Copy central directory entry
|
||||
result.set(data.slice(oldCdPos, oldCdPos + cdEntryLength), writePos);
|
||||
|
||||
// Update local header offset
|
||||
resultView.setUint32(writePos + 42, info.newOffset, true);
|
||||
|
||||
writePos += cdEntryLength;
|
||||
}
|
||||
|
||||
// Write EOCD
|
||||
result.set(data.slice(eocdOffset, eocdOffset + 22), writePos);
|
||||
// Update central directory offset
|
||||
resultView.setUint32(writePos + 16, newCdStart, true);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* APK Signature Scheme v2 implementation
|
||||
* Inserts a signing block between ZIP content and Central Directory
|
||||
*/
|
||||
function applyV2Signature(apk: Uint8Array, key: SigningKey): Uint8Array {
|
||||
const view = new DataView(apk.buffer, apk.byteOffset, apk.byteLength);
|
||||
|
||||
// Find EOCD
|
||||
let eocdOffset = -1;
|
||||
for (let i = apk.length - 22; i >= 0; i--) {
|
||||
if (view.getUint32(i, true) === 0x06054b50) {
|
||||
eocdOffset = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocdOffset === -1) throw new Error('Invalid ZIP: EOCD not found');
|
||||
|
||||
const cdOffset = view.getUint32(eocdOffset + 16, true);
|
||||
const _cdSize = view.getUint32(eocdOffset + 12, true);
|
||||
|
||||
// Section 1: ZIP entries (before CD)
|
||||
const zipEntries = apk.slice(0, cdOffset);
|
||||
// Section 3: Central Directory
|
||||
const centralDir = apk.slice(cdOffset, eocdOffset);
|
||||
// Section 4: EOCD
|
||||
const eocd = apk.slice(eocdOffset);
|
||||
|
||||
// Calculate content digests using 1MB chunks
|
||||
const CHUNK_SIZE = 1024 * 1024;
|
||||
const digests: Uint8Array[] = [];
|
||||
|
||||
// Helper to compute SHA256
|
||||
const sha256 = (data: Uint8Array): Uint8Array => {
|
||||
const md = forge.md.sha256.create();
|
||||
const len = data.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(data[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
return new Uint8Array(forge.util.binary.raw.decode(md.digest().getBytes()));
|
||||
};
|
||||
|
||||
// Digest section 1 (ZIP entries)
|
||||
for (let offset = 0; offset < zipEntries.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, zipEntries.length);
|
||||
const chunk = zipEntries.slice(offset, chunkEnd);
|
||||
// Chunk format: 0xa5 + 4-byte little-endian length + data
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Digest section 3 (Central Directory)
|
||||
for (let offset = 0; offset < centralDir.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, centralDir.length);
|
||||
const chunk = centralDir.slice(offset, chunkEnd);
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Pre-calculate signing block size to compute modified EOCD
|
||||
// The signing block size depends on: certificate size, signature size (256 for RSA-2048), public key size
|
||||
// We'll compute the actual size after building the blocks, but for now estimate
|
||||
// Actually, we need to include EOCD with modified offset in the digest
|
||||
// So we need to know the final signing block size first
|
||||
|
||||
// For RSA-2048: signature is 256 bytes
|
||||
// We'll calculate the exact size by building the structure first without the actual signature
|
||||
const certDerForSize = getCertificateDer(key.certificate);
|
||||
const pubKeyDerForSize = getPublicKeyDer(key.certificate);
|
||||
|
||||
// Calculate signing block size components:
|
||||
// digestsBlock: 4 (seq) + 4 (entry) + 4 (algo) + 4 (digest_len) + 32 (digest) = 48
|
||||
// certsBlock: 4 + 4 + certDer.length
|
||||
// attrsBlock: 4
|
||||
// signedData: 4 + digestsBlock + certsBlock + attrsBlock
|
||||
// sigsBlock: 4 (seq) + 4 (entry) + 4 (algo) + 4 (sig_len) + 256 (sig) = 272 (RSA-2048)
|
||||
// pubKeyBlock: 4 + pubKeyDer.length
|
||||
// signerBlock: 4 + signedData + sigsBlock + pubKeyBlock
|
||||
// signersBlock: 4 + signerBlock
|
||||
// v2Block: 8 (pair_size) + 4 (id) + signersBlock
|
||||
// signingBlock: 8 + v2Block + 8 + 16
|
||||
const digestsBlockSize = 4 + 4 + 4 + 4 + 32; // 48
|
||||
const certsBlockSize = 4 + 4 + certDerForSize.length;
|
||||
const attrsBlockSize = 4;
|
||||
const signedDataSize = 4 + digestsBlockSize + certsBlockSize + attrsBlockSize;
|
||||
const sigsBlockSize = 4 + 4 + 4 + 4 + 256; // 272 for RSA-2048 signature
|
||||
const pubKeyBlockSize = 4 + pubKeyDerForSize.length;
|
||||
const signerBlockSize = 4 + signedDataSize + sigsBlockSize + pubKeyBlockSize;
|
||||
const signersBlockSize = 4 + signerBlockSize;
|
||||
const v2BlockSize = 8 + 4 + signersBlockSize; // uint64 pair_size + uint32 ID + value
|
||||
const signingBlockTotalSize = 8 + v2BlockSize + 8 + 16;
|
||||
|
||||
// For digest computation, EOCD's offset is treated as pointing to signing block start
|
||||
// (which is the original cdOffset, where we'll insert the signing block)
|
||||
// The actual file's EOCD will point to real CD, but digest uses signing block offset
|
||||
const eocdForDigest = new Uint8Array(eocd);
|
||||
// cdOffset is where signing block will be inserted, so EOCD offset = cdOffset for digest
|
||||
new DataView(eocdForDigest.buffer).setUint32(16, cdOffset, true);
|
||||
|
||||
// Digest section 4 (EOCD with modified CD offset)
|
||||
for (let offset = 0; offset < eocdForDigest.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, eocdForDigest.length);
|
||||
const chunk = eocdForDigest.slice(offset, chunkEnd);
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Combine chunk digests into content digest
|
||||
// Format: 0x5a + 4-byte count + all digests concatenated
|
||||
const digestData = new Uint8Array(5 + digests.length * 32);
|
||||
digestData[0] = 0x5a;
|
||||
new DataView(digestData.buffer).setUint32(1, digests.length, true);
|
||||
for (let i = 0; i < digests.length; i++) {
|
||||
digestData.set(digests[i], 5 + i * 32);
|
||||
}
|
||||
const contentDigest = sha256(digestData);
|
||||
|
||||
// Build signed data
|
||||
// Structure: sequence of length-prefixed digests, certificates, and additional attributes
|
||||
const certDer = getCertificateDer(key.certificate);
|
||||
|
||||
// Digests: length-prefixed sequence of length-prefixed (algorithmId, digest) pairs
|
||||
// Algorithm ID: 0x0103 = RSASSA-PKCS1-v1_5 with SHA-256
|
||||
// Structure: sequence_length + [entry_length + algorithm_id + digest_length + digest]
|
||||
const digestEntrySize = 4 + 4 + 32; // algorithm_id + digest_length + digest
|
||||
const digestsBlock = new Uint8Array(4 + 4 + digestEntrySize);
|
||||
let dPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 4 + digestEntrySize, true);
|
||||
dPos += 4;
|
||||
// Entry length
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, digestEntrySize, true);
|
||||
dPos += 4;
|
||||
// Algorithm ID
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 0x0103, true);
|
||||
dPos += 4;
|
||||
// Digest length
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 32, true);
|
||||
dPos += 4;
|
||||
// Digest
|
||||
digestsBlock.set(contentDigest, dPos);
|
||||
|
||||
// Certificates: length-prefixed sequence of DER-encoded certificates
|
||||
const certsBlock = new Uint8Array(4 + 4 + certDer.length);
|
||||
let cPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(certsBlock.buffer).setUint32(cPos, 4 + certDer.length, true);
|
||||
cPos += 4;
|
||||
// Certificate length
|
||||
new DataView(certsBlock.buffer).setUint32(cPos, certDer.length, true);
|
||||
cPos += 4;
|
||||
// Certificate
|
||||
certsBlock.set(certDer, cPos);
|
||||
|
||||
// Additional attributes (empty for now)
|
||||
const attrsBlock = new Uint8Array(4);
|
||||
new DataView(attrsBlock.buffer).setUint32(0, 0, true);
|
||||
|
||||
// Combine into signed data content (without length prefix - that's added separately)
|
||||
const signedDataContent = new Uint8Array(digestsBlock.length + certsBlock.length + attrsBlock.length);
|
||||
let sdPos = 0;
|
||||
signedDataContent.set(digestsBlock, sdPos);
|
||||
sdPos += digestsBlock.length;
|
||||
signedDataContent.set(certsBlock, sdPos);
|
||||
sdPos += certsBlock.length;
|
||||
signedDataContent.set(attrsBlock, sdPos);
|
||||
|
||||
// Sign the signed data content (RSA-PKCS1-v1_5 with SHA-256)
|
||||
// The signing algorithm hashes internally, so we feed it the raw content
|
||||
const md = forge.md.sha256.create();
|
||||
// Convert to string in chunks to avoid stack overflow
|
||||
const len = signedDataContent.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(signedDataContent[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
const rsaPrivateKey = key.privateKey as unknown as forge.pki.rsa.PrivateKey;
|
||||
const signature = rsaPrivateKey.sign(md);
|
||||
const signatureBytes = new Uint8Array(forge.util.binary.raw.decode(signature));
|
||||
|
||||
// Create length-prefixed signed data for the signer block
|
||||
const signedData = new Uint8Array(4 + signedDataContent.length);
|
||||
new DataView(signedData.buffer).setUint32(0, signedDataContent.length, true);
|
||||
signedData.set(signedDataContent, 4);
|
||||
|
||||
// Build signatures block
|
||||
// Structure: sequence_length + [entry_length + algorithm_id + signature_length + signature]
|
||||
const sigEntrySize = 4 + 4 + signatureBytes.length; // algorithm_id + sig_length + signature
|
||||
const sigsBlock = new Uint8Array(4 + 4 + sigEntrySize);
|
||||
let sPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, 4 + sigEntrySize, true);
|
||||
sPos += 4;
|
||||
// Entry length
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, sigEntrySize, true);
|
||||
sPos += 4;
|
||||
// Algorithm ID
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, 0x0103, true);
|
||||
sPos += 4;
|
||||
// Signature length
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, signatureBytes.length, true);
|
||||
sPos += 4;
|
||||
// Signature
|
||||
sigsBlock.set(signatureBytes, sPos);
|
||||
|
||||
// Get public key DER
|
||||
const pubKeyDer = getPublicKeyDer(key.certificate);
|
||||
const pubKeyBlock = new Uint8Array(4 + pubKeyDer.length);
|
||||
new DataView(pubKeyBlock.buffer).setUint32(0, pubKeyDer.length, true);
|
||||
pubKeyBlock.set(pubKeyDer, 4);
|
||||
|
||||
// Build signer block
|
||||
const signerBlock = new Uint8Array(4 + signedData.length + sigsBlock.length + pubKeyBlock.length);
|
||||
let signerPos = 0;
|
||||
// Length prefix
|
||||
new DataView(signerBlock.buffer).setUint32(signerPos, signedData.length + sigsBlock.length + pubKeyBlock.length, true);
|
||||
signerPos += 4;
|
||||
signerBlock.set(signedData, signerPos);
|
||||
signerPos += signedData.length;
|
||||
signerBlock.set(sigsBlock, signerPos);
|
||||
signerPos += sigsBlock.length;
|
||||
signerBlock.set(pubKeyBlock, signerPos);
|
||||
|
||||
// Build signers sequence (just one signer)
|
||||
const signersBlock = new Uint8Array(4 + signerBlock.length);
|
||||
new DataView(signersBlock.buffer).setUint32(0, signerBlock.length, true);
|
||||
signersBlock.set(signerBlock, 4);
|
||||
|
||||
// Build v2 signature block (ID 0x7109871a)
|
||||
// Format: uint64 pair_size + uint32 ID + value
|
||||
const v2Block = new Uint8Array(8 + 4 + signersBlock.length);
|
||||
// Pair size (uint64): ID (4 bytes) + value
|
||||
new DataView(v2Block.buffer).setBigUint64(0, BigInt(4 + signersBlock.length), true);
|
||||
// ID (uint32)
|
||||
new DataView(v2Block.buffer).setUint32(8, 0x7109871a, true);
|
||||
// Value (signers)
|
||||
v2Block.set(signersBlock, 12);
|
||||
|
||||
// Build APK Signing Block
|
||||
// Structure: 8-byte size + pairs + 8-byte size + 16-byte magic
|
||||
const MAGIC = new Uint8Array([
|
||||
0x41, 0x50, 0x4b, 0x20, 0x53, 0x69, 0x67, 0x20,
|
||||
0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x34, 0x32,
|
||||
]); // "APK Sig Block 42"
|
||||
|
||||
const pairsSize = v2Block.length;
|
||||
const blockSize = pairsSize + 8 + 16; // pairs + second size + magic
|
||||
const signingBlock = new Uint8Array(8 + blockSize);
|
||||
let sbPos = 0;
|
||||
// First size
|
||||
new DataView(signingBlock.buffer).setBigUint64(sbPos, BigInt(blockSize), true);
|
||||
sbPos += 8;
|
||||
// Pairs (v2 block)
|
||||
signingBlock.set(v2Block, sbPos);
|
||||
sbPos += v2Block.length;
|
||||
// Second size
|
||||
new DataView(signingBlock.buffer).setBigUint64(sbPos, BigInt(blockSize), true);
|
||||
sbPos += 8;
|
||||
// Magic
|
||||
signingBlock.set(MAGIC, sbPos);
|
||||
|
||||
// Verify size calculation matches actual size
|
||||
if (signingBlockTotalSize !== signingBlock.length) {
|
||||
throw new Error('V2 signing block size mismatch - digest will be invalid');
|
||||
}
|
||||
|
||||
// Update EOCD with new CD offset (after signing block)
|
||||
const newEocd = new Uint8Array(eocd);
|
||||
new DataView(newEocd.buffer).setUint32(16, cdOffset + signingBlock.length, true);
|
||||
|
||||
// Build final APK
|
||||
const result = new Uint8Array(zipEntries.length + signingBlock.length + centralDir.length + newEocd.length);
|
||||
let rPos = 0;
|
||||
result.set(zipEntries, rPos);
|
||||
rPos += zipEntries.length;
|
||||
result.set(signingBlock, rPos);
|
||||
rPos += signingBlock.length;
|
||||
result.set(centralDir, rPos);
|
||||
rPos += centralDir.length;
|
||||
result.set(newEocd, rPos);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate as DER bytes
|
||||
*/
|
||||
function getCertificateDer(cert: forge.pki.Certificate): Uint8Array {
|
||||
const pem = forge.pki.certificateToPem(cert);
|
||||
const base64 = pem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
const der = forge.util.decode64(base64);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get public key as DER bytes (SubjectPublicKeyInfo)
|
||||
*/
|
||||
function getPublicKeyDer(cert: forge.pki.Certificate): Uint8Array {
|
||||
const pem = forge.pki.publicKeyToPem(cert.publicKey);
|
||||
const base64 = pem
|
||||
.replace(/-----BEGIN PUBLIC KEY-----/, '')
|
||||
.replace(/-----END PUBLIC KEY-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
const der = forge.util.decode64(base64);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign an APK using JAR signing (v1 signature scheme)
|
||||
* This creates META-INF/MANIFEST.MF, META-INF/CERT.SF, and META-INF/CERT.RSA
|
||||
*/
|
||||
export async function signApk(options: SigningOptions): Promise<Blob> {
|
||||
const { key, apkData } = options;
|
||||
|
||||
// Load the APK (ZIP file)
|
||||
const zip = await JSZip.loadAsync(apkData);
|
||||
|
||||
// Remove any existing signatures
|
||||
zip.remove('META-INF/MANIFEST.MF');
|
||||
zip.remove('META-INF/CERT.SF');
|
||||
zip.remove('META-INF/CERT.RSA');
|
||||
zip.remove('META-INF/CERT.DSA');
|
||||
zip.remove('META-INF/CERT.EC');
|
||||
|
||||
// Remove any other signature files
|
||||
const metaInfFiles = Object.keys(zip.files).filter(f =>
|
||||
f.startsWith('META-INF/') && (f.endsWith('.SF') || f.endsWith('.RSA') || f.endsWith('.DSA') || f.endsWith('.EC'))
|
||||
);
|
||||
for (const file of metaInfFiles) {
|
||||
zip.remove(file);
|
||||
}
|
||||
|
||||
// Create MANIFEST.MF
|
||||
const manifest = await createManifest(zip);
|
||||
zip.file('META-INF/MANIFEST.MF', manifest, { compression: 'DEFLATE' });
|
||||
|
||||
// Create CERT.SF (signature file)
|
||||
const signatureFile = createSignatureFile(manifest);
|
||||
zip.file('META-INF/CERT.SF', signatureFile, { compression: 'DEFLATE' });
|
||||
|
||||
// Create CERT.RSA (PKCS#7 signature block)
|
||||
const signatureBlock = createSignatureBlock(signatureFile, key);
|
||||
zip.file('META-INF/CERT.RSA', signatureBlock, { compression: 'DEFLATE' });
|
||||
|
||||
// Generate the signed APK
|
||||
// Don't use global compression - preserve original compression settings
|
||||
// This is critical for resources.arsc which must be STORE (uncompressed) on Android 11+
|
||||
const signedApkRaw = await zip.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
// Use per-file compression to preserve original settings
|
||||
// resources.arsc and .so files must stay uncompressed
|
||||
});
|
||||
|
||||
// Apply zipalign to ensure 4-byte alignment for uncompressed files
|
||||
// This is required for Android 11+ (API 30+)
|
||||
const alignedApk = zipalign(new Uint8Array(signedApkRaw), 4);
|
||||
|
||||
// Apply APK Signature Scheme v2
|
||||
// This is required for Android 7.0+ and mandatory for Android 11+
|
||||
const v2SignedApk = applyV2Signature(alignedApk, key);
|
||||
|
||||
return new Blob([v2SignedApk], { type: 'application/vnd.android.package-archive' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Create MANIFEST.MF with SHA-256 digests of all files
|
||||
*/
|
||||
async function createManifest(zip: JSZip): Promise<string> {
|
||||
const lines: string[] = [
|
||||
'Manifest-Version: 1.0',
|
||||
'Created-By: Shakespeare APK Signer',
|
||||
'',
|
||||
];
|
||||
|
||||
// Get all files (excluding META-INF directory)
|
||||
const files = Object.keys(zip.files)
|
||||
.filter(name => !zip.files[name].dir && !name.startsWith('META-INF/'))
|
||||
.sort();
|
||||
|
||||
for (const fileName of files) {
|
||||
const file = zip.files[fileName];
|
||||
const content = await file.async('uint8array');
|
||||
const digest = sha256Base64(content);
|
||||
|
||||
lines.push(`Name: ${fileName}`);
|
||||
lines.push(`SHA-256-Digest: ${digest}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create CERT.SF (signature file) with digests of manifest sections
|
||||
*/
|
||||
function createSignatureFile(manifest: string): string {
|
||||
const lines: string[] = [
|
||||
'Signature-Version: 1.0',
|
||||
'Created-By: Shakespeare APK Signer',
|
||||
`SHA-256-Digest-Manifest: ${sha256Base64(new TextEncoder().encode(manifest))}`,
|
||||
'',
|
||||
];
|
||||
|
||||
// Parse manifest sections and create digests for each
|
||||
const sections = manifest.split('\r\n\r\n');
|
||||
|
||||
for (let i = 1; i < sections.length; i++) {
|
||||
const section = sections[i];
|
||||
if (!section.trim()) continue;
|
||||
|
||||
// Extract the Name attribute
|
||||
const nameMatch = section.match(/^Name: (.+)$/m);
|
||||
if (nameMatch) {
|
||||
const sectionWithNewline = section + '\r\n\r\n';
|
||||
const digest = sha256Base64(new TextEncoder().encode(sectionWithNewline));
|
||||
|
||||
lines.push(`Name: ${nameMatch[1]}`);
|
||||
lines.push(`SHA-256-Digest: ${digest}`);
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create CERT.RSA (PKCS#7 signature block)
|
||||
*/
|
||||
function createSignatureBlock(signatureFile: string, key: SigningKey): Uint8Array {
|
||||
const { privateKey, certificate } = key;
|
||||
|
||||
// Create SHA-256 digest of the signature file
|
||||
const md = forge.md.sha256.create();
|
||||
md.update(signatureFile, 'utf8');
|
||||
|
||||
// Sign the digest directly with RSA
|
||||
// Type assertion needed due to node-forge type definition issues
|
||||
const rsaPrivateKey = privateKey as unknown as forge.pki.rsa.PrivateKey;
|
||||
const signature = rsaPrivateKey.sign(md);
|
||||
|
||||
// Build PKCS#7 SignedData structure manually
|
||||
// This avoids the recursion issues in forge.pkcs7
|
||||
// Use PEM->DER conversion to avoid certificateToAsn1 recursion issues
|
||||
const certPem = forge.pki.certificateToPem(certificate);
|
||||
|
||||
const certDerBase64 = certPem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
|
||||
const certDer = forge.util.decode64(certDerBase64);
|
||||
|
||||
const certAsn1 = forge.asn1.fromDer(certDer);
|
||||
|
||||
// Build issuer DN ASN.1
|
||||
let issuerAsn1;
|
||||
if (certificate.issuer.attributes.length > 0) {
|
||||
issuerAsn1 = forge.pki.distinguishedNameToAsn1(certificate.issuer);
|
||||
} else {
|
||||
issuerAsn1 = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, []);
|
||||
}
|
||||
|
||||
const signerInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// version
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.asn1.integerToDer(1).getBytes()),
|
||||
// issuerAndSerialNumber
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// issuer
|
||||
issuerAsn1,
|
||||
// serialNumber
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.util.hexToBytes(certificate.serialNumber)),
|
||||
]),
|
||||
// digestAlgorithm (SHA-256)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
// digestEncryptionAlgorithm (RSA)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.1.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
// encryptedDigest (the signature)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OCTETSTRING, false, signature),
|
||||
]);
|
||||
|
||||
const signedData = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// version
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.asn1.integerToDer(1).getBytes()),
|
||||
// digestAlgorithms
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
]),
|
||||
// contentInfo (empty for detached signature)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.7.1').getBytes()),
|
||||
]),
|
||||
// certificates (implicit tag 0)
|
||||
forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [certAsn1]),
|
||||
// signerInfos
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [signerInfo]),
|
||||
]);
|
||||
|
||||
// Wrap in ContentInfo
|
||||
const contentInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// contentType (signedData)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.7.2').getBytes()),
|
||||
// content
|
||||
forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [signedData]),
|
||||
]);
|
||||
|
||||
const der = forge.asn1.toDer(contentInfo);
|
||||
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate SHA-256 hash and return as base64
|
||||
*/
|
||||
function sha256Base64(data: Uint8Array): string {
|
||||
const md = forge.md.sha256.create();
|
||||
// forge.util.binary.raw.encode uses String.fromCharCode.apply which causes
|
||||
// stack overflow for large arrays. Build string manually.
|
||||
const len = data.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(data[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
const digest = md.digest();
|
||||
return forge.util.encode64(digest.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new signing key pair and self-signed certificate
|
||||
*/
|
||||
export function generateSigningKey(options: {
|
||||
commonName: string;
|
||||
organizationName?: string;
|
||||
countryCode?: string;
|
||||
validityYears?: number;
|
||||
alias?: string;
|
||||
}): SigningKey {
|
||||
const {
|
||||
commonName,
|
||||
organizationName = 'Shakespeare',
|
||||
countryCode = 'US',
|
||||
validityYears = 25,
|
||||
alias = 'key0',
|
||||
} = options;
|
||||
|
||||
// Generate RSA key pair
|
||||
const keys = forge.pki.rsa.generateKeyPair(2048);
|
||||
|
||||
// Create certificate
|
||||
const cert = forge.pki.createCertificate();
|
||||
cert.publicKey = keys.publicKey;
|
||||
cert.serialNumber = '01' + forge.util.bytesToHex(forge.random.getBytesSync(8));
|
||||
|
||||
// Set validity
|
||||
cert.validity.notBefore = new Date();
|
||||
cert.validity.notAfter = new Date();
|
||||
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + validityYears);
|
||||
|
||||
// Set subject/issuer attributes
|
||||
const attrs = [
|
||||
{ name: 'commonName', value: commonName },
|
||||
{ name: 'organizationName', value: organizationName },
|
||||
{ name: 'countryName', value: countryCode },
|
||||
];
|
||||
cert.setSubject(attrs);
|
||||
cert.setIssuer(attrs);
|
||||
|
||||
// Set extensions
|
||||
cert.setExtensions([
|
||||
{
|
||||
name: 'basicConstraints',
|
||||
cA: false,
|
||||
},
|
||||
{
|
||||
name: 'keyUsage',
|
||||
digitalSignature: true,
|
||||
keyEncipherment: true,
|
||||
},
|
||||
{
|
||||
name: 'extKeyUsage',
|
||||
codeSigning: true,
|
||||
},
|
||||
]);
|
||||
|
||||
// Self-sign the certificate
|
||||
cert.sign(keys.privateKey, forge.md.sha256.create());
|
||||
|
||||
return {
|
||||
privateKey: keys.privateKey,
|
||||
certificate: cert,
|
||||
alias,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Export signing key to PKCS#12 format (.p12)
|
||||
*/
|
||||
export function exportKeyToPkcs12(key: SigningKey, password: string): Uint8Array {
|
||||
// Type assertion needed due to node-forge type definition issues
|
||||
const p12Asn1 = forge.pkcs12.toPkcs12Asn1(
|
||||
key.privateKey as unknown as Parameters<typeof forge.pkcs12.toPkcs12Asn1>[0],
|
||||
[key.certificate],
|
||||
password,
|
||||
{
|
||||
friendlyName: key.alias,
|
||||
algorithm: '3des', // Use 3DES for compatibility
|
||||
}
|
||||
);
|
||||
|
||||
const p12Der = forge.asn1.toDer(p12Asn1);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(p12Der.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Import signing key from PKCS#12 format (.p12 / .pfx)
|
||||
*/
|
||||
export function importKeyFromPkcs12(data: ArrayBuffer, password: string): SigningKey {
|
||||
const p12Der = forge.util.binary.raw.encode(new Uint8Array(data));
|
||||
const p12Asn1 = forge.asn1.fromDer(p12Der);
|
||||
const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, password);
|
||||
|
||||
// Find the private key and certificate
|
||||
let privateKey: forge.pki.PrivateKey | null = null;
|
||||
let certificate: forge.pki.Certificate | null = null;
|
||||
let alias = 'key0';
|
||||
|
||||
for (const safeContents of p12.safeContents) {
|
||||
for (const safeBag of safeContents.safeBags) {
|
||||
if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag && safeBag.key) {
|
||||
privateKey = safeBag.key;
|
||||
if (safeBag.attributes?.friendlyName?.[0]) {
|
||||
alias = safeBag.attributes.friendlyName[0];
|
||||
}
|
||||
} else if (safeBag.type === forge.pki.oids.certBag && safeBag.cert) {
|
||||
certificate = safeBag.cert;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!privateKey || !certificate) {
|
||||
throw new Error('Could not find private key and certificate in PKCS#12 file');
|
||||
}
|
||||
|
||||
return { privateKey, certificate, alias };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if data is a JKS (Java KeyStore) file and throw helpful error
|
||||
* Note: JKS is a proprietary format. For best compatibility, convert to PKCS#12 first:
|
||||
* keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12
|
||||
*/
|
||||
export function checkJksAndThrow(data: ArrayBuffer): never {
|
||||
const view = new DataView(data);
|
||||
|
||||
// JKS magic number: 0xFEEDFEED
|
||||
const magic = view.getUint32(0, false);
|
||||
if (magic === 0xFEEDFEED) {
|
||||
throw new Error(
|
||||
'JKS format is not directly supported. Please convert to PKCS#12 format using:\n' +
|
||||
'keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12'
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error('Unknown keystore format. Please use PKCS#12 (.p12 / .pfx) format.');
|
||||
}
|
||||
@@ -129,12 +129,6 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
|
||||
baseDomain: z.string().optional(),
|
||||
});
|
||||
|
||||
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,
|
||||
@@ -142,7 +136,6 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
|
||||
nsiteProviderSchema,
|
||||
cloudflareProviderSchema,
|
||||
denoDeployProviderSchema,
|
||||
apkBuilderProviderSchema,
|
||||
]);
|
||||
|
||||
const deploySettingsSchema = z.object({
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
import JSZip from 'jszip';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, APKBuilderDeployConfig, APKBuildType } from './types';
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
|
||||
interface APKBuildStatus {
|
||||
id: string;
|
||||
status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled';
|
||||
progress: number;
|
||||
error?: string;
|
||||
apkSize?: number;
|
||||
logs?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* APK Builder Deploy Adapter
|
||||
* Builds Android APKs from web projects using a Capacitor build service
|
||||
*/
|
||||
export class APKBuilderAdapter implements DeployAdapter {
|
||||
private fs: JSRuntimeFS;
|
||||
private buildServerUrl: string;
|
||||
private apiKey: string;
|
||||
private appName: string;
|
||||
private packageId: string;
|
||||
private buildType: APKBuildType;
|
||||
private corsProxy?: string;
|
||||
private onProgress?: (status: APKBuildStatus) => void;
|
||||
|
||||
constructor(config: APKBuilderDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
this.buildServerUrl = config.buildServerUrl.replace(/\/$/, '');
|
||||
this.apiKey = config.apiKey;
|
||||
this.appName = config.appName;
|
||||
this.packageId = config.packageId;
|
||||
this.buildType = config.buildType || 'debug';
|
||||
this.corsProxy = config.corsProxy;
|
||||
this.onProgress = config.onProgress;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectPath } = options;
|
||||
const distPath = `${projectPath}/dist`;
|
||||
|
||||
// Verify dist exists
|
||||
try {
|
||||
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
|
||||
} catch {
|
||||
throw new Error('No dist folder found. Build the project first using the Build button.');
|
||||
}
|
||||
|
||||
// Create ZIP of dist folder
|
||||
const zip = new JSZip();
|
||||
const distFolder = zip.folder('dist');
|
||||
if (!distFolder) {
|
||||
throw new Error('Failed to create ZIP folder');
|
||||
}
|
||||
await this.addDirectoryToZip(distPath, distFolder);
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Submit build request
|
||||
const buildId = await this.submitBuild(zipBlob);
|
||||
|
||||
// Poll for completion
|
||||
const result = await this.waitForBuild(buildId);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async submitBuild(zipBlob: Blob): Promise<string> {
|
||||
const url = `${this.buildServerUrl}/api/build`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('project', zipBlob, 'project.zip');
|
||||
formData.append('config', JSON.stringify({
|
||||
appName: this.appName,
|
||||
packageId: this.packageId,
|
||||
buildType: this.buildType,
|
||||
}));
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || `Build submission failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.buildId;
|
||||
}
|
||||
|
||||
private async waitForBuild(buildId: string): Promise<DeployResult> {
|
||||
const maxWait = 10 * 60 * 1000; // 10 minutes
|
||||
const pollInterval = 3000; // 3 seconds
|
||||
const startTime = Date.now();
|
||||
|
||||
while (Date.now() - startTime < maxWait) {
|
||||
const status = await this.getStatus(buildId);
|
||||
|
||||
if (this.onProgress) {
|
||||
this.onProgress(status);
|
||||
}
|
||||
|
||||
if (status.status === 'complete') {
|
||||
// Fetch APK with header auth and create blob URL
|
||||
const apkBlobUrl = await this.downloadApk(buildId);
|
||||
|
||||
return {
|
||||
url: apkBlobUrl,
|
||||
metadata: {
|
||||
buildId,
|
||||
type: 'apk',
|
||||
appName: this.appName,
|
||||
packageId: this.packageId,
|
||||
buildType: this.buildType,
|
||||
apkSize: status.apkSize,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (status.status === 'failed') {
|
||||
throw new Error(status.error || 'APK build failed');
|
||||
}
|
||||
|
||||
if (status.status === 'cancelled') {
|
||||
throw new Error('APK build was cancelled');
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
throw new Error('APK build timed out after 10 minutes');
|
||||
}
|
||||
|
||||
private async downloadApk(buildId: string): Promise<string> {
|
||||
const url = `${this.buildServerUrl}/api/build/${buildId}/download`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download APK: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
private async getStatus(buildId: string): Promise<APKBuildStatus> {
|
||||
const url = `${this.buildServerUrl}/api/build/${buildId}/status`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get build status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
|
||||
try {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
const folder = zip.folder(entry.name);
|
||||
if (folder) {
|
||||
await this.addDirectoryToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
try {
|
||||
const fileContent = await this.fs.readFile(fullPath);
|
||||
zip.file(entry.name, fileContent);
|
||||
} catch {
|
||||
console.warn(`Failed to read file ${fullPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
console.warn(`Failed to read directory ${dirPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,4 +5,3 @@ export * from './VercelAdapter';
|
||||
export * from './NsiteAdapter';
|
||||
export * from './CloudflareAdapter';
|
||||
export * from './DenoDeployAdapter';
|
||||
export * from './APKBuilderAdapter';
|
||||
+1
-43
@@ -75,50 +75,9 @@ 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' | 'apkbuilder';
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
|
||||
name: string;
|
||||
description: string;
|
||||
baseURL?: string;
|
||||
@@ -129,6 +88,5 @@ export interface PresetDeployProvider {
|
||||
accountIdURL?: string;
|
||||
organizationIdLabel?: string;
|
||||
organizationIdURL?: string;
|
||||
buildServerUrlLabel?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
@@ -60,14 +60,4 @@ 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,
|
||||
},
|
||||
];
|
||||
@@ -1107,6 +1107,7 @@ class GitHttp implements HttpClient {
|
||||
|
||||
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
|
||||
this.proxy = proxy;
|
||||
// Bind fetch to globalThis to preserve context when called as this.fetch()
|
||||
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
/**
|
||||
* NIP-98 HTTP Auth utilities
|
||||
* Creates signed events for HTTP authentication
|
||||
*/
|
||||
import type { NostrSigner, NostrEvent } from '@nostrify/nostrify';
|
||||
import { proxyUrl } from './proxyUrl';
|
||||
|
||||
/**
|
||||
* Create a NIP-98 auth event for HTTP requests
|
||||
*/
|
||||
export async function createNip98AuthEvent(
|
||||
signer: NostrSigner,
|
||||
url: string,
|
||||
method: string,
|
||||
payload?: string
|
||||
): Promise<NostrEvent> {
|
||||
const tags: string[][] = [
|
||||
['u', url],
|
||||
['method', method.toUpperCase()],
|
||||
];
|
||||
|
||||
// Add payload hash if provided
|
||||
if (payload) {
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(payload);
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
tags.push(['payload', hashHex]);
|
||||
}
|
||||
|
||||
const event = await signer.signEvent({
|
||||
kind: 27235,
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Authorization header value from NIP-98 event
|
||||
*/
|
||||
export function createNip98AuthHeader(event: NostrEvent): string {
|
||||
const eventJson = JSON.stringify(event);
|
||||
const base64 = btoa(eventJson);
|
||||
return `Nostr ${base64}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a NIP-98 authenticated request
|
||||
*/
|
||||
export async function nip98Fetch(
|
||||
signer: NostrSigner,
|
||||
url: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<Response> {
|
||||
const method = options.method || 'GET';
|
||||
const body = options.body as string | undefined;
|
||||
|
||||
const event = await createNip98AuthEvent(signer, url, method, body);
|
||||
const authHeader = createNip98AuthHeader(event);
|
||||
|
||||
return fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
...options.headers,
|
||||
'Authorization': authHeader,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Request an API key from a build server using NIP-98 auth
|
||||
*/
|
||||
export async function requestBuildServerApiKey(
|
||||
signer: NostrSigner,
|
||||
buildServerUrl: string,
|
||||
corsProxy?: string
|
||||
): Promise<{ apiKey: string; pubkey: string; isNew: boolean }> {
|
||||
const authUrl = `${buildServerUrl.replace(/\/+$/, '')}/api/auth`;
|
||||
|
||||
// Create the auth event
|
||||
const event = await createNip98AuthEvent(signer, authUrl, 'POST');
|
||||
const authHeader = createNip98AuthHeader(event);
|
||||
|
||||
// Make the request (use CORS proxy if provided)
|
||||
const targetUrl = corsProxy
|
||||
? proxyUrl(corsProxy, authUrl)
|
||||
: authUrl;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': authHeader,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Request failed' }));
|
||||
throw new Error(error.error || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.success || !data.apiKey) {
|
||||
throw new Error(data.error || 'Failed to get API key');
|
||||
}
|
||||
|
||||
return {
|
||||
apiKey: data.apiKey,
|
||||
pubkey: data.pubkey,
|
||||
isNew: data.isNew,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } from 'lucide-react';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket, Wallet } from 'lucide-react';
|
||||
|
||||
export interface SettingsItem {
|
||||
id: string;
|
||||
@@ -59,6 +59,12 @@ export const getSettingsCategories = (t: (key: string) => string): SettingsCateg
|
||||
title: t('nostrSettings'),
|
||||
href: '/settings/nostr',
|
||||
},
|
||||
{
|
||||
id: 'wallet',
|
||||
icon: Wallet,
|
||||
title: t('walletSettings'),
|
||||
href: '/settings/wallet',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
UnzipCommand,
|
||||
WcCommand,
|
||||
WhoamiCommand,
|
||||
WhichCommand,
|
||||
WhichCommand
|
||||
} from "../commands";
|
||||
|
||||
interface ShellToolParams {
|
||||
|
||||
+36
-18
@@ -54,12 +54,9 @@
|
||||
"showcaseModerator": "Showcase Moderator",
|
||||
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
|
||||
"filesystemPaths": "Filesystem Paths",
|
||||
"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",
|
||||
"projectsDirectory": "Projects",
|
||||
"configDirectory": "Config",
|
||||
"temporaryDirectory": "Temporary",
|
||||
"sentryDsn": "Sentry DSN",
|
||||
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
||||
"shareErrorReports": "Share error reports",
|
||||
@@ -109,12 +106,43 @@
|
||||
"deploySettingsDescription": "Configure deployment providers",
|
||||
"nostrSettings": "Nostr",
|
||||
"nostrSettingsDescription": "Configure relay connections and Nostr preferences",
|
||||
"walletSettings": "Wallet",
|
||||
"walletSettingsDescription": "Connect Lightning wallets for zaps",
|
||||
"currentStatus": "Current Status",
|
||||
"browserExtension": "Browser extension",
|
||||
"ready": "Ready",
|
||||
"notFound": "Not Found",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} wallet(s) connected",
|
||||
"remoteWalletConnection": "Remote wallet connection",
|
||||
"none": "None",
|
||||
"noWalletsConnected": "No wallets connected",
|
||||
"addNwcWalletToGetStarted": "Add an NWC wallet to get started",
|
||||
"lightningWallet": "Lightning Wallet",
|
||||
"nwcConnection": "NWC Connection",
|
||||
"setAsActive": "Set as active",
|
||||
"activeWalletChanged": "Active wallet changed",
|
||||
"selectedWalletNowActive": "The selected wallet is now active for zaps.",
|
||||
"installWeblnOrConnectNwc": "Install a WebLN extension or connect an NWC wallet to send zaps.",
|
||||
"connectNwcWallet": "Connect NWC Wallet",
|
||||
"enterConnectionStringFromWallet": "Enter your connection string from a compatible wallet.",
|
||||
"walletNameOptional": "Wallet Name (optional)",
|
||||
"myLightningWallet": "My Lightning Wallet",
|
||||
"connectionUri": "Connection URI",
|
||||
"connecting": "Connecting...",
|
||||
"connect": "Connect",
|
||||
"connectionUriRequired": "Connection URI required",
|
||||
"pleaseEnterValidNwcUri": "Please enter a valid NWC connection URI.",
|
||||
"storageSettings": "Storage",
|
||||
"storageSettingsDescription": "Export files and manage local data",
|
||||
"emailUpdates": "Email Updates",
|
||||
"emailUpdatesDescription": "Subscribe to Shakespeare updates and resources",
|
||||
"newProject": "New Project",
|
||||
"importRepository": "Import Repository",
|
||||
"explore": "Explore",
|
||||
"exploreApps": "Explore Apps",
|
||||
"exploreRepositories": "Explore repositories from the Nostr network",
|
||||
"pleaseLogInToExplore": "Please log in to explore repositories",
|
||||
"noProjectsYet": "No projects yet",
|
||||
"createFirstProject": "Create your first project to get started",
|
||||
"searchProjects": "Search projects...",
|
||||
@@ -484,8 +512,7 @@
|
||||
"skills": "Skills",
|
||||
"noSkillsFound": "No skills found in this plugin.",
|
||||
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
||||
"pluginsDirectory": "Plugins Directory",
|
||||
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
|
||||
"pluginsDirectory": "Plugins",
|
||||
"discoverPlugins": "Discover Plugins",
|
||||
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
|
||||
"searchPlugins": "Search plugins...",
|
||||
@@ -526,21 +553,12 @@
|
||||
"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 Directory",
|
||||
"templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.",
|
||||
"templatesDirectory": "Templates",
|
||||
"terminal": "Terminal",
|
||||
"templateName": "Template Name",
|
||||
"templateDescription": "Description",
|
||||
|
||||
@@ -104,6 +104,33 @@
|
||||
"nostrSettingsDescription": "Saita haɗin relay da zaɓuɓɓukan Nostr",
|
||||
"storageSettings": "Ajiya",
|
||||
"storageSettingsDescription": "Fitar da fayiloli da sarrafa bayanan gida",
|
||||
"walletSettings": "Walat",
|
||||
"walletSettingsDescription": "Haɗa walat na Lightning don zaps",
|
||||
"currentStatus": "Matsayin Yanzu",
|
||||
"browserExtension": "Ƙari na bincike",
|
||||
"ready": "Shirye",
|
||||
"notFound": "Ba a Samu ba",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} walat da aka haɗa",
|
||||
"remoteWalletConnection": "Haɗin walat na nesa",
|
||||
"none": "Babu",
|
||||
"noWalletsConnected": "Babu walat da aka haɗa",
|
||||
"addNwcWalletToGetStarted": "Ƙara walat NWC don farawa",
|
||||
"lightningWallet": "Walat na Lightning",
|
||||
"nwcConnection": "Haɗin NWC",
|
||||
"setAsActive": "Saita a matsayin mai aiki",
|
||||
"activeWalletChanged": "Walat mai aiki ya canza",
|
||||
"selectedWalletNowActive": "Walat da aka zaɓa yanzu yana aiki don zaps.",
|
||||
"installWeblnOrConnectNwc": "Shigar da ƙarin WebLN ko haɗa walat NWC don aika zaps.",
|
||||
"connectNwcWallet": "Haɗa Walat NWC",
|
||||
"enterConnectionStringFromWallet": "Shigar da igiyar haɗin ku daga walat mai dacewa.",
|
||||
"walletNameOptional": "Sunan Walat (na zaɓi)",
|
||||
"myLightningWallet": "Walat na Lightning Na",
|
||||
"connectionUri": "URI Haɗi",
|
||||
"connecting": "Ana haɗawa...",
|
||||
"connect": "Haɗa",
|
||||
"connectionUriRequired": "URI haɗi yana buƙata",
|
||||
"pleaseEnterValidNwcUri": "Da fatan za a shigar da URI haɗin NWC mai inganci.",
|
||||
"emailUpdates": "Sabuntawar Imel",
|
||||
"emailUpdatesDescription": "Yi rajista don karbar sabuntawar Shakespeare da albarkatu",
|
||||
"newProject": "Sabon Aikin",
|
||||
@@ -140,6 +167,10 @@
|
||||
"unsavedChanges": "Canje-canjen da ba a ajiye ba",
|
||||
"saving": "Ana ajiyewa...",
|
||||
"languageLabel": "Harshe",
|
||||
"explore": "Bincika",
|
||||
"exploreApps": "Bincika Ayyuka",
|
||||
"exploreRepositories": "Bincika ma'ajiyar bayanai daga hanyar sadarwa ta Nostr",
|
||||
"pleaseLogInToExplore": "Da fatan za a shiga don bincika ma'ajiyar bayanai",
|
||||
"searchFiles": "Neman fayiloli...",
|
||||
"noFilesFound": "Babu fayilolin da aka samu",
|
||||
"noFilesFoundSearch": "Babu fayilolin da suka dace da bincikenku",
|
||||
|
||||
@@ -104,6 +104,33 @@
|
||||
"nostrSettingsDescription": "Hazie njikọ relay na nhọrọ Nostr",
|
||||
"storageSettings": "Nchekwa",
|
||||
"storageSettingsDescription": "Bupụta faịlụ na jikwaa data mpaghara",
|
||||
"walletSettings": "Obere Akpa",
|
||||
"walletSettingsDescription": "Jikọọ obere akpa Lightning maka zaps",
|
||||
"currentStatus": "Ọnọdụ Ugbu A",
|
||||
"browserExtension": "Mgbatị ihe nchọgharị",
|
||||
"ready": "Njikere",
|
||||
"notFound": "Achọtaghị",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} obere akpa jikọrọ",
|
||||
"remoteWalletConnection": "Njikọ obere akpa dị anya",
|
||||
"none": "Ọ dịghị",
|
||||
"noWalletsConnected": "Enweghị obere akpa jikọrọ",
|
||||
"addNwcWalletToGetStarted": "Tinye obere akpa NWC iji malite",
|
||||
"lightningWallet": "Obere Akpa Lightning",
|
||||
"nwcConnection": "Njikọ NWC",
|
||||
"setAsActive": "Tọọ dị ka ọrụ",
|
||||
"activeWalletChanged": "Obere akpa na-arụ ọrụ agbanweela",
|
||||
"selectedWalletNowActive": "Obere akpa ahọpụtara na-arụ ọrụ ugbu a maka zaps.",
|
||||
"installWeblnOrConnectNwc": "Wụnye mgbatị WebLN ma ọ bụ jikọọ obere akpa NWC iji zipu zaps.",
|
||||
"connectNwcWallet": "Jikọọ Obere Akpa NWC",
|
||||
"enterConnectionStringFromWallet": "Tinye eriri njikọ gị site na obere akpa dakọtara.",
|
||||
"walletNameOptional": "Aha Obere Akpa (nhọrọ)",
|
||||
"myLightningWallet": "Obere Akpa Lightning M",
|
||||
"connectionUri": "URI Njikọ",
|
||||
"connecting": "Na-ejikọ...",
|
||||
"connect": "Jikọọ",
|
||||
"connectionUriRequired": "URI njikọ achọrọ",
|
||||
"pleaseEnterValidNwcUri": "Biko tinye URI njikọ NWC dị mma.",
|
||||
"emailUpdates": "Nmelite Email",
|
||||
"emailUpdatesDescription": "Debanye aha maka nmelite Shakespeare na akụrụngwa",
|
||||
"newProject": "Ọrụ Ọhụrụ",
|
||||
@@ -140,6 +167,10 @@
|
||||
"unsavedChanges": "Mgbanwe ndị na-echekwaghị",
|
||||
"saving": "Na-echekwa...",
|
||||
"languageLabel": "Asụsụ",
|
||||
"explore": "Chọpụta",
|
||||
"exploreApps": "Chọpụta Ngwa",
|
||||
"exploreRepositories": "Chọpụta ebe nchekwa sitere na netwọk Nostr",
|
||||
"pleaseLogInToExplore": "Biko banye iji chọpụta ebe nchekwa",
|
||||
"searchFiles": "Chọọ faịlụ...",
|
||||
"noFilesFound": "Ahụghị faịlụ ọ bụla",
|
||||
"noFilesFoundSearch": "Ahụghị faịlụ ọ bụla dabara na nchọgharị gị",
|
||||
|
||||
@@ -106,6 +106,33 @@
|
||||
"nostrSettingsDescription": "Configure conexões de relay e preferências do Nostr",
|
||||
"storageSettings": "Armazenamento",
|
||||
"storageSettingsDescription": "Exporte arquivos e gerencie dados locais",
|
||||
"walletSettings": "Carteira",
|
||||
"walletSettingsDescription": "Conecte carteiras Lightning para zaps",
|
||||
"currentStatus": "Status Atual",
|
||||
"browserExtension": "Extensão do navegador",
|
||||
"ready": "Pronto",
|
||||
"notFound": "Não Encontrado",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} carteira(s) conectada(s)",
|
||||
"remoteWalletConnection": "Conexão de carteira remota",
|
||||
"none": "Nenhum",
|
||||
"noWalletsConnected": "Nenhuma carteira conectada",
|
||||
"addNwcWalletToGetStarted": "Adicione uma carteira NWC para começar",
|
||||
"lightningWallet": "Carteira Lightning",
|
||||
"nwcConnection": "Conexão NWC",
|
||||
"setAsActive": "Definir como ativa",
|
||||
"activeWalletChanged": "Carteira ativa alterada",
|
||||
"selectedWalletNowActive": "A carteira selecionada está agora ativa para zaps.",
|
||||
"installWeblnOrConnectNwc": "Instale uma extensão WebLN ou conecte uma carteira NWC para enviar zaps.",
|
||||
"connectNwcWallet": "Conectar Carteira NWC",
|
||||
"enterConnectionStringFromWallet": "Digite sua string de conexão de uma carteira compatível.",
|
||||
"walletNameOptional": "Nome da Carteira (opcional)",
|
||||
"myLightningWallet": "Minha Carteira Lightning",
|
||||
"connectionUri": "URI de Conexão",
|
||||
"connecting": "Conectando...",
|
||||
"connect": "Conectar",
|
||||
"connectionUriRequired": "URI de conexão obrigatória",
|
||||
"pleaseEnterValidNwcUri": "Por favor, insira um URI de conexão NWC válido.",
|
||||
"emailUpdates": "Atualizações por Email",
|
||||
"emailUpdatesDescription": "Inscreva-se para receber atualizações e recursos do Shakespeare",
|
||||
"newProject": "Novo Projeto",
|
||||
@@ -142,6 +169,10 @@
|
||||
"unsavedChanges": "Alterações não salvas",
|
||||
"saving": "Salvando...",
|
||||
"languageLabel": "Linguagem",
|
||||
"explore": "Explorar",
|
||||
"exploreApps": "Explorar Aplicativos",
|
||||
"exploreRepositories": "Explorar repositórios da rede Nostr",
|
||||
"pleaseLogInToExplore": "Por favor, faça login para explorar repositórios",
|
||||
"searchFiles": "Buscar arquivos...",
|
||||
"noFilesFound": "Nenhum arquivo encontrado",
|
||||
"noFilesFoundSearch": "Nenhum arquivo encontrado correspondente à sua busca",
|
||||
|
||||
@@ -104,6 +104,33 @@
|
||||
"nostrSettingsDescription": "Tunto awọn asopọ relay ati awọn ayanfẹ Nostr",
|
||||
"storageSettings": "Ibi ipamọ",
|
||||
"storageSettingsDescription": "Gbe awọn faili jade ati ṣakoso data agbegbe",
|
||||
"walletSettings": "Apamọwọ",
|
||||
"walletSettingsDescription": "So awọn apamọwọ Lightning mọ fun zaps",
|
||||
"currentStatus": "Ipo Lọwọlọwọ",
|
||||
"browserExtension": "Afikun awoṣe",
|
||||
"ready": "Ṣetan",
|
||||
"notFound": "Ko Ri",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} apamọwọ ti a sopọ mọ",
|
||||
"remoteWalletConnection": "Asopọ apamọwọ latọna jijin",
|
||||
"none": "Ko si",
|
||||
"noWalletsConnected": "Ko si awọn apamọwọ ti a sopọ mọ",
|
||||
"addNwcWalletToGetStarted": "Fi apamọwọ NWC kun lati bẹrẹ",
|
||||
"lightningWallet": "Apamọwọ Lightning",
|
||||
"nwcConnection": "Asopọ NWC",
|
||||
"setAsActive": "Ṣeto bi ti nṣiṣẹ",
|
||||
"activeWalletChanged": "Apamọwọ ti nṣiṣẹ ti yipada",
|
||||
"selectedWalletNowActive": "Apamọwọ ti a yan ti nṣiṣẹ bayi fun zaps.",
|
||||
"installWeblnOrConnectNwc": "Fi afikun WebLN sori tabi sopọ apamọwọ NWC lati fi zaps ranṣẹ.",
|
||||
"connectNwcWallet": "Sopọ Apamọwọ NWC",
|
||||
"enterConnectionStringFromWallet": "Tẹ okun asopọ rẹ lati apamọwọ ti o baamu.",
|
||||
"walletNameOptional": "Orukọ Apamọwọ (aṣayan)",
|
||||
"myLightningWallet": "Apamọwọ Lightning Mi",
|
||||
"connectionUri": "URI Asopọ",
|
||||
"connecting": "N sopọ mọ...",
|
||||
"connect": "Sopọ mọ",
|
||||
"connectionUriRequired": "URI asopọ nilo",
|
||||
"pleaseEnterValidNwcUri": "Jọwọ tẹ URI asopọ NWC ti o tọ.",
|
||||
"emailUpdates": "Awọn Imudojuiwọn Imeeli",
|
||||
"emailUpdatesDescription": "Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo",
|
||||
"newProject": "Iṣẹ akanṣe Tuntun",
|
||||
@@ -140,6 +167,10 @@
|
||||
"unsavedChanges": "Awọn iyipada ti a ko fi pamọ",
|
||||
"saving": "N fi pamọ...",
|
||||
"languageLabel": "Ede",
|
||||
"explore": "Ṣawari",
|
||||
"exploreApps": "Ṣawari Awọn Ohun Elo",
|
||||
"exploreRepositories": "Ṣawari awọn ibi ipamọ lati nẹtiwọki Nostr",
|
||||
"pleaseLogInToExplore": "Jọwọ wọle lati ṣawari awọn ibi ipamọ",
|
||||
"searchFiles": "Wa awọn faili...",
|
||||
"noFilesFound": "Ko si awọn faili ti a ri",
|
||||
"noFilesFoundSearch": "Ko si awọn faili ti o baamu wiwa rẹ",
|
||||
|
||||
@@ -106,6 +106,33 @@
|
||||
"nostrSettingsDescription": "配置中继连接和Nostr偏好",
|
||||
"storageSettings": "存储",
|
||||
"storageSettingsDescription": "导出文件和管理本地数据",
|
||||
"walletSettings": "钱包",
|
||||
"walletSettingsDescription": "连接闪电钱包以进行打赏",
|
||||
"currentStatus": "当前状态",
|
||||
"browserExtension": "浏览器扩展",
|
||||
"ready": "就绪",
|
||||
"notFound": "未找到",
|
||||
"nostrWalletConnect": "Nostr钱包连接",
|
||||
"walletsConnected": "已连接{{count}}个钱包",
|
||||
"remoteWalletConnection": "远程钱包连接",
|
||||
"none": "无",
|
||||
"noWalletsConnected": "未连接钱包",
|
||||
"addNwcWalletToGetStarted": "添加NWC钱包以开始使用",
|
||||
"lightningWallet": "闪电钱包",
|
||||
"nwcConnection": "NWC连接",
|
||||
"setAsActive": "设为活动",
|
||||
"activeWalletChanged": "活动钱包已更改",
|
||||
"selectedWalletNowActive": "所选钱包现在已激活用于打赏。",
|
||||
"installWeblnOrConnectNwc": "安装WebLN扩展或连接NWC钱包以发送打赏。",
|
||||
"connectNwcWallet": "连接NWC钱包",
|
||||
"enterConnectionStringFromWallet": "输入来自兼容钱包的连接字符串。",
|
||||
"walletNameOptional": "钱包名称(可选)",
|
||||
"myLightningWallet": "我的闪电钱包",
|
||||
"connectionUri": "连接URI",
|
||||
"connecting": "连接中...",
|
||||
"connect": "连接",
|
||||
"connectionUriRequired": "需要连接URI",
|
||||
"pleaseEnterValidNwcUri": "请输入有效的NWC连接URI。",
|
||||
"emailUpdates": "邮件更新",
|
||||
"emailUpdatesDescription": "订阅Shakespeare更新和资源",
|
||||
"newProject": "新项目",
|
||||
@@ -142,6 +169,10 @@
|
||||
"unsavedChanges": "未保存的更改",
|
||||
"saving": "保存中...",
|
||||
"languageLabel": "语言",
|
||||
"explore": "探索",
|
||||
"exploreApps": "探索应用",
|
||||
"exploreRepositories": "探索Nostr网络中的仓库",
|
||||
"pleaseLogInToExplore": "请登录以探索仓库",
|
||||
"searchFiles": "搜索文件...",
|
||||
"noFilesFound": "未找到文件",
|
||||
"noFilesFoundSearch": "未找到与您搜索匹配的文件",
|
||||
|
||||
@@ -16,6 +16,7 @@ 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';
|
||||
@@ -45,6 +46,7 @@ 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);
|
||||
|
||||
@@ -54,6 +56,7 @@ 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(
|
||||
@@ -256,9 +259,18 @@ export function AISettings() {
|
||||
{selectedPreset && (
|
||||
<AddAIProviderDialog
|
||||
open={addDialogOpen}
|
||||
onOpenChange={setAddDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setAddDialogOpen(open);
|
||||
if (!open) {
|
||||
// Reset force manual entry when dialog closes
|
||||
setForceManualEntry(false);
|
||||
}
|
||||
}}
|
||||
preset={selectedPreset}
|
||||
isLoggedIntoNostr={!!user}
|
||||
oauthHook={selectedPreset.id === 'openrouter' ? openRouterOAuth : null}
|
||||
forceManualEntry={forceManualEntry}
|
||||
onSetForceManualEntry={setForceManualEntry}
|
||||
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
|
||||
/>
|
||||
)}
|
||||
|
||||
+75
-359
@@ -1,32 +1,19 @@
|
||||
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal, Search } from 'lucide-react';
|
||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useUserRepositories } from '@/hooks/useUserRepositories';
|
||||
import { useContacts } from '@/hooks/useContacts';
|
||||
import { useFollowedRepositories } from '@/hooks/useFollowedRepositories';
|
||||
import { RepositoryCard } from '@/components/RepositoryCard';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { NSchema as n } from '@nostrify/nostrify';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { detectFork } from '@/lib/detectFork';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
|
||||
export default function Clone() {
|
||||
const { t } = useTranslation();
|
||||
@@ -41,46 +28,6 @@ export default function Clone() {
|
||||
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||
const { user } = useCurrentUser();
|
||||
const { settings: gitSettings } = useGitSettings();
|
||||
const { data: repositories = [], isLoading: isLoadingRepos } = useUserRepositories(user?.pubkey);
|
||||
const { data: contacts = [] } = useContacts(user?.pubkey);
|
||||
const { data: followedRepositories = [], isLoading: isLoadingFollowedRepos } = useFollowedRepositories(contacts);
|
||||
const [activeTab, setActiveTab] = useState<'my-projects' | 'follows'>('my-projects');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
// Get unique pubkeys from all repositories
|
||||
const allRepos = useMemo(() => [...repositories, ...followedRepositories], [repositories, followedRepositories]);
|
||||
const uniquePubkeys = useMemo(() => {
|
||||
const pubkeys = new Set<string>();
|
||||
allRepos.forEach(repo => pubkeys.add(repo.pubkey));
|
||||
return Array.from(pubkeys);
|
||||
}, [allRepos]);
|
||||
|
||||
// Fetch author metadata for all unique pubkeys
|
||||
const { nostr } = useNostr();
|
||||
const { data: authorMetadataMap = new Map<string, NostrMetadata>() } = useQuery({
|
||||
queryKey: ['repository-authors', uniquePubkeys.sort().join(',')],
|
||||
queryFn: async () => {
|
||||
if (uniquePubkeys.length === 0) return new Map<string, NostrMetadata>();
|
||||
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [0], authors: uniquePubkeys, limit: uniquePubkeys.length }],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const metadataMap = new Map<string, NostrMetadata>();
|
||||
for (const event of events) {
|
||||
try {
|
||||
const metadata = n.json().pipe(n.metadata()).parse(event.content);
|
||||
metadataMap.set(event.pubkey, metadata);
|
||||
} catch {
|
||||
// If parsing fails, continue without metadata for this pubkey
|
||||
}
|
||||
}
|
||||
return metadataMap;
|
||||
},
|
||||
enabled: uniquePubkeys.length > 0,
|
||||
staleTime: 60000, // 1 minute
|
||||
});
|
||||
|
||||
useSeoMeta({
|
||||
title: `${t('importRepository')} - Shakespeare`,
|
||||
@@ -256,140 +203,83 @@ export default function Clone() {
|
||||
}
|
||||
};
|
||||
|
||||
// Filter repositories based on search query
|
||||
const filterRepositories = useCallback((repos: Repository[], query: string): Repository[] => {
|
||||
if (!query.trim()) {
|
||||
return repos;
|
||||
}
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
|
||||
return repos.filter((repo) => {
|
||||
// Filter by repository name
|
||||
if (repo.name.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by description
|
||||
if (repo.description?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by tags (hashtags)
|
||||
if (repo.repoTags.some(tag => tag.toLowerCase().includes(lowerQuery))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by hex pubkey
|
||||
if (repo.pubkey.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by npub (bech32 encoded pubkey)
|
||||
try {
|
||||
const npub = nip19.npubEncode(repo.pubkey);
|
||||
if (npub.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// If encoding fails, skip npub search
|
||||
}
|
||||
|
||||
// Filter by author name
|
||||
const authorMetadata = authorMetadataMap.get(repo.pubkey);
|
||||
if (authorMetadata?.name?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}, [authorMetadataMap]);
|
||||
|
||||
// Filtered repositories for "My Projects" tab
|
||||
const filteredMyRepositories = useMemo(() => {
|
||||
return filterRepositories(repositories, searchQuery);
|
||||
}, [repositories, searchQuery, filterRepositories]);
|
||||
|
||||
// Filtered repositories for "Follows" tab
|
||||
const filteredFollowedRepositories = useMemo(() => {
|
||||
return filterRepositories(followedRepositories, searchQuery);
|
||||
}, [followedRepositories, searchQuery, filterRepositories]);
|
||||
|
||||
return (
|
||||
<AppLayout title={t('importRepository')}>
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<div className="text-center mb-8">
|
||||
<div className="text-4xl mb-4">
|
||||
<GitBranch className="h-12 w-12 mx-auto text-primary" />
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold mb-3 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('importRepository')}
|
||||
</h1>
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{t('cloneGitRepository')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
id="repo-url"
|
||||
type="text"
|
||||
placeholder="https://github.com/username/repository.git"
|
||||
value={repoUrl}
|
||||
onChange={(e) => {
|
||||
setRepoUrl(e.target.value);
|
||||
setError(null); // Clear error when user types
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isCloning}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 p-3 bg-destructive/10 border border-destructive/20 rounded-md">
|
||||
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
<div className="min-h-[calc(100vh-12rem)] flex items-center justify-center">
|
||||
<div className="max-w-2xl mx-auto w-full">
|
||||
<div className="text-center mb-8">
|
||||
<div className="text-4xl mb-4">
|
||||
<GitBranch className="h-12 w-12 mx-auto text-primary" />
|
||||
</div>
|
||||
)}
|
||||
<h1 className="text-3xl font-bold mb-3 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('importRepository')}
|
||||
</h1>
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{t('cloneGitRepository')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() => handleClone()}
|
||||
disabled={!repoUrl.trim() || isCloning}
|
||||
className="w-full focus-ring bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg"
|
||||
size="lg"
|
||||
>
|
||||
{isCloning ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{t('cloningRepository')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="mr-2 h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</>
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
id="repo-url"
|
||||
type="text"
|
||||
placeholder="https://github.com/username/repository.git"
|
||||
value={repoUrl}
|
||||
onChange={(e) => {
|
||||
setRepoUrl(e.target.value);
|
||||
setError(null); // Clear error when user types
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isCloning}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 p-3 bg-destructive/10 border border-destructive/20 rounded-md">
|
||||
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Import ZIP File Link */}
|
||||
<div className="mt-8 text-center">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="text-muted-foreground hover:text-primary hover:bg-transparent">
|
||||
<MoreHorizontal className="h-5 w-5" />
|
||||
<span className="sr-only">More options</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center">
|
||||
<DropdownMenuItem
|
||||
className="flex items-center gap-2 w-full"
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button
|
||||
onClick={() => handleClone()}
|
||||
disabled={!repoUrl.trim() || isCloning}
|
||||
className="w-full focus-ring bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg"
|
||||
size="lg"
|
||||
>
|
||||
{isCloning ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{t('cloningRepository')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="mr-2 h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Import ZIP File Link */}
|
||||
<div className="mt-8 text-center">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="text-muted-foreground hover:text-primary hover:bg-transparent">
|
||||
<MoreHorizontal className="h-5 w-5" />
|
||||
<span className="sr-only">More options</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center">
|
||||
<DropdownMenuItem
|
||||
className="flex items-center gap-2 w-full"
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -399,180 +289,6 @@ export default function Clone() {
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
|
||||
{/* NIP-34 Repositories with Tabs */}
|
||||
{user && (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'my-projects' | 'follows')}>
|
||||
<div className="flex items-center gap-4 mb-6 flex-wrap">
|
||||
<TabsList>
|
||||
<TabsTrigger value="my-projects">
|
||||
My Projects
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="follows">
|
||||
Follows
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Search Input */}
|
||||
{(repositories.length > 0 || followedRepositories.length > 0) && (
|
||||
<div className="relative flex-1 min-w-[200px] max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search repositories..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9 h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TabsContent value="my-projects">
|
||||
{isLoadingRepos ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-9 flex-1" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : filteredMyRepositories.length > 0 ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredMyRepositories.map((repo) => (
|
||||
<RepositoryCard key={repo.id} repo={repo} />
|
||||
))}
|
||||
</div>
|
||||
) : searchQuery.trim() ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found matching "{searchQuery}".
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found. Publish your first repository to Nostr to see it here.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="follows">
|
||||
{isLoadingFollowedRepos ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-9 flex-1" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : filteredFollowedRepositories.length > 0 ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredFollowedRepositories.map((repo) => (
|
||||
<RepositoryCard key={repo.id} repo={repo} />
|
||||
))}
|
||||
</div>
|
||||
) : searchQuery.trim() ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found matching "{searchQuery}".
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : contacts.length > 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
None of the people you follow have published repositories yet.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
You're not following anyone yet. Follow people on Nostr to see their repositories here.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)}
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 { AddProviderDialog } from '@/components/AddProviderDialog';
|
||||
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||
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, buildServerUrl?: string) => {
|
||||
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string) => {
|
||||
// For Shakespeare, just check if user is logged in
|
||||
if (preset.requiresNostr && !user) {
|
||||
return;
|
||||
@@ -260,18 +260,6 @@ 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
|
||||
}
|
||||
@@ -290,8 +278,6 @@ export function DeploySettings() {
|
||||
|
||||
const handleRemoveProvider = (index: number) => {
|
||||
removeProvider(index);
|
||||
setDialogOpen(false);
|
||||
setSelectedProviderIndex(null);
|
||||
};
|
||||
|
||||
const handleUpdateProvider = (index: number, provider: DeployProvider) => {
|
||||
@@ -398,7 +384,7 @@ export function DeploySettings() {
|
||||
|
||||
{/* Add Preset Provider Dialog */}
|
||||
{selectedPreset && (
|
||||
<AddProviderDialog
|
||||
<AddDeployProviderDialog
|
||||
open={addDialogOpen}
|
||||
onOpenChange={setAddDialogOpen}
|
||||
preset={selectedPreset}
|
||||
@@ -411,8 +397,8 @@ export function DeploySettings() {
|
||||
onSetForceManualEntry={(force) =>
|
||||
setForceManualEntry(prev => ({ ...prev, [selectedPreset.id]: force }))
|
||||
}
|
||||
onAdd={(apiKey, accountId, organizationId, buildServerUrl) =>
|
||||
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId, buildServerUrl)
|
||||
onAdd={(apiKey, accountId, organizationId) =>
|
||||
handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
import { useState, useMemo, useDeferredValue } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Search, Compass } from 'lucide-react';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useUserRepositories } from '@/hooks/useUserRepositories';
|
||||
import { useContacts } from '@/hooks/useContacts';
|
||||
import { useFollowedRepositories } from '@/hooks/useFollowedRepositories';
|
||||
import { RepositoryCard } from '@/components/RepositoryCard';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { NSchema as n } from '@nostrify/nostrify';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
|
||||
export default function Explore() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { data: repositories = [], isLoading: isLoadingRepos } = useUserRepositories(user?.pubkey);
|
||||
const { data: contacts = [] } = useContacts(user?.pubkey);
|
||||
const { data: followedRepositories = [], isLoading: isLoadingFollowedRepos } = useFollowedRepositories(contacts);
|
||||
const [activeTab, setActiveTab] = useState<'my-projects' | 'follows'>('follows');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
// Defer search query to prevent blocking UI on every keystroke
|
||||
const deferredSearchQuery = useDeferredValue(searchQuery);
|
||||
|
||||
// Get unique pubkeys from all repositories
|
||||
const allRepos = useMemo(() => [...repositories, ...followedRepositories], [repositories, followedRepositories]);
|
||||
const uniquePubkeys = useMemo(() => {
|
||||
const pubkeys = new Set<string>();
|
||||
allRepos.forEach(repo => pubkeys.add(repo.pubkey));
|
||||
return Array.from(pubkeys);
|
||||
}, [allRepos]);
|
||||
|
||||
// Pre-compute npubs once to avoid expensive encoding on every search
|
||||
const npubMap = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
allRepos.forEach(repo => {
|
||||
if (!map.has(repo.pubkey)) {
|
||||
try {
|
||||
map.set(repo.pubkey, nip19.npubEncode(repo.pubkey));
|
||||
} catch {
|
||||
// ignore encoding failures
|
||||
}
|
||||
}
|
||||
});
|
||||
return map;
|
||||
}, [allRepos]);
|
||||
|
||||
// Fetch author metadata for all unique pubkeys
|
||||
const { nostr } = useNostr();
|
||||
const { data: authorMetadataMap = new Map<string, NostrMetadata>() } = useQuery({
|
||||
queryKey: ['repository-authors', uniquePubkeys],
|
||||
queryFn: async () => {
|
||||
if (uniquePubkeys.length === 0) return new Map<string, NostrMetadata>();
|
||||
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [0], authors: uniquePubkeys, limit: uniquePubkeys.length }],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const metadataMap = new Map<string, NostrMetadata>();
|
||||
for (const event of events) {
|
||||
try {
|
||||
const metadata = n.json().pipe(n.metadata()).parse(event.content);
|
||||
metadataMap.set(event.pubkey, metadata);
|
||||
} catch {
|
||||
// If parsing fails, continue without metadata for this pubkey
|
||||
}
|
||||
}
|
||||
return metadataMap;
|
||||
},
|
||||
enabled: uniquePubkeys.length > 0,
|
||||
staleTime: 60000, // 1 minute
|
||||
});
|
||||
|
||||
useSeoMeta({
|
||||
title: `${t('explore')} - Shakespeare`,
|
||||
description: t('exploreRepositories'),
|
||||
});
|
||||
|
||||
// Filter repositories based on search query - stable function with no dependencies
|
||||
const filterRepositories = (
|
||||
repos: Repository[],
|
||||
query: string,
|
||||
metadata: Map<string, NostrMetadata>,
|
||||
npubs: Map<string, string>
|
||||
): Repository[] => {
|
||||
if (!query.trim()) {
|
||||
return repos;
|
||||
}
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
|
||||
return repos.filter((repo) => {
|
||||
// Filter by repository name
|
||||
if (repo.name.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by description
|
||||
if (repo.description?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by tags (hashtags)
|
||||
if (repo.repoTags.some(tag => tag.toLowerCase().includes(lowerQuery))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by hex pubkey
|
||||
if (repo.pubkey.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by npub (pre-computed)
|
||||
const npub = npubs.get(repo.pubkey);
|
||||
if (npub?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by author name
|
||||
const authorMetadata = metadata.get(repo.pubkey);
|
||||
if (authorMetadata?.name?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
// Filtered repositories for "My Projects" tab - uses deferred query
|
||||
const filteredMyRepositories = useMemo(() => {
|
||||
return filterRepositories(repositories, deferredSearchQuery, authorMetadataMap, npubMap);
|
||||
}, [repositories, deferredSearchQuery, authorMetadataMap, npubMap]);
|
||||
|
||||
// Filtered repositories for "Follows" tab - uses deferred query
|
||||
const filteredFollowedRepositories = useMemo(() => {
|
||||
return filterRepositories(followedRepositories, deferredSearchQuery, authorMetadataMap, npubMap);
|
||||
}, [followedRepositories, deferredSearchQuery, authorMetadataMap, npubMap]);
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<AppLayout title={t('exploreApps')}>
|
||||
<div className="max-w-2xl mx-auto text-center py-12">
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{t('pleaseLogInToExplore')}
|
||||
</p>
|
||||
</div>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppLayout title={t('exploreApps')}>
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<Compass className="h-8 w-8 text-primary flex-shrink-0" />
|
||||
<h1 className="text-3xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('exploreApps')}
|
||||
</h1>
|
||||
</div>
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{t('exploreRepositories')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'my-projects' | 'follows')}>
|
||||
<div className="flex items-center gap-4 mb-6 flex-wrap">
|
||||
<TabsList>
|
||||
<TabsTrigger value="my-projects">
|
||||
My Projects
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="follows">
|
||||
Follows
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Search Input */}
|
||||
{(repositories.length > 0 || followedRepositories.length > 0) && (
|
||||
<div className="relative flex-1 min-w-[200px] max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search repositories..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9 h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TabsContent value="my-projects">
|
||||
{isLoadingRepos ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-9 flex-1" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : filteredMyRepositories.length > 0 ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredMyRepositories.map((repo) => (
|
||||
<RepositoryCard
|
||||
key={repo.id}
|
||||
repo={repo}
|
||||
authorMetadata={authorMetadataMap.get(repo.pubkey)}
|
||||
onTagClick={(tag) => setSearchQuery(tag)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : searchQuery.trim() ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found matching "{searchQuery}".
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found. Publish your first repository to Nostr to see it here.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="follows">
|
||||
{isLoadingFollowedRepos ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-9 flex-1" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : filteredFollowedRepositories.length > 0 ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredFollowedRepositories.map((repo) => (
|
||||
<RepositoryCard
|
||||
key={repo.id}
|
||||
repo={repo}
|
||||
authorMetadata={authorMetadataMap.get(repo.pubkey)}
|
||||
onTagClick={(tag) => setSearchQuery(tag)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : searchQuery.trim() ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found matching "{searchQuery}".
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : contacts.length > 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
None of the people you follow have published repositories yet.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
You're not following anyone yet. Follow people on Nostr to see their repositories here.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Bot } from 'lucide-react';
|
||||
|
||||
export default function OpenRouterOAuth() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const { handleCallback } = useOpenRouterOAuth();
|
||||
const { isLoading: isSettingsLoading } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
// Wait for AI settings to be initialized
|
||||
if (isSettingsLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
const error = searchParams.get('error');
|
||||
const errorDescription = searchParams.get('error_description');
|
||||
const storedCodeVerifier = localStorage.getItem('openrouter_oauth_code_verifier');
|
||||
|
||||
// Handle OAuth errors
|
||||
if (error) {
|
||||
toast({
|
||||
title: "OpenRouter OAuth Error",
|
||||
description: errorDescription || error,
|
||||
variant: "destructive",
|
||||
});
|
||||
navigate('/settings/ai');
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle successful OAuth callback
|
||||
if (code && storedCodeVerifier) {
|
||||
handleCallback(code, state || '').then((success) => {
|
||||
if (success) {
|
||||
toast({
|
||||
title: "OpenRouter Connected",
|
||||
description: "Successfully connected to OpenRouter. You can now use OpenRouter models.",
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Connection Failed",
|
||||
description: "Failed to connect to OpenRouter. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
// Always redirect to AI settings after handling the callback
|
||||
navigate('/settings/ai');
|
||||
});
|
||||
} else if (code && !storedCodeVerifier) {
|
||||
// Missing code verifier - likely an incomplete PKCE flow
|
||||
toast({
|
||||
title: "Authentication Error",
|
||||
description: "OAuth flow is incomplete. Please try connecting to OpenRouter again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
// Clean up any remaining OAuth data
|
||||
localStorage.removeItem('openrouter_oauth_state');
|
||||
localStorage.removeItem('openrouter_oauth_code_verifier');
|
||||
navigate('/settings/ai');
|
||||
} else {
|
||||
// No code parameter - redirect to AI settings
|
||||
navigate('/settings/ai');
|
||||
}
|
||||
}, [searchParams, handleCallback, toast, navigate, isSettingsLoading]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-center">
|
||||
<Bot className="h-12 w-12 text-primary" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold">Connecting to OpenRouter</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Processing your OpenRouter authentication...
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-center">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -257,6 +257,7 @@ export function SystemSettings() {
|
||||
icon={Settings}
|
||||
titleKey="systemSettings"
|
||||
descriptionKey="systemSettingsDescription"
|
||||
className="space-y-2"
|
||||
>
|
||||
{/* Service Worker Configuration */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
@@ -767,7 +768,7 @@ export function SystemSettings() {
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 py-1">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
|
||||
@@ -804,9 +805,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('projectsDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
@@ -845,9 +843,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('configDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
@@ -886,9 +881,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('temporaryDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
@@ -927,9 +919,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('pluginsDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
@@ -968,9 +957,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('templatesDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
|
||||
|
||||
export function WalletSettings() {
|
||||
const { t } = useTranslation();
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [connectionUri, setConnectionUri] = useState('');
|
||||
const [alias, setAlias] = useState('');
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
const {
|
||||
connections,
|
||||
activeConnection,
|
||||
connectionInfo,
|
||||
addConnection,
|
||||
removeConnection,
|
||||
setActiveConnection
|
||||
} = useNWC();
|
||||
|
||||
const { webln } = useWallet();
|
||||
|
||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
||||
|
||||
const handleAddConnection = async () => {
|
||||
if (!connectionUri.trim()) {
|
||||
toast({
|
||||
title: t('connectionUriRequired'),
|
||||
description: t('pleaseEnterValidNwcUri'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
|
||||
if (success) {
|
||||
setConnectionUri('');
|
||||
setAlias('');
|
||||
setAddDialogOpen(false);
|
||||
}
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveConnection = (connectionString: string) => {
|
||||
removeConnection(connectionString);
|
||||
};
|
||||
|
||||
const handleSetActive = (connectionString: string) => {
|
||||
setActiveConnection(connectionString);
|
||||
toast({
|
||||
title: t('activeWalletChanged'),
|
||||
description: t('selectedWalletNowActive'),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsPageLayout
|
||||
icon={Wallet}
|
||||
titleKey="walletSettings"
|
||||
descriptionKey="walletSettingsDescription"
|
||||
>
|
||||
{/* Current Status */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">{t('currentStatus')}</h3>
|
||||
<div className="grid gap-3">
|
||||
{/* WebLN */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">WebLN</p>
|
||||
<p className="text-xs text-muted-foreground">{t('browserExtension')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{webln && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={webln ? "default" : "secondary"} className="text-xs">
|
||||
{webln ? t('ready') : t('notFound')}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{/* NWC */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">{t('nostrWalletConnect')}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{connections.length > 0
|
||||
? t('walletsConnected', { count: connections.length })
|
||||
: t('remoteWalletConnection')
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
|
||||
{hasNWC ? t('ready') : t('none')}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* NWC Management */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-medium">{t('nostrWalletConnect')}</h3>
|
||||
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Connected Wallets List */}
|
||||
{connections.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground border border-dashed rounded-lg">
|
||||
<WalletMinimal className="h-8 w-8 mx-auto mb-2 opacity-50" />
|
||||
<p className="text-sm">{t('noWalletsConnected')}</p>
|
||||
<p className="text-xs mt-1">{t('addNwcWalletToGetStarted')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{connections.map((connection) => {
|
||||
const info = connectionInfo[connection.connectionString];
|
||||
const isActive = activeConnection === connection.connectionString;
|
||||
return (
|
||||
<div
|
||||
key={connection.connectionString}
|
||||
className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{connection.alias || info?.alias || t('lightningWallet')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('nwcConnection')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
{!isActive && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleSetActive(connection.connectionString)}
|
||||
title={t('setAsActive')}
|
||||
>
|
||||
<Zap className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleRemoveConnection(connection.connectionString)}
|
||||
title={t('remove')}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Help */}
|
||||
{!webln && connections.length === 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('installWeblnOrConnectNwc')}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Add Wallet Dialog */}
|
||||
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('connectNwcWallet')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('enterConnectionStringFromWallet')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div>
|
||||
<Label htmlFor="alias">{t('walletNameOptional')}</Label>
|
||||
<Input
|
||||
id="alias"
|
||||
placeholder={t('myLightningWallet')}
|
||||
value={alias}
|
||||
onChange={(e) => setAlias(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="connection-uri">{t('connectionUri')}</Label>
|
||||
<Textarea
|
||||
id="connection-uri"
|
||||
placeholder="nostr+walletconnect://..."
|
||||
value={connectionUri}
|
||||
onChange={(e) => setConnectionUri(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
onClick={handleAddConnection}
|
||||
disabled={isConnecting || !connectionUri.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isConnecting ? t('connecting') : t('connect')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</SettingsPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export default WalletSettings;
|
||||
Reference in new issue
Block a user