diff --git a/.github/workflows/production.yml b/.github/workflows/production.yml index 216f75b5c..71d7dc298 100644 --- a/.github/workflows/production.yml +++ b/.github/workflows/production.yml @@ -11,8 +11,10 @@ concurrency: env: ENVIRONMENT: production + PROJECT: cloud + APPLICATION: cloud DECLARATIVE_OWNER: appwrite-labs - DECLARATIVE_REPOSITORY: cloud-applications + DECLARATIVE_REPOSITORY: application-configuration DECLARATIVE_ALIAS: cloud-console IMAGE_NAME: appwrite/console-cloud TAG: ${{ github.event.release.tag_name || github.sha }} @@ -54,7 +56,7 @@ jobs: needs: build runs-on: ubuntu-latest # Shared across the staging and production workflows so their deploy - # jobs never push to cloud-applications at the same time. + # jobs never push to application-configuration at the same time. concurrency: group: declarative-deploy cancel-in-progress: false @@ -77,7 +79,7 @@ jobs: persist-credentials: false - name: Update image tag - run: yq -i '.[strenv(DECLARATIVE_ALIAS)].image.tag = strenv(TAG)' ${{ env.ENVIRONMENT }}/cloud/default.yaml + run: yq -i '.[strenv(DECLARATIVE_ALIAS)].image.tag = strenv(TAG)' ${{ env.PROJECT }}/${{ env.ENVIRONMENT }}/${{ env.APPLICATION }}/default.yaml - name: Open pull request # The release author reviews; falls back to the dispatcher for @@ -90,7 +92,7 @@ jobs: run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" - git add ${{ env.ENVIRONMENT }}/cloud/default.yaml + git add ${{ env.PROJECT }}/${{ env.ENVIRONMENT }}/${{ env.APPLICATION }}/default.yaml if git diff --cached --quiet; then echo "No changes to commit" exit 0 diff --git a/.github/workflows/staging.yml b/.github/workflows/staging.yml index 5ba4e204b..b7dc185d1 100644 --- a/.github/workflows/staging.yml +++ b/.github/workflows/staging.yml @@ -12,8 +12,10 @@ concurrency: env: ENVIRONMENT: staging + PROJECT: cloud + APPLICATION: cloud DECLARATIVE_OWNER: appwrite-labs - DECLARATIVE_REPOSITORY: cloud-applications + DECLARATIVE_REPOSITORY: application-configuration DECLARATIVE_ALIAS: cloud-console IMAGE_NAME: appwrite/console-cloud-stage TAG: ${{ github.sha }} @@ -54,7 +56,7 @@ jobs: needs: build runs-on: ubuntu-latest # Shared across the staging and production workflows so their deploy - # jobs never push to cloud-applications at the same time. + # jobs never push to application-configuration at the same time. concurrency: group: declarative-deploy cancel-in-progress: false @@ -77,7 +79,7 @@ jobs: persist-credentials: false - name: Update image tag - run: yq -i '.[strenv(DECLARATIVE_ALIAS)].image.tag = strenv(TAG)' ${{ env.ENVIRONMENT }}/cloud/default.yaml + run: yq -i '.[strenv(DECLARATIVE_ALIAS)].image.tag = strenv(TAG)' ${{ env.PROJECT }}/${{ env.ENVIRONMENT }}/${{ env.APPLICATION }}/default.yaml - name: Commit and push env: @@ -85,7 +87,7 @@ jobs: run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" - git add ${{ env.ENVIRONMENT }}/cloud/default.yaml + git add ${{ env.PROJECT }}/${{ env.ENVIRONMENT }}/${{ env.APPLICATION }}/default.yaml if git diff --cached --quiet; then echo "No changes to commit" else diff --git a/bun.lock b/bun.lock index f028a4c20..798c00a88 100644 --- a/bun.lock +++ b/bun.lock @@ -37,11 +37,10 @@ "flatted": "^3.4.2", "ignore": "^6.0.2", "json5": "^2.2.3", - "nanoid": "^5.1.11", + "nanoid": "^3.3.18", "nanotar": "^0.3.0", "pretty-bytes": "^6.1.1", "remarkable": "^2.0.1", - "svelte-confetti": "^1.4.0", "three": "^0.181.2", "tippy.js": "^6.3.7", }, @@ -95,8 +94,9 @@ "devalue": "^5.8.1", "flatted": "^3.4.2", "immutable": "^5.1.8", - "js-yaml": "^4.3.0", + "js-yaml": "^4.3.1", "minimatch": "10.2.3", + "nanoid": "^3.3.18", "picomatch": "^4.0.4", "postcss": "^8.5.18", "vite": "npm:rolldown-vite@latest", @@ -1024,7 +1024,7 @@ "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], - "js-yaml": ["js-yaml@4.3.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q=="], + "js-yaml": ["js-yaml@4.3.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ=="], "jsdom": ["jsdom@26.1.0", "", { "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", "decimal.js": "^10.5.0", "html-encoding-sniffer": "^4.0.0", "http-proxy-agent": "^7.0.2", "https-proxy-agent": "^7.0.6", "is-potential-custom-element-name": "^1.0.1", "nwsapi": "^2.2.16", "parse5": "^7.2.1", "rrweb-cssom": "^0.8.0", "saxes": "^6.0.0", "symbol-tree": "^3.2.4", "tough-cookie": "^5.1.1", "w3c-xmlserializer": "^5.0.0", "webidl-conversions": "^7.0.0", "whatwg-encoding": "^3.1.1", "whatwg-mimetype": "^4.0.0", "whatwg-url": "^14.1.1", "ws": "^8.18.0", "xml-name-validator": "^5.0.0" }, "peerDependencies": { "canvas": "^3.0.0" }, "optionalPeers": ["canvas"] }, "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg=="], @@ -1128,7 +1128,7 @@ "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "nanoid": ["nanoid@5.1.11", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg=="], + "nanoid": ["nanoid@3.3.18", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="], "nanotar": ["nanotar@0.3.0", "", {}, "sha512-Kv2JYYiCzt16Kt5QwAc9BFG89xfPNBx+oQL4GQXD9nLqPkZBiNaqaCWtwnbk/q7UVsTYevvM1b0UF8zmEI4pCg=="], @@ -1338,8 +1338,6 @@ "svelte-check": ["svelte-check@4.5.0", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.25", "chokidar": "^4.0.1", "fdir": "^6.2.0", "picocolors": "^1.0.0", "sade": "^1.7.4" }, "peerDependencies": { "svelte": "^4.0.0 || ^5.0.0-next.0", "typescript": ">=5.0.0" }, "bin": { "svelte-check": "bin/svelte-check" } }, "sha512-9lNwPxCLWniFvQIcEv1LFqjIxcFtO3smb5+5BKbRJ3ttL4o2lXCej5rLF4DAnfLPI66oaA81vAxw6ILdIWI7kA=="], - "svelte-confetti": ["svelte-confetti@1.4.0", "", { "peerDependencies": { "svelte": "^4.0.0" } }, "sha512-B0woNwpsFGwhkEoP48BIDQgvW0bMxPhavLVD+E+tsTWevlpr1aiz1S2wA8ArIXX957BiaZWHRHKmI5/pFRDbdg=="], - "svelte-eslint-parser": ["svelte-eslint-parser@1.7.1", "", { "dependencies": { "eslint-scope": "^8.2.0", "eslint-visitor-keys": "^4.0.0", "espree": "^10.0.0", "postcss": "^8.4.49", "postcss-scss": "^4.0.9", "postcss-selector-parser": "^7.0.0", "semver": "^7.7.2" }, "peerDependencies": { "svelte": "^3.37.0 || ^4.0.0 || ^5.0.0" }, "optionalPeers": ["svelte"] }, "sha512-mmwwKL9L/MB0QyBKdfyWxGjDuQfEyzxWy5S9Kkd0O/V5XD57MQ33KQtXrO6vKLuP6PIt8CRozvOX1mxpcRTqUg=="], "svelte-motion": ["svelte-motion@0.12.2", "", { "dependencies": { "@types/react": "^18.2.42", "framesync": "^6.1.2", "popmotion": "^11.0.5", "style-value-types": "5.1.2", "tslib": "^2.6.2" }, "peerDependencies": { "svelte": ">=3.35.0 || ^4.0.0 || ^5.0.0 || ^5.0.0-next.0" } }, "sha512-7RrdRz9iVP55B9HT/C0hYW3pyrKlF61kAby/AkDtOAP0uHFQDrfd0qQetDC81cEsK9b40jt+jfcqSAXcA7LPEw=="], @@ -1500,8 +1498,6 @@ "@ai-sdk/provider-utils/@ai-sdk/provider": ["@ai-sdk/provider@1.0.11", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-CPyImHGiT3svyfmvPvAFTianZzWFtm0qK82XjwlQIA1C3IQ2iku/PMQXi7aFyrX0TyMh3VTkJPB03tjU2VXVrw=="], - "@ai-sdk/provider-utils/nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], - "@ai-sdk/ui-utils/@ai-sdk/provider": ["@ai-sdk/provider@1.0.11", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-CPyImHGiT3svyfmvPvAFTianZzWFtm0qK82XjwlQIA1C3IQ2iku/PMQXi7aFyrX0TyMh3VTkJPB03tjU2VXVrw=="], "@appwrite.io/pink-legacy/@appwrite.io/pink-icons": ["@appwrite.io/pink-icons@1.0.0", "", {}, "sha512-+zpksP07MvOYwhx9AZDFW0pxXQNC2juKwyOQVRAwAOkN1ACSQKPlyytkI1u2ci6CQPWjJe20CzbvBBuRNXOKjA=="], @@ -1524,8 +1520,6 @@ "@eslint/eslintrc/ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], - "@melt-ui/svelte/nanoid": ["nanoid@5.1.7", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-ua3NDgISf6jdwezAheMOk4mbE1LXjm1DfMUDMuJf4AqxLFK3ccGpgWizwa5YV7Yz9EpXwEaWoRXSb/BnV0t5dQ=="], - "@opentelemetry/core/@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.28.0", "", {}, "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA=="], "@opentelemetry/instrumentation-http/@opentelemetry/instrumentation": ["@opentelemetry/instrumentation@0.57.1", "", { "dependencies": { "@opentelemetry/api-logs": "0.57.1", "@types/shimmer": "^1.2.0", "import-in-the-middle": "^1.8.1", "require-in-the-middle": "^7.1.1", "semver": "^7.5.2", "shimmer": "^1.2.1" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-SgHEKXoVxOjc20ZYusPG3Fh+RLIZTSa4x8QtD3NfgAUDyqdFFS9W1F2ZVbZkqDCdyMcQG02Ok4duUGLHJXHgbA=="], @@ -1574,8 +1568,6 @@ "popmotion/tslib": ["tslib@2.4.0", "", {}, "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ=="], - "postcss/nanoid": ["nanoid@3.3.16", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="], - "style-value-types/tslib": ["tslib@2.4.0", "", {}, "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ=="], "svelte/aria-query": ["aria-query@5.3.1", "", {}, "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g=="], diff --git a/package.json b/package.json index f7ffc2352..fd0ebc590 100644 --- a/package.json +++ b/package.json @@ -51,11 +51,10 @@ "flatted": "^3.4.2", "ignore": "^6.0.2", "json5": "^2.2.3", - "nanoid": "^5.1.11", + "nanoid": "^3.3.18", "nanotar": "^0.3.0", "pretty-bytes": "^6.1.1", "remarkable": "^2.0.1", - "svelte-confetti": "^1.4.0", "three": "^0.181.2", "tippy.js": "^6.3.7" }, @@ -105,7 +104,7 @@ "vite": "npm:rolldown-vite@latest", "minimatch": "10.2.3", "brace-expansion": ">=5.0.9", - "js-yaml": "^4.3.0", + "js-yaml": "^4.3.1", "immutable": "^5.1.8", "flatted": "^3.4.2", "devalue": "^5.8.1", @@ -113,6 +112,7 @@ "picomatch": "^4.0.4", "cookie": "^0.7.0", "ws": "^8.21.0", - "postcss": "^8.5.18" + "postcss": "^8.5.18", + "nanoid": "^3.3.18" } } diff --git a/src/lib/components/variables/createVariableModal.svelte b/src/lib/components/variables/createVariableModal.svelte index 06b73ea54..5ba5ef4c6 100644 --- a/src/lib/components/variables/createVariableModal.svelte +++ b/src/lib/components/variables/createVariableModal.svelte @@ -8,6 +8,7 @@ import { Link } from '$lib/elements'; import { page } from '$app/state'; import { IconPlus, IconX } from '@appwrite.io/pink-icons-svelte'; + import { validateVariables } from '$lib/helpers/variables'; export type ProductLabel = 'site' | 'function'; @@ -39,13 +40,13 @@ newVariables = newVariables.map((variable) => ({ ...variable, secret: true })); } - newVariables.forEach((variable) => { - if (('' + variable.value).length > 8192) { - throw new Error( - `Variable ${variable.key} is longer than 8192 allowed characters` - ); - } - }); + const validationError = validateVariables( + newVariables.filter((variable) => variable.key || variable.value) + ); + if (validationError) { + throw new Error(validationError); + } + const updatedVariables = [...variables]; newVariables.forEach((newVar) => { if (!newVar.key) { diff --git a/src/lib/components/variables/environmentVariables.svelte b/src/lib/components/variables/environmentVariables.svelte index 595cc08ac..88dddf301 100644 --- a/src/lib/components/variables/environmentVariables.svelte +++ b/src/lib/components/variables/environmentVariables.svelte @@ -22,6 +22,7 @@ import UpdateVariableModal from './updateVariableModal.svelte'; import { Click, trackEvent } from '$lib/actions/analytics'; import { isSmallViewport } from '$lib/stores/viewport'; + import { isValidVariableKey } from '$lib/helpers/variables'; const DOCS_LINKS: Record = { site: 'https://appwrite.io/docs/products/sites/develop#accessing-environment-variables', @@ -146,7 +147,28 @@ {#each paginatedItems as variable} - {variable.key} + + + {#if !isValidVariableKey(variable.key)} + + + + This key can't be used as an environment + variable name. Rename it using only letters, + digits and underscores, without starting + with a digit. + + + {/if} + {variable.key} + +
diff --git a/src/lib/components/variables/importVariablesModal.svelte b/src/lib/components/variables/importVariablesModal.svelte index 9f0b782d1..9eed108b2 100644 --- a/src/lib/components/variables/importVariablesModal.svelte +++ b/src/lib/components/variables/importVariablesModal.svelte @@ -7,6 +7,7 @@ import { Icon, Layout, Selector, Tooltip, Typography, Upload } from '@appwrite.io/pink-svelte'; import { parse } from '$lib/helpers/envfile'; import { removeFile } from '$lib/helpers/files'; + import { validateVariables } from '$lib/helpers/variables'; export let show = false; export let variables: Partial[]; @@ -35,19 +36,20 @@ if (!Object.keys(uploaded).length) { throw new Error('No variables found'); } - const entries = Object.entries(uploaded); + // Drop the valueless entries first. They are never written, so an + // invalid key on one of them must not reject the whole file. + const entries = Object.entries(uploaded).filter(([, value]) => !!value); - for (const [key, value] of entries) { - if (value.length > 8192) { - throw new Error(`Variable ${key} is longer than 8192 allowed characters`); - } + const validationError = validateVariables( + entries.map(([key, value]) => ({ key, value })) + ); + if (validationError) { + throw new Error(validationError); } - entries - .filter(([, value]) => !!value) - .forEach(([key, value]) => { - variables.push({ key, value, secret }); - }); + entries.forEach(([key, value]) => { + variables.push({ key, value, secret }); + }); show = false; } catch (e) { diff --git a/src/lib/components/variables/updateVariableModal.svelte b/src/lib/components/variables/updateVariableModal.svelte index 7d02391fa..005ec89ba 100644 --- a/src/lib/components/variables/updateVariableModal.svelte +++ b/src/lib/components/variables/updateVariableModal.svelte @@ -7,6 +7,7 @@ import { Layout, Selector } from '@appwrite.io/pink-svelte'; import { Link } from '$lib/elements'; import { page } from '$app/state'; + import { validateVariables } from '$lib/helpers/variables'; export let show = false; export let selectedVar: Partial; @@ -20,7 +21,15 @@ secret: selectedVar?.secret }; + let error = ''; + function handleVariable() { + const validationError = validateVariables([pair]); + if (validationError) { + error = validationError; + return; + } + if (selectedVar) { variables = variables.map((variable) => { const match = selectedVar.$id @@ -39,7 +48,7 @@ } - + Update the environment variable for your {productLabel}. Global variables can be set in 8192) { - throw new Error(`Variable ${key} is longer than 8192 allowed characters`); - } + const validationError = validateVariables( + entries.map(([key, value]) => ({ key, value })) + ); + if (validationError) { + throw new Error(validationError); } // Update or remove editable variables diff --git a/src/lib/helpers/campaign.ts b/src/lib/helpers/campaign.ts new file mode 100644 index 000000000..1018d668f --- /dev/null +++ b/src/lib/helpers/campaign.ts @@ -0,0 +1,7 @@ +import { getApiEndpoint } from '$lib/stores/sdk'; + +export function getCampaignImageUrl(image: string) { + const endpoint = getApiEndpoint(); + const url = new URL(image, endpoint); + return url.toString(); +} diff --git a/src/lib/helpers/oauth2-app-logo.test.ts b/src/lib/helpers/oauth2-app-logo.test.ts new file mode 100644 index 000000000..1ab56b2c0 --- /dev/null +++ b/src/lib/helpers/oauth2-app-logo.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest'; +import { resolveOAuth2AppLogoUrl } from './oauth2-app-logo'; + +describe('resolveOAuth2AppLogoUrl', () => { + it('uses the square Appwrite icon for the first-party CLI client', () => { + expect( + resolveOAuth2AppLogoUrl({ + $id: 'appwrite-cli', + logoUri: 'https://example.com/wordmark.svg' + }) + ).toBe('/console/logos/appwrite-icon.svg'); + }); + + it('keeps third-party logoUri values', () => { + expect( + resolveOAuth2AppLogoUrl({ + $id: 'other-app', + logoUri: 'https://example.com/logo.png' + }) + ).toBe('https://example.com/logo.png'); + }); + + it('returns an empty string when no logo is available', () => { + expect(resolveOAuth2AppLogoUrl({ $id: 'other-app', logoUri: ' ' })).toBe(''); + expect(resolveOAuth2AppLogoUrl(null)).toBe(''); + }); +}); diff --git a/src/lib/helpers/oauth2-app-logo.ts b/src/lib/helpers/oauth2-app-logo.ts new file mode 100644 index 000000000..3235ec749 --- /dev/null +++ b/src/lib/helpers/oauth2-app-logo.ts @@ -0,0 +1,18 @@ +import { base } from '$app/paths'; + +/** + * First-party clients may register a wide wordmark as `logoUri`. Consent and + * outcome avatars are square, so `object-fit: cover` crops those marks into + * unreadable fragments (see #3159 for Appwrite CLI). Prefer the square icon. + */ +const FIRST_PARTY_ICON_CLIENTS = new Set(['appwrite-cli']); + +export function resolveOAuth2AppLogoUrl( + app: { $id?: string; logoUri?: string } | null | undefined +): string { + if (app?.$id && FIRST_PARTY_ICON_CLIENTS.has(app.$id)) { + return `${base}/logos/appwrite-icon.svg`; + } + + return app?.logoUri?.trim() ?? ''; +} diff --git a/src/lib/helpers/oauth2-cimd.test.ts b/src/lib/helpers/oauth2-cimd.test.ts new file mode 100644 index 000000000..fce9d1b2a --- /dev/null +++ b/src/lib/helpers/oauth2-cimd.test.ts @@ -0,0 +1,76 @@ +import { cimdDocumentToApp, isCimdClientId } from '$lib/helpers/oauth2-cimd'; +import { describe, expect, it } from 'vitest'; + +describe('isCimdClientId', () => { + it('accepts https URLs', () => { + expect(isCimdClientId('https://example.com/oauth/client-metadata.json')).toBe(true); + }); + + it('accepts http only for loopback', () => { + expect(isCimdClientId('http://localhost:3000/client.json')).toBe(true); + expect(isCimdClientId('http://127.0.0.1/client.json')).toBe(true); + expect(isCimdClientId('http://example.com/client.json')).toBe(false); + }); + + it('rejects plain app IDs and non-http schemes', () => { + expect(isCimdClientId('my-app_1.0')).toBe(false); + expect(isCimdClientId('64f1e2a9b3c4d5e6f7a8')).toBe(false); + expect(isCimdClientId('javascript:alert(1)')).toBe(false); + }); +}); + +describe('cimdDocumentToApp', () => { + const clientId = 'https://example.com/oauth/client-metadata.json'; + + it('maps RFC 7591 metadata onto the App model', () => { + const app = cimdDocumentToApp(clientId, { + client_id: clientId, + client_name: 'Example App', + client_uri: 'https://example.com', + logo_uri: 'https://example.com/logo.png', + policy_uri: 'https://example.com/privacy', + tos_uri: 'https://example.com/terms', + contacts: ['support@example.com'], + redirect_uris: ['https://example.com/callback'], + token_endpoint_auth_method: 'none', + grant_types: ['authorization_code', 'urn:ietf:params:oauth:grant-type:device_code'] + }); + + expect(app.$id).toBe(clientId); + expect(app.name).toBe('Example App'); + expect(app.clientUri).toBe('https://example.com'); + expect(app.logoUri).toBe('https://example.com/logo.png'); + expect(app.privacyPolicyUrl).toBe('https://example.com/privacy'); + expect(app.termsUrl).toBe('https://example.com/terms'); + expect(app.contacts).toEqual(['support@example.com']); + expect(app.redirectUris).toEqual(['https://example.com/callback']); + expect(app.type).toBe('public'); + expect(app.deviceFlow).toBe(true); + expect(app.enabled).toBe(true); + }); + + it('falls back to the hostname when client_name is missing', () => { + const app = cimdDocumentToApp(clientId, { client_id: clientId }); + expect(app.name).toBe('example.com'); + expect(app.deviceFlow).toBe(false); + }); + + it('rejects a document whose client_id does not match its URL', () => { + expect(() => + cimdDocumentToApp(clientId, { client_id: 'https://evil.example/other.json' }) + ).toThrow(); + expect(() => cimdDocumentToApp(clientId, 'not an object')).toThrow(); + }); + + it('drops unrenderable URI values', () => { + const app = cimdDocumentToApp(clientId, { + client_id: clientId, + logo_uri: 'javascript:alert(1)', + client_uri: 'not a url', + contacts: ['ok', 42] + }); + expect(app.logoUri).toBe(''); + expect(app.clientUri).toBe(''); + expect(app.contacts).toEqual(['ok']); + }); +}); diff --git a/src/lib/helpers/oauth2-cimd.ts b/src/lib/helpers/oauth2-cimd.ts new file mode 100644 index 000000000..7d631f678 --- /dev/null +++ b/src/lib/helpers/oauth2-cimd.ts @@ -0,0 +1,108 @@ +import { sdk } from '$lib/stores/sdk'; +import type { Models } from '@appwrite.io/console'; + +// CIMD (Client ID Metadata Document): a client_id may be an HTTPS URL pointing +// to a JSON document of RFC 7591 client metadata. The Appwrite API no longer +// resolves these, so the console fetches the document itself for branding. + +const FETCH_TIMEOUT = 10_000; +const DEVICE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code'; +const HTTP_URL = /^https?:\/\//i; + +type CimdDocument = { + client_id?: unknown; + client_name?: unknown; + client_uri?: unknown; + logo_uri?: unknown; + policy_uri?: unknown; + tos_uri?: unknown; + contacts?: unknown; + redirect_uris?: unknown; + post_logout_redirect_uris?: unknown; + token_endpoint_auth_method?: unknown; + grant_types?: unknown; +}; + +// Plain app IDs never parse as URLs; http is allowed for local development only. +export function isCimdClientId(clientId: string): boolean { + try { + const url = new URL(clientId); + return ( + url.protocol === 'https:' || + (url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) + ); + } catch { + return false; + } +} + +export function cimdDocumentToApp(clientId: string, document: unknown): Models.App { + if (typeof document !== 'object' || document === null) { + throw new Error('CIMD document is not a JSON object'); + } + const doc = document as CimdDocument; + // The document's client_id must equal the URL it was fetched from. + if (doc.client_id !== clientId) { + throw new Error('CIMD document client_id does not match its URL'); + } + const name = typeof doc.client_name === 'string' ? doc.client_name.trim() : ''; + return { + $id: clientId, + $createdAt: '', + $updatedAt: '', + name: name || new URL(clientId).hostname, + description: '', + // Untrusted values rendered in href/src must be http(s) URLs. + clientUri: + typeof doc.client_uri === 'string' && HTTP_URL.test(doc.client_uri) + ? doc.client_uri + : '', + logoUri: + typeof doc.logo_uri === 'string' && HTTP_URL.test(doc.logo_uri) ? doc.logo_uri : '', + privacyPolicyUrl: + typeof doc.policy_uri === 'string' && HTTP_URL.test(doc.policy_uri) + ? doc.policy_uri + : '', + termsUrl: typeof doc.tos_uri === 'string' && HTTP_URL.test(doc.tos_uri) ? doc.tos_uri : '', + contacts: Array.isArray(doc.contacts) + ? doc.contacts.filter((contact) => typeof contact === 'string') + : [], + tagline: '', + tags: [], + images: [], + supportUrl: '', + dataDeletionUrl: '', + redirectUris: Array.isArray(doc.redirect_uris) + ? doc.redirect_uris.filter((uri) => typeof uri === 'string') + : [], + postLogoutRedirectUris: Array.isArray(doc.post_logout_redirect_uris) + ? doc.post_logout_redirect_uris.filter((uri) => typeof uri === 'string') + : [], + enabled: true, + type: doc.token_endpoint_auth_method === 'none' ? 'public' : 'confidential', + deviceFlow: Array.isArray(doc.grant_types) && doc.grant_types.includes(DEVICE_GRANT_TYPE), + teamId: '', + userId: '', + secrets: [] + }; +} + +// Plain IDs resolve via the API; CIMD URLs are fetched directly. Fetch or +// validation failures fall back to hostname-only branding rather than blocking +// the flow — the server still validates the client during authorization. +export async function getOAuth2App(appId: string): Promise { + if (!isCimdClientId(appId)) { + return sdk.forConsole.apps.get({ appId }); + } + try { + const response = await fetch(appId, { + headers: { accept: 'application/json' }, + credentials: 'omit', + signal: AbortSignal.timeout(FETCH_TIMEOUT) + }); + if (!response.ok) throw new Error(`CIMD document request failed: ${response.status}`); + return cimdDocumentToApp(appId, await response.json()); + } catch { + return cimdDocumentToApp(appId, { client_id: appId }); + } +} diff --git a/src/lib/helpers/variables.test.ts b/src/lib/helpers/variables.test.ts new file mode 100644 index 000000000..75f431a88 --- /dev/null +++ b/src/lib/helpers/variables.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from 'vitest'; +import { + getVariableKeyError, + isValidVariableKey, + validateVariables, + VARIABLE_KEY_MAX_LENGTH, + VARIABLE_VALUE_MAX_LENGTH +} from '$lib/helpers/variables'; + +test('accept keys that are valid environment variable names', () => { + expect(isValidVariableKey('APP_TEST')).toBe(true); + expect(isValidVariableKey('_PRIVATE')).toBe(true); + expect(isValidVariableKey('key1')).toBe(true); + expect(isValidVariableKey('a'.repeat(VARIABLE_KEY_MAX_LENGTH))).toBe(true); +}); + +test('reject keys that cannot be used as environment variable names', () => { + expect(isValidVariableKey('MY-KEY')).toBe(false); + expect(isValidVariableKey('MY.KEY')).toBe(false); + expect(isValidVariableKey('MY KEY')).toBe(false); + expect(isValidVariableKey('9KEY')).toBe(false); + expect(isValidVariableKey('KÉY')).toBe(false); + expect(isValidVariableKey('KEY\t')).toBe(false); + expect(isValidVariableKey('')).toBe(false); + expect(isValidVariableKey('a'.repeat(VARIABLE_KEY_MAX_LENGTH + 1))).toBe(false); +}); + +test('report a missing key separately from an invalid one', () => { + expect(getVariableKeyError('')).toEqual('Variable key is required'); + expect(getVariableKeyError('MY-KEY')).toContain('is invalid'); + expect(getVariableKeyError('a'.repeat(VARIABLE_KEY_MAX_LENGTH + 1))).toContain('longer than'); + expect(getVariableKeyError('APP_TEST')).toBeNull(); +}); + +test('validate a list of variables and name the offending key', () => { + expect(validateVariables([{ key: 'APP_TEST', value: 'value' }])).toBeNull(); + expect(validateVariables([{ key: 'APP_TEST', value: '' }])).toBeNull(); + + expect( + validateVariables([ + { key: 'APP_TEST', value: 'value' }, + { key: 'MY-KEY', value: 'value' } + ]) + ).toContain('MY-KEY'); + + expect( + validateVariables([{ key: 'APP_TEST', value: 'v'.repeat(VARIABLE_VALUE_MAX_LENGTH + 1) }]) + ).toContain('APP_TEST'); +}); diff --git a/src/lib/helpers/variables.ts b/src/lib/helpers/variables.ts index 90219499e..e93e25620 100644 --- a/src/lib/helpers/variables.ts +++ b/src/lib/helpers/variables.ts @@ -1,5 +1,71 @@ import type { Models } from '@appwrite.io/console'; +export const VARIABLE_KEY_MAX_LENGTH = 255; +export const VARIABLE_VALUE_MAX_LENGTH = 8192; + +/** + * Variable keys become environment variable names at build and runtime, so the + * API only accepts C-style identifiers. Keys stored before that rule existed + * can still fail this check, which is why `isValidVariableKey` is also used to + * flag them in the variables table. + */ +const VARIABLE_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; + +export function isValidVariableKey(key: string): boolean { + return ( + typeof key === 'string' && + key.length <= VARIABLE_KEY_MAX_LENGTH && + VARIABLE_KEY_PATTERN.test(key) + ); +} + +export function getVariableKeyError(key: string): string | null { + if (!key) { + return 'Variable key is required'; + } + + if (key.length > VARIABLE_KEY_MAX_LENGTH) { + return `Variable key "${key}" is longer than ${VARIABLE_KEY_MAX_LENGTH} allowed characters`; + } + + if (!VARIABLE_KEY_PATTERN.test(key)) { + return `Variable key "${key}" is invalid. Keys can only contain letters, digits and underscores, and cannot start with a digit`; + } + + return null; +} + +export function getVariableValueError(key: string, value: unknown): string | null { + if (('' + (value ?? '')).length > VARIABLE_VALUE_MAX_LENGTH) { + return `Variable ${key} is longer than ${VARIABLE_VALUE_MAX_LENGTH} allowed characters`; + } + + return null; +} + +/** + * Returns the first problem found, or null when every variable is accepted by + * the API. Call before submitting so a rejected key is reported against the + * file or row it came from instead of as a bare server error. + */ +export function validateVariables( + variables: Array<{ key?: string; value?: unknown }> +): string | null { + for (const { key, value } of variables) { + const keyError = getVariableKeyError(key); + if (keyError) { + return keyError; + } + + const valueError = getVariableValueError(key, value); + if (valueError) { + return valueError; + } + } + + return null; +} + export function normalizeDetectedVariables( detected: Models.DetectionVariable[] = [] ): Partial[] { diff --git a/src/lib/layout/unauthenticated.svelte b/src/lib/layout/unauthenticated.svelte index 27b44f624..d68dcfa86 100644 --- a/src/lib/layout/unauthenticated.svelte +++ b/src/lib/layout/unauthenticated.svelte @@ -7,7 +7,7 @@ import LoginLight from '$lib/images/login/login-light-mode.png'; import { app } from '$lib/stores/app'; import { Typography, Layout, Avatar } from '@appwrite.io/pink-svelte'; - import { getCampaignImageUrl } from '$routes/(public)/card/helpers'; + import { getCampaignImageUrl } from '$lib/helpers/campaign'; import { isSmallViewport } from '$lib/stores/viewport'; import type { Models } from '@appwrite.io/console'; diff --git a/src/lib/stores/sites.ts b/src/lib/stores/sites.ts index ef39511ee..29d811332 100644 --- a/src/lib/stores/sites.ts +++ b/src/lib/stores/sites.ts @@ -1,9 +1,3 @@ -import type { Models } from '@appwrite.io/console'; - -export type FrameworkAdapterWithStartCommand = Models.FrameworkAdapter & { - startCommand?: string; -}; - export function getFrameworkIcon(framework: string) { switch (true) { case framework.toLocaleLowerCase().includes('sveltekit'): diff --git a/src/lib/stores/windowFocus.ts b/src/lib/stores/windowFocus.ts deleted file mode 100644 index b0c28abca..000000000 --- a/src/lib/stores/windowFocus.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { readable, type Readable } from 'svelte/store'; - -function isCurrentWindowFocused(): boolean { - if (!window) return false; - if (!window.document) return false; - if (typeof window.document.hasFocus !== 'function') return false; - - return window.document.hasFocus(); -} - -export function windowFocusStore(): Readable { - const visibility = readable(isCurrentWindowFocused(), (set) => { - function handler() { - set(isCurrentWindowFocused()); - } - - if (window) { - window.addEventListener('focus', handler); - window.addEventListener('blur', handler); - - return () => { - window.removeEventListener('focus', handler); - window.removeEventListener('blur', handler); - }; - } - }); - - return visibility; -} diff --git a/src/routes/(console)/+layout.svelte b/src/routes/(console)/+layout.svelte index 139f1883d..b0f426798 100644 --- a/src/routes/(console)/+layout.svelte +++ b/src/routes/(console)/+layout.svelte @@ -331,7 +331,6 @@ { const connectedApps = await Promise.all( grants.map(async (identity) => { const appId = identity.provider.slice(OAUTH2_PREFIX.length); - const app = await sdk.forConsole.apps.get({ appId }).catch(() => null); + const app = await getOAuth2App(appId).catch(() => null); return { identity, appId, app }; }) ); diff --git a/src/routes/(console)/project-[region]-[project]/auth/user-[user]/updateStatus.svelte b/src/routes/(console)/project-[region]-[project]/auth/user-[user]/updateStatus.svelte index ffbd35e64..59a425cd9 100644 --- a/src/routes/(console)/project-[region]-[project]/auth/user-[user]/updateStatus.svelte +++ b/src/routes/(console)/project-[region]-[project]/auth/user-[user]/updateStatus.svelte @@ -52,7 +52,7 @@ await invalidate(Dependencies.USER); addNotification({ message: `${$user.name || $user.email || $user.phone || 'The account'} has been ${ - $user.phoneVerification ? 'unverified' : 'verified' + !$user.phoneVerification ? 'unverified' : 'verified' }`, type: 'success' }); diff --git a/src/routes/(console)/project-[region]-[project]/createVariableModal.svelte b/src/routes/(console)/project-[region]-[project]/createVariableModal.svelte index 2696db0fb..4136fcb18 100644 --- a/src/routes/(console)/project-[region]-[project]/createVariableModal.svelte +++ b/src/routes/(console)/project-[region]-[project]/createVariableModal.svelte @@ -9,12 +9,14 @@ import { Alert, Layout, Selector, Button as PinkButton, Icon } from '@appwrite.io/pink-svelte'; import { Link } from '$lib/elements'; import { IconPlus, IconX } from '@appwrite.io/pink-icons-svelte'; + import { validateVariables } from '$lib/helpers/variables'; export let isGlobal: boolean; export let product: 'function' | 'site' = 'function'; export let showCreate = false; let newVariables: Partial[] = [{ key: '', value: '' }]; let secret = false; + let error = ''; const dispatch = createEventDispatcher(); @@ -26,12 +28,16 @@ if (secret) { newVariables = newVariables.map((variable) => ({ ...variable, secret: true })); } - newVariables.forEach((variable) => { - if (('' + variable.value).length > 8192) { - throw new Error(`Variable ${variable.key} is longer than 8192 allowed characters`); - } - }); - dispatch('created', newVariables); + + const filled = newVariables.filter((variable) => variable.key || variable.value); + + const validationError = validateVariables(filled); + if (validationError) { + error = validationError; + return; + } + + dispatch('created', filled); close(); } @@ -48,6 +54,7 @@ diff --git a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/rows/columns/column.svelte b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/rows/columns/column.svelte index 37947fefe..1f385d75a 100644 --- a/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/rows/columns/column.svelte +++ b/src/routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/rows/columns/column.svelte @@ -88,7 +88,7 @@ {:else} ({ key: variable.name, value: variable.value })) + ); + if (validationError) { + throw new Error(validationError); + } + const rt = data.template.runtimes.find((r) => r.name === runtime); const func = await sdk diff --git a/src/routes/(console)/project-[region]-[project]/rawVariableEditor.svelte b/src/routes/(console)/project-[region]-[project]/rawVariableEditor.svelte index cdd889992..b1c3b79b2 100644 --- a/src/routes/(console)/project-[region]-[project]/rawVariableEditor.svelte +++ b/src/routes/(console)/project-[region]-[project]/rawVariableEditor.svelte @@ -6,6 +6,7 @@ import { addNotification } from '$lib/stores/notifications'; import type { Models } from '@appwrite.io/console'; import { parse } from '$lib/helpers/envfile'; + import { validateVariables } from '$lib/helpers/variables'; import { Icon, InlineCode, Layout, Tabs } from '@appwrite.io/pink-svelte'; import { InputTextarea } from '$lib/elements/forms'; import { @@ -35,7 +36,7 @@ ) => Promise; export let sdkUpdateVariable: ( variableId: string, - key: string, + key: string | undefined, value: string, secret?: boolean ) => Promise; @@ -74,10 +75,10 @@ } function validateEntries(entries: DraftVariable[]) { - for (const { key, value } of entries) { - if (value.length > 8192) { - throw new Error(`Variable ${key} is longer than 8192 allowed characters`); - } + const validationError = validateVariables(entries); + + if (validationError) { + throw new Error(validationError); } } @@ -146,22 +147,30 @@ const editableVariables = variableList.variables.filter((variable) => !variable.secret); const secretVariables = variableList.variables.filter((variable) => variable.secret); - await Promise.all( + const existingKeys = editableVariables.map((variable) => variable.key); + const existingResults = await Promise.allSettled( editableVariables.map(async (variable) => { const newValue = vars[variable.key] ?? null; + // Claim the key up front. A rejected write must not leave it + // behind for the second pass, which would retry it as a new + // variable and send the stored key along with it. + delete vars[variable.key]; + if (newValue === null) { await sdkDeleteVariable(variable.$id); } else if (newValue !== variable.value) { - await sdkUpdateVariable(variable.$id, variable.key, newValue, false); + // The key is unchanged here, so leave it out and let + // the API keep the stored one. + await sdkUpdateVariable(variable.$id, undefined, newValue, false); } - delete vars[variable.key]; }) ); // Add new variables, skipping keys that exist in secret variables - await Promise.all( - Object.keys(vars).map(async (key) => { + const newKeys = Object.keys(vars); + const newResults = await Promise.allSettled( + newKeys.map(async (key) => { const existingVariable = variableList.variables.find( (variable) => variable.key === key ); @@ -178,6 +187,22 @@ await sdkCreateVariable(key, vars[key], false); }) ); + + // Every variable is written on its own, so name the keys that + // failed rather than surfacing a single rejection. + const failed = [ + ...existingResults.map((result, index) => + result.status === 'rejected' ? existingKeys[index] : null + ), + ...newResults.map((result, index) => + result.status === 'rejected' ? newKeys[index] : null + ) + ].filter(Boolean); + + if (failed.length) { + throw new Error(`Failed to update variables: ${failed.join(', ')}`); + } + // Ensure secret variables are preserved variableList.variables = [ ...secretVariables, diff --git a/src/routes/(console)/project-[region]-[project]/sites/create-site/configuration.svelte b/src/routes/(console)/project-[region]-[project]/sites/create-site/configuration.svelte index f6d8129d6..73e1eea7c 100644 --- a/src/routes/(console)/project-[region]-[project]/sites/create-site/configuration.svelte +++ b/src/routes/(console)/project-[region]-[project]/sites/create-site/configuration.svelte @@ -3,16 +3,15 @@ import { Fieldset, Layout, Accordion } from '@appwrite.io/pink-svelte'; import type { Models } from '@appwrite.io/console'; import { iconPath } from '$lib/stores/app'; - import { getFrameworkIcon, type FrameworkAdapterWithStartCommand } from '$lib/stores/sites'; + import { getFrameworkIcon } from '$lib/stores/sites'; import { EnvironmentVariables } from '$lib/components/variables'; export let frameworks: Models.Framework[]; export let selectedFramework: Models.Framework; $: frameworkData = frameworks.find((framework) => framework.key === selectedFramework?.key); - $: adapterData = (frameworkData?.adapters.find((adapter) => adapter.key === 'ssr') ?? - frameworkData?.adapters.find( - (adapter) => adapter.key === 'static' - )) as FrameworkAdapterWithStartCommand; + $: adapterData = + frameworkData?.adapters.find((adapter) => adapter.key === 'ssr') ?? + frameworkData?.adapters.find((adapter) => adapter.key === 'static'); export let variables: Partial[] = []; export let isLoading = false; @@ -28,8 +27,8 @@ $: if (frameworkData && adapterDefaultsKey !== lastAdapterDefaultsKey) { installCommand = adapterData?.installCommand ?? ''; buildCommand = adapterData?.buildCommand ?? ''; - startCommand = adapterData?.startCommand ?? ''; outputDirectory = adapterData?.outputDirectory ?? ''; + startCommand = ''; lastAdapterDefaultsKey = adapterDefaultsKey; } @@ -92,16 +91,7 @@ id="startCommand" label="Start command" bind:value={startCommand} - placeholder={adapterData?.startCommand || - 'Enter start command'} /> - + placeholder="Enter start command" /> {/if} diff --git a/src/routes/(console)/project-[region]-[project]/sites/create-site/deploy/+page.svelte b/src/routes/(console)/project-[region]-[project]/sites/create-site/deploy/+page.svelte index fa75d2794..79c4c28f0 100644 --- a/src/routes/(console)/project-[region]-[project]/sites/create-site/deploy/+page.svelte +++ b/src/routes/(console)/project-[region]-[project]/sites/create-site/deploy/+page.svelte @@ -27,7 +27,7 @@ import { writable } from 'svelte/store'; import { getLatestTag } from '$lib/helpers/github'; import Link from '$lib/elements/link.svelte'; - import type { FrameworkAdapterWithStartCommand } from '$lib/stores/sites'; + import { validateVariables } from '$lib/helpers/variables'; let { data @@ -94,7 +94,6 @@ const adapter = fw.adapters[0]; installCommand = adapter.installCommand || ''; buildCommand = adapter.buildCommand || ''; - startCommand = (adapter as FrameworkAdapterWithStartCommand).startCommand || ''; outputDirectory = adapter.outputDirectory || ''; } } @@ -124,7 +123,6 @@ const adapter = fw.adapters[0]; installCommand = adapter.installCommand || ''; buildCommand = adapter.buildCommand || ''; - startCommand = (adapter as FrameworkAdapterWithStartCommand).startCommand || ''; outputDirectory = adapter.outputDirectory || ''; } } @@ -147,6 +145,13 @@ $isSubmitting = true; try { + // Reject an unusable key before the resource is created, so a + // rejected variable can't leave a half-configured resource behind. + const validationError = validateVariables(variables); + if (validationError) { + throw new Error(validationError); + } + // Create site with build configuration let site = await sdk.forProject(page.params.region, page.params.project).sites.create({ siteId: id || ID.unique(), @@ -264,7 +269,8 @@ label="Framework" placeholder="Select framework" bind:value={framework} - options={frameworkSelectOptions} /> + options={frameworkSelectOptions} + on:change={() => (startCommand = '')} /> diff --git a/src/routes/(console)/project-[region]-[project]/sites/create-site/manual/+page.svelte b/src/routes/(console)/project-[region]-[project]/sites/create-site/manual/+page.svelte index f2da210d0..46dc62789 100644 --- a/src/routes/(console)/project-[region]-[project]/sites/create-site/manual/+page.svelte +++ b/src/routes/(console)/project-[region]-[project]/sites/create-site/manual/+page.svelte @@ -26,7 +26,7 @@ import { currentPlan } from '$lib/stores/organization'; import Domain from '../domain.svelte'; import { uploader } from '$lib/stores/uploader'; - import type { FrameworkAdapterWithStartCommand } from '$lib/stores/sites'; + import { validateVariables } from '$lib/helpers/variables'; export let data; let showExitModal = false; @@ -41,10 +41,10 @@ let framework: Models.Framework = data.frameworks.frameworks?.find((f) => f.key === 'other') ?? data.frameworks.frameworks?.[0]; - let adapter = framework?.adapters[0] as FrameworkAdapterWithStartCommand; + let adapter = framework?.adapters[0]; let installCommand = adapter?.installCommand; let buildCommand = adapter?.buildCommand; - let startCommand = adapter?.startCommand; + let startCommand = ''; let outputDirectory = adapter?.outputDirectory; let variables: Partial[] = []; let files: FileList; @@ -60,6 +60,13 @@ let site: Models.Site | null = null; try { + // Reject an unusable key before the resource is created, so a + // rejected variable can't leave a half-configured resource behind. + const validationError = validateVariables(variables); + if (validationError) { + throw new Error(validationError); + } + if (!domainIsValid) { addNotification({ type: 'error', diff --git a/src/routes/(console)/project-[region]-[project]/sites/create-site/repositories/repository-[repository]/+page.svelte b/src/routes/(console)/project-[region]-[project]/sites/create-site/repositories/repository-[repository]/+page.svelte index aca5fe7bb..aa0f25a0c 100644 --- a/src/routes/(console)/project-[region]-[project]/sites/create-site/repositories/repository-[repository]/+page.svelte +++ b/src/routes/(console)/project-[region]-[project]/sites/create-site/repositories/repository-[repository]/+page.svelte @@ -27,8 +27,11 @@ import Configuration from '../../configuration.svelte'; import Domain from '../../domain.svelte'; import { regionalConsoleVariables } from '$routes/(console)/project-[region]-[project]/store'; - import { normalizeDetectedVariables, mergeVariables } from '$lib/helpers/variables'; - import type { FrameworkAdapterWithStartCommand } from '$lib/stores/sites'; + import { + normalizeDetectedVariables, + mergeVariables, + validateVariables + } from '$lib/helpers/variables'; export let data; let showExitModal = false; @@ -39,12 +42,12 @@ let name = ''; let id = ID.unique(); let framework: Models.Framework = data.frameworks.frameworks.find((f) => f.key === 'other'); - let adapter = framework?.adapters[0] as FrameworkAdapterWithStartCommand; + let adapter = framework?.adapters[0]; let branch: string; let rootDir = './'; let installCommand = adapter?.installCommand; let buildCommand = adapter?.buildCommand; - let startCommand = adapter?.startCommand; + let startCommand = ''; let outputDirectory = adapter?.outputDirectory; let variables: Partial[] = []; let silentMode = false; @@ -83,10 +86,9 @@ if (!framework) { framework = data.frameworks.frameworks.find((f) => f.key === 'other'); } - adapter = framework?.adapters[0] as FrameworkAdapterWithStartCommand; + adapter = framework?.adapters[0]; installCommand = adapter?.installCommand; buildCommand = adapter?.buildCommand; - startCommand = adapter?.startCommand; outputDirectory = adapter?.outputDirectory; const detectedVariables = normalizeDetectedVariables(response?.variables); if (detectedVariables.length) { @@ -113,6 +115,13 @@ return; } try { + // Reject an unusable key before the resource is created, so a + // rejected variable can't leave a half-configured resource behind. + const validationError = validateVariables(variables); + if (validationError) { + throw new Error(validationError); + } + const fr = Object.values(Framework).find((f) => f === framework.key); const buildRuntime = Object.values(BuildRuntime).find( (f) => f === framework.buildRuntime diff --git a/src/routes/(console)/project-[region]-[project]/sites/create-site/templates/template-[template]/+page.svelte b/src/routes/(console)/project-[region]-[project]/sites/create-site/templates/template-[template]/+page.svelte index a11121d55..006003d84 100644 --- a/src/routes/(console)/project-[region]-[project]/sites/create-site/templates/template-[template]/+page.svelte +++ b/src/routes/(console)/project-[region]-[project]/sites/create-site/templates/template-[template]/+page.svelte @@ -45,6 +45,7 @@ import { getFrameworkIcon } from '$lib/stores/sites'; import { regionalConsoleVariables } from '$routes/(console)/project-[region]-[project]/store'; import { getTemplateSourceUrl } from '$lib/helpers/templateSource'; + import { validateVariables } from '$lib/helpers/variables'; export let data; @@ -117,6 +118,15 @@ return; } else { try { + // Reject an unusable key before the resource is created, so a + // rejected variable can't leave a half-configured resource behind. + const validationError = validateVariables( + variables.map((variable) => ({ key: variable.name, value: variable.value })) + ); + if (validationError) { + throw new Error(validationError); + } + const fr = Object.values(Framework).find((f) => f === framework.key); const buildRuntime = Object.values(BuildRuntime).find( (f) => f === framework.buildRuntime diff --git a/src/routes/(console)/project-[region]-[project]/sites/site-[site]/settings/updateBuildSettings.svelte b/src/routes/(console)/project-[region]-[project]/sites/site-[site]/settings/updateBuildSettings.svelte index 433a9b45d..977cb98f7 100644 --- a/src/routes/(console)/project-[region]-[project]/sites/site-[site]/settings/updateBuildSettings.svelte +++ b/src/routes/(console)/project-[region]-[project]/sites/site-[site]/settings/updateBuildSettings.svelte @@ -12,7 +12,7 @@ import { Link } from '$lib/elements'; import { IconInfo } from '@appwrite.io/pink-icons-svelte'; import { adapterDataList } from './store'; - import { getFrameworkIcon, type FrameworkAdapterWithStartCommand } from '$lib/stores/sites'; + import { getFrameworkIcon } from '$lib/stores/sites'; import { page } from '$app/state'; let { @@ -50,9 +50,8 @@ (fallback ?? '') === (site?.fallbackFile ?? '') && (adapter ?? '') === (site?.adapter ?? '') ); - let frameworkAdapterData: FrameworkAdapterWithStartCommand = $derived( - (selectedFramework.adapters.find((a) => a.key === adapter) ?? - selectedFramework.adapters[0]) as FrameworkAdapterWithStartCommand + let frameworkAdapterData = $derived( + selectedFramework.adapters.find((a) => a.key === adapter) ?? selectedFramework.adapters[0] ); $effect(() => { @@ -77,17 +76,19 @@ } //Update values - const data = (selectedFramework.adapters.find((a) => a.key === adapter) ?? - selectedFramework.adapters[0]) as FrameworkAdapterWithStartCommand; + const data = + selectedFramework.adapters.find((a) => a.key === adapter) ?? + selectedFramework.adapters[0]; installCommand = data.installCommand; buildCommand = data.buildCommand; - startCommand = data.startCommand; + startCommand = ''; outputDirectory = data.outputDirectory; adapter = data.key as Adapter; fallback = data.fallbackFile; } else if (hasFrameworkSelectionChanged) { - const data = (selectedFramework.adapters.find((a) => a.key === adapter) ?? - selectedFramework.adapters[0]) as FrameworkAdapterWithStartCommand; + const data = + selectedFramework.adapters.find((a) => a.key === adapter) ?? + selectedFramework.adapters[0]; const isOriginalAdapter = adapter === site.adapter; installCommand = isOriginalAdapter @@ -96,9 +97,7 @@ buildCommand = isOriginalAdapter ? (site?.buildCommand ?? frameworkAdapterData.buildCommand) : data.buildCommand; - startCommand = isOriginalAdapter - ? (site?.startCommand ?? frameworkAdapterData.startCommand) - : data.startCommand; + startCommand = isOriginalAdapter ? (site?.startCommand ?? '') : ''; outputDirectory = isOriginalAdapter ? (site?.outputDirectory ?? frameworkAdapterData.outputDirectory) : data.outputDirectory; @@ -162,7 +161,7 @@ timeout: site.timeout || undefined, installCommand: installCommand || undefined, buildCommand: buildCommand || undefined, - startCommand: startCommand || undefined, + startCommand: adptr?.key === 'ssr' ? startCommand || undefined : undefined, outputDirectory: outputDirectory || undefined, buildRuntime: (site?.buildRuntime as BuildRuntime) || undefined, adapter: (adptr?.key as Adapter) || undefined, @@ -193,17 +192,13 @@ } } - function reset(type: 'installCommand' | 'buildCommand' | 'startCommand' | 'outputDirectory') { - const data = selectedFramework.adapters.find( - (a) => a.key === adapter - ) as FrameworkAdapterWithStartCommand; + function reset(type: 'installCommand' | 'buildCommand' | 'outputDirectory') { + const data = selectedFramework.adapters.find((a) => a.key === adapter); if (type === 'installCommand') { installCommand = data.installCommand; } else if (type === 'buildCommand') { buildCommand = data.buildCommand; - } else if (type === 'startCommand') { - startCommand = data.startCommand; } else if (type === 'outputDirectory') { outputDirectory = data.outputDirectory; } @@ -338,16 +333,7 @@ id="startCommand" label="Start command" bind:value={startCommand} - placeholder={frameworkAdapterData?.startCommand || - 'Enter start command'} /> - + placeholder="Enter start command" /> {/if} diff --git a/src/routes/(console)/project-[region]-[project]/updateVariables.svelte b/src/routes/(console)/project-[region]-[project]/updateVariables.svelte index 8b9f3da47..7164be11a 100644 --- a/src/routes/(console)/project-[region]-[project]/updateVariables.svelte +++ b/src/routes/(console)/project-[region]-[project]/updateVariables.svelte @@ -5,6 +5,7 @@ import { CardGrid, Empty, Output, PaginationInline } from '$lib/components'; import UploadVariables from './uploadVariablesModal.svelte'; import { variablesOperation, type VariablesOperationItem } from './variablesOperation'; + import { isValidVariableKey, validateVariables } from '$lib/helpers/variables'; import { goto, invalidate } from '$app/navigation'; import { Click, Submit, trackError, trackEvent } from '$lib/actions/analytics'; import { Dependencies } from '$lib/constants'; @@ -21,6 +22,7 @@ Layout, Popover, Table, + Tooltip, Alert } from '@appwrite.io/pink-svelte'; import { @@ -55,7 +57,7 @@ ) => Promise; export let sdkUpdateVariable: ( variableId: string, - key: string, + key: string | undefined, value: string, secret?: boolean ) => Promise; @@ -127,10 +129,24 @@ async function handleVariableCreated(event: CustomEvent) { const variables = event.detail; try { - const promises = variables.map((variable) => - sdkCreateVariable(variable.key, variable.value, variable?.secret || false) + const results = await Promise.allSettled( + variables.map((variable) => + sdkCreateVariable(variable.key, variable.value, variable?.secret || false) + ) ); - await Promise.all(promises); + + // Each variable is created on its own, so name the keys that failed + // instead of reporting a single rejection for the whole batch. + const failed = results + .map((result, index) => + result.status === 'rejected' ? variables[index].key : null + ) + .filter(Boolean); + + if (failed.length) { + throw new Error(`Failed to create variables: ${failed.join(', ')}`); + } + fullVariableList = undefined; showVariablesModal = false; addNotification({ @@ -174,7 +190,10 @@ async function handleVariableSecret(event: CustomEvent) { const variable = event.detail; try { - await sdkUpdateVariable(variable.$id, variable.key, variable.value, variable.secret); + // Marking a variable secret never changes its key, so leave the key + // out and keep the stored one — including keys that predate the + // identifier rule. + await sdkUpdateVariable(variable.$id, undefined, variable.value, variable.secret); fullVariableList = undefined; selectedVar = null; showVariablesModal = false; @@ -237,6 +256,14 @@ async function handleVariablePromoted(variable: Models.Variable) { try { + // Promoting a conflicting key deletes the existing global variable + // before recreating it, so refuse a key the API would reject rather + // than deleting one and failing to create its replacement. + const validationError = validateVariables([variable]); + if (validationError) { + throw new Error(validationError); + } + const globalVariable = globalVariableList ? globalVariableList.variables.find( (globalVariable) => globalVariable.key === variable.key @@ -507,6 +534,19 @@ class="icon-exclamation u-color-text-warning" aria-hidden="true"> {/if} + {#if !isValidVariableKey(variable.key)} + + + + This key can't be used as an environment variable + name, so it is ignored at build and runtime. Rename + it using only letters, digits and underscores, + without starting with a digit. + + + {/if} {variable.key} diff --git a/src/routes/(console)/project-[region]-[project]/updateVariablesModal.svelte b/src/routes/(console)/project-[region]-[project]/updateVariablesModal.svelte index d22a14c57..af61ff9fa 100644 --- a/src/routes/(console)/project-[region]-[project]/updateVariablesModal.svelte +++ b/src/routes/(console)/project-[region]-[project]/updateVariablesModal.svelte @@ -8,6 +8,7 @@ import { base } from '$app/paths'; import { Alert, Layout, Selector } from '@appwrite.io/pink-svelte'; import { Link } from '$lib/elements'; + import { getVariableValueError, validateVariables } from '$lib/helpers/variables'; export let isGlobal: boolean; export let product: 'function' | 'site' = 'function'; @@ -21,6 +22,10 @@ secret: selectedVar?.secret }; + const originalKey = selectedVar?.key; + + let error = ''; + const dispatch = createEventDispatcher(); function close() { @@ -29,7 +34,21 @@ } function handleVariable() { - dispatch('updated', pair); + const keyChanged = pair.key !== originalKey; + + // A key stored before the identifier rule existed is left untouched so + // its value stays editable; only a key the user actually changed has to + // satisfy the rule. + const validationError = keyChanged + ? validateVariables([pair]) + : getVariableValueError(pair.key, pair.value); + + if (validationError) { + error = validationError; + return; + } + + dispatch('updated', { ...pair, key: keyChanged ? pair.key : undefined }); close(); } @@ -41,6 +60,7 @@ diff --git a/src/routes/(console)/project-[region]-[project]/uploadVariablesModal.svelte b/src/routes/(console)/project-[region]-[project]/uploadVariablesModal.svelte index 134fe5c09..e2d10734c 100644 --- a/src/routes/(console)/project-[region]-[project]/uploadVariablesModal.svelte +++ b/src/routes/(console)/project-[region]-[project]/uploadVariablesModal.svelte @@ -16,6 +16,7 @@ } from '@appwrite.io/pink-svelte'; import { parse } from '$lib/helpers/envfile'; import { removeFile } from '$lib/helpers/files'; + import { validateVariables } from '$lib/helpers/variables'; import type { VariablesOperationItem } from './variablesOperation'; export let show = false; @@ -27,7 +28,7 @@ ) => Promise; export let sdkUpdateVariable: ( variableId: string, - key: string, + key: string | undefined, value: string, secret?: boolean ) => Promise; @@ -64,18 +65,19 @@ const entries = Object.entries(uploaded); - for (const [key, value] of entries) { - if (value.length > 8192) { - throw new Error(`Variable ${key} is longer than 8192 allowed characters`); - } - } - const filteredEntries = entries.filter(([, value]) => !!value); if (!filteredEntries.length) { throw new Error('No variables found'); } + const validationError = validateVariables( + filteredEntries.map(([key, value]) => ({ key, value })) + ); + if (validationError) { + throw new Error(validationError); + } + if (filteredEntries.length > 100) { throw new Error('Please upload a file with fewer than 100 environment variables.'); } @@ -93,7 +95,7 @@ show = false; - await Promise.all( + const results = await Promise.allSettled( filteredEntries.map(([key, value]) => { const found = variableList.variables.find((variable) => variable.key === key); return found @@ -102,6 +104,18 @@ }) ); + // Each variable is written on its own, so report which keys failed + // instead of letting one rejection hide the ones that landed. + const failed = results + .map((result, index) => + result.status === 'rejected' ? filteredEntries[index][0] : null + ) + .filter(Boolean); + + if (failed.length) { + throw new Error(`Failed to upload variables: ${failed.join(', ')}`); + } + onStatusChange({ id: importId, count: uploadCount, diff --git a/src/routes/(public)/card/+layout.svelte b/src/routes/(public)/card/+layout.svelte deleted file mode 100644 index b795ff5b0..000000000 --- a/src/routes/(public)/card/+layout.svelte +++ /dev/null @@ -1,9 +0,0 @@ - - - - -