⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix: enforce security boundaries and bound integration workloads
Tin71bd1983a77f
diff --git a/.github/workflows/auto-merge.yml b/.github/workflows/auto-merge.ymlindex fe404d198..548d374eb 100644--- a/.github/workflows/auto-merge.yml+++ b/.github/workflows/auto-merge.yml@@ -1,41 +1,59 @@name: Dependabot Auto-Merge-on: pull_request+# Never check out or execute pull-request content in this privileged workflow.+on:+ pull_request_target:+ types: [opened, synchronize, reopened, ready_for_review]permissions:- contents: write- pull-requests: write+ contents: read+ pull-requests: readjobs:dependabot:- name: Dependabot Auto-Merge- runs-on: ubuntu-latest- if: github.actor == 'dependabot[bot]' && github.event.pull_request.user.login == 'dependabot[bot]'-+ runs-on: ubuntu-24.04+ timeout-minutes: 45+ if: >-+ github.actor == 'dependabot[bot]' &&+ github.event.pull_request.user.login == 'dependabot[bot]' &&+ github.event.pull_request.base.ref == 'main' &&+ github.event.pull_request.head.repo.full_name == github.repository+ permissions:+ contents: write+ pull-requests: write+ checks: read+ statuses: readsteps:- name: Dependabot Metadataid: metadata- uses: dependabot/fetch-metadata@v3+ uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3with:- github-token: "${{ secrets.GITHUB_TOKEN }}"+ github-token: ${{ github.token }}- - name: Auto-Merge Dependabot PR- if: steps.metadata.outputs.update-type == 'version-update:semver-patch' || steps.metadata.outputs.update-type == 'version-update:semver-minor'- run: |- # Wait a bit for any checks to start- sleep 30-- # Check if all required checks have passed- if gh pr view "$PR_URL" --json statusCheckRollup --jq '.statusCheckRollup | all(.conclusion == "SUCCESS")'; then- echo "All checks passed, merging..."- gh pr merge --squash "$PR_URL"- elif gh pr view "$PR_URL" --json statusCheckRollup --jq '.statusCheckRollup | length == 0'; then- echo "No status checks required, merging..."- gh pr merge --squash "$PR_URL"- else- echo "Status checks not passed, skipping merge"- gh pr view "$PR_URL" --json statusCheckRollup- fi+ - name: Merge eligible npm updates after required checks pass+ if: >-+ steps.metadata.outputs.package-ecosystem == 'npm_and_yarn' &&+ (steps.metadata.outputs.update-type == 'version-update:semver-patch' ||+ steps.metadata.outputs.update-type == 'version-update:semver-minor')env:- PR_URL: ${{github.event.pull_request.html_url}}- GH_TOKEN: ${{secrets.AUTO_MERGE_PAT}}+ GH_TOKEN: ${{ github.token }}+ PR_URL: ${{ github.event.pull_request.html_url }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }}+ run: |+ set -euo pipefail+ # Only manifests and the lockfile are eligible, including on renames.+ gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files" \+ | jq -se 'add | length > 0 and all(.[];+ .status != "renamed" and+ (.filename == "pnpm-lock.yaml" or+ .filename == "package.json" or+ (.filename | test("^(apps|packages)/[^/]+/package\\.json$"))))'++ # No configured/visible required checks is a failure, never permission to merge.+ gh pr checks "$PR_URL" --required --watch --fail-fast --interval 20+ gh pr checks "$PR_URL" --required --json name,bucket \+ | jq -e 'length > 0 and all(.[]; .bucket == "pass")'+ gh pr view "$PR_URL" --json headRefOid \+ | jq -e --arg sha "$EXPECTED_HEAD" '.headRefOid == $sha'+ gh pr merge "$PR_URL" --auto --squash --match-head-commit "$EXPECTED_HEAD"diff --git a/.github/workflows/build-images.yml b/.github/workflows/build-images.ymlindex 5b57de391..b30015a9d 100644--- a/.github/workflows/build-images.yml+++ b/.github/workflows/build-images.yml@@ -8,10 +8,15 @@ on:required: truetype: stringversion:- description: "Release version to stamp into the tree before building (blank builds the tree as-is)"+ description: "Release version to verify or stamp, according to source_mode (blank only for nightly)"required: falsetype: stringdefault: ""+ source_mode:+ description: "released checks out an existing reviewed tag; planned builds a new release from the run SHA; nightly uses the run SHA without a release version"+ required: false+ type: string+ default: releasedplatforms:required: falsetype: string@@ -19,6 +24,7 @@ on:jobs:build:+ if: github.ref == 'refs/heads/main'name: ${{ matrix.name }}runs-on: ubuntu-24.04permissions:@@ -40,24 +46,41 @@ jobs:steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ fetch-depth: 0+ ref: ${{ github.sha }}++ - name: Verify publication source+ id: source+ env:+ SOURCE_MODE: ${{ inputs.source_mode }}+ RELEASE_VERSION: ${{ inputs.version }}+ run: node scripts/security/verify-release-source.mjs "$SOURCE_MODE" "$RELEASE_VERSION"++ - name: Checkout verified source+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:persist-credentials: false+ ref: ${{ steps.source.outputs.source_sha }}# A release builds its images before the release commit exists, and the# artifacts self-report their version.- name: Stamp release version- if: inputs.version != ''- run: node scripts/release/apply-version.mjs "${{ inputs.version }}"+ if: inputs.source_mode == 'planned'+ env:+ RELEASE_VERSION: ${{ inputs.version }}+ run: node scripts/release/apply-version.mjs "$RELEASE_VERSION"- name: Set up QEMU- uses: docker/setup-qemu-action@v4+ uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4- name: Set up Docker Buildx- uses: docker/setup-buildx-action@v4+ uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4- name: Log in to GitHub Container Registry- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4with:registry: ghcr.iousername: ${{ github.actor }}@@ -65,7 +88,7 @@ jobs:- name: Extract metadataid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6with:images: ${{ matrix.image }}tags: ${{ inputs.tags }}@@ -80,7 +103,7 @@ jobs:chmod 600 /tmp/sentry-build-secrets/SENTRY_AUTH_TOKEN- name: Build and push- uses: docker/build-push-action@v7+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7with:context: .file: ${{ matrix.dockerfile }}diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2f4aecf1d..5e918d66a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -34,15 +34,15 @@ jobs:runs-on: ubuntu-24.04steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -57,17 +57,17 @@ jobs:runs-on: ubuntu-24.04steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:persist-credentials: false- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -82,17 +82,17 @@ jobs:runs-on: ubuntu-24.04steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:persist-credentials: false- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -107,15 +107,15 @@ jobs:runs-on: ubuntu-24.04steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -130,15 +130,15 @@ jobs:runs-on: ubuntu-24.04steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -146,22 +146,30 @@ jobs:- name: Install dependenciesrun: pnpm install --frozen-lockfile+ - name: Test release security controls+ run: |+ docker pull nginx:1.29.5-alpine+ node --test scripts/security/*.test.mjs+- name: Run unit tests+ env:+ # Let jsdom supply browser storage instead of Node's native storage.+ NODE_OPTIONS: --no-experimental-webstoragerun: pnpm testbuild:runs-on: ubuntu-24.04steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -197,15 +205,15 @@ jobs:DISABLE_GUEST_ACCESS: "false"steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -220,13 +228,13 @@ jobs:runs-on: ubuntu-24.04steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Set up Docker Buildx- uses: docker/setup-buildx-action@v4+ uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4- name: Build kaneo image (smoke test)- uses: docker/build-push-action@v7+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7with:context: .file: ./Dockerfile.kaneodiff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.ymlindex c805b63ed..170d8933a 100644--- a/.github/workflows/deploy-site.yml+++ b/.github/workflows/deploy-site.yml@@ -4,7 +4,6 @@ on:push:branches:- main- - cosspaths:- "apps/site/**"- "packages/**"@@ -15,8 +14,6 @@ on:permissions:contents: read- pages: write- id-token: writeconcurrency:group: "pages"@@ -24,23 +21,24 @@ concurrency:jobs:build:+ if: github.ref == 'refs/heads/main'name: Build static siteruns-on: ubuntu-lateststeps:- name: Checkout- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Setup Node- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: "24.19.0"- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6- name: Setup Pages- uses: actions/configure-pages@v6+ uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6- name: Install dependenciesrun: pnpm install --frozen-lockfile@@ -49,11 +47,15 @@ jobs:run: pnpm --filter @kaneo/site build- name: Upload Pages artifact- uses: actions/upload-pages-artifact@v5+ uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5with:path: apps/site/outdeploy:+ if: github.ref == 'refs/heads/main'+ permissions:+ pages: write+ id-token: writename: Deploy to GitHub Pagesenvironment:name: github-pages@@ -63,4 +65,4 @@ jobs:steps:- name: Deployid: deployment- uses: actions/deploy-pages@v5+ uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.ymlindex 12eb251de..cbb32c921 100644--- a/.github/workflows/docker.yml+++ b/.github/workflows/docker.yml@@ -4,7 +4,7 @@ on:workflow_dispatch:inputs:version:- description: "Version to tag the images (e.g., 1.0.0)"+ description: "Existing released version to rebuild from its reviewed vX.Y.Z tag"required: truetype: stringlatest:@@ -15,12 +15,14 @@ on:jobs:build:+ if: github.ref == 'refs/heads/main'permissions:contents: readpackages: writeuses: ./.github/workflows/build-images.ymlsecrets: inheritwith:+ source_mode: releasedversion: ${{ inputs.version }}tags: |type=raw,value=${{ inputs.version }}diff --git a/.github/workflows/helm-chart.yml b/.github/workflows/helm-chart.ymlindex f2c7868a8..ca6fad28e 100644--- a/.github/workflows/helm-chart.yml+++ b/.github/workflows/helm-chart.yml@@ -16,7 +16,7 @@ on:workflow_dispatch:inputs:version:- description: "Chart version to publish (e.g. 1.0.0)"+ description: "Existing released version to publish from its reviewed vX.Y.Z tag"required: truetype: string@@ -31,7 +31,7 @@ jobs:uses: ./.github/workflows/helm-validate.ymlpublish:- if: inputs.version != ''+ if: github.ref == 'refs/heads/main' && inputs.version != ''runs-on: ubuntu-24.04needs: validatepermissions:@@ -40,22 +40,36 @@ jobs:steps:- name: Checkout repository- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:persist-credentials: false+ fetch-depth: 0+ ref: ${{ github.sha }}++ - name: Verify publication source+ id: source+ env:+ RELEASE_VERSION: ${{ inputs.version }}+ run: node scripts/security/verify-release-source.mjs released "$RELEASE_VERSION"++ - name: Checkout verified release tag+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ ref: ${{ steps.source.outputs.source_sha }}- name: Set up Helmuses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5- - name: Resolve chart version- env:- INPUT_VERSION: ${{ inputs.version }}- run: echo "CHART_VERSION=$INPUT_VERSION" >> "$GITHUB_ENV"+ - name: Validate the release chart+ run: |+ helm lint "$CHART_PATH" --set kaneo.env.authSecret=validation-only-secret-at-least-32-characters --set kaneo.env.clientUrl=https://kaneo.example.com+ helm template kaneo "$CHART_PATH" --set kaneo.env.authSecret=validation-only-secret-at-least-32-characters --set kaneo.env.clientUrl=https://kaneo.example.com > /dev/null- name: Package chartrun: |mkdir -p dist- helm package "$CHART_PATH" --version "$CHART_VERSION" --app-version "$CHART_VERSION" --destination dist+ helm package "$CHART_PATH" --destination dist- name: Log in to GHCRenv:@@ -64,6 +78,8 @@ jobs:run: echo "$GH_TOKEN" | helm registry login "$REGISTRY" --username "$GH_ACTOR" --password-stdin- name: Publish chart+ env:+ CHART_VERSION: ${{ inputs.version }}run: |OWNER="${GITHUB_REPOSITORY_OWNER,,}"CHART_REF="oci://$REGISTRY/$OWNER/charts/kaneo"diff --git a/.github/workflows/helm-validate.yml b/.github/workflows/helm-validate.ymlindex 1fa79a09e..5d44ae609 100644--- a/.github/workflows/helm-validate.yml+++ b/.github/workflows/helm-validate.yml@@ -49,7 +49,7 @@ jobs:steps:- name: Checkout repository- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:persist-credentials: false@@ -57,7 +57,7 @@ jobs:uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5- name: Lint chart- run: helm lint "$CHART_PATH"+ run: helm lint "$CHART_PATH" --set kaneo.env.clientUrl=https://kaneo.example.com ${{ matrix.args }}- name: Render chart (${{ matrix.name }})- run: helm template kaneo "$CHART_PATH" ${{ matrix.args }}+ run: helm template kaneo "$CHART_PATH" --set kaneo.env.clientUrl=https://kaneo.example.com ${{ matrix.args }}diff --git a/.github/workflows/issue-notify.yml b/.github/workflows/issue-notify.ymlindex b856a8918..3860987fe 100644--- a/.github/workflows/issue-notify.yml+++ b/.github/workflows/issue-notify.yml@@ -4,9 +4,12 @@ on:issues:types: [opened]+permissions: {}+jobs:notify:- runs-on: ubuntu-latest+ runs-on: ubuntu-24.04+ timeout-minutes: 5steps:- name: Post to Discordenv:@@ -21,5 +24,5 @@ jobs:--arg url "$ISSUE_URL" \--arg number "$ISSUE_NUMBER" \--arg author "$AUTHOR" \- '{content: "New issue #\($number) by **\($author)**: \($title)\n\($url)"}')- curl -fsS -H "Content-Type: application/json" -d "$payload" "$WEBHOOK"+ '{allowed_mentions: {parse: []}, content: "New issue #\($number) by **\($author)**: \($title)\n\($url)"}')+ curl --connect-timeout 5 --max-time 30 -fsS -H "Content-Type: application/json" -d "$payload" "$WEBHOOK"diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.ymlindex 1cdfbb57c..605015c0f 100644--- a/.github/workflows/nightly.yml+++ b/.github/workflows/nightly.yml@@ -46,12 +46,12 @@ jobs:persist-credentials: false- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -81,6 +81,7 @@ jobs:uses: ./.github/workflows/build-images.ymlsecrets: inheritwith:+ source_mode: nightlytags: |type=raw,value=nightlytype=raw,value=nightly-{{date 'YYYYMMDD'}}diff --git a/.github/workflows/pr-size-labeler.yml b/.github/workflows/pr-size-labeler.ymlindex b33c2db1a..f202e1d9d 100644--- a/.github/workflows/pr-size-labeler.yml+++ b/.github/workflows/pr-size-labeler.yml@@ -19,7 +19,7 @@ jobs:steps:# Only read trusted base-branch configuration, including for fork PRs.- name: Checkout size configuration- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:ref: ${{ github.event.pull_request.base.sha }}persist-credentials: falsediff --git a/.github/workflows/publish-mcp.yml b/.github/workflows/publish-mcp.ymlindex ff7530de1..38597616d 100644--- a/.github/workflows/publish-mcp.yml+++ b/.github/workflows/publish-mcp.yml@@ -24,17 +24,28 @@ jobs:steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:persist-credentials: false+ fetch-depth: 0++ - name: Require reviewed release source+ env:+ EVENT_NAME: ${{ github.event_name }}+ run: |+ set -euo pipefail+ if [ "$EVENT_NAME" = push ] && [ "$GITHUB_REF" != refs/heads/main ]; then+ exit 1+ fi+ git merge-base --is-ancestor "$GITHUB_SHA" refs/remotes/origin/main- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -81,21 +92,6 @@ jobs:cd packages/mcpnpm publish --access public --provenance- - name: Publish to the MCP Registry- run: |- PACKAGE_VERSION=$(node -p "require('./packages/mcp/package.json').version")- IN_REGISTRY=$(curl -s "https://registry.modelcontextprotocol.io/v0/servers?search=io.github.usekaneo/kaneo" \- | jq -r --arg v "$PACKAGE_VERSION" '[.servers[]? | (.server // .) | select(.name == "io.github.usekaneo/kaneo" and .version == $v)] | length')- if [ "$IN_REGISTRY" != "0" ]; then- echo "io.github.usekaneo/kaneo@${PACKAGE_VERSION} is already in the MCP Registry; skipping."- exit 0- fi- curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher- cd packages/mcp- jq --arg v "$PACKAGE_VERSION" '.version = $v | .packages[0].version = $v' server.json > server.tmp && mv server.tmp server.json- ../../mcp-publisher login github-oidc- ../../mcp-publisher publish-- name: Create MCP releaseif: ${{ github.event_name == 'push' }}run: |@@ -113,3 +109,37 @@ jobs:--latest=falseenv:GH_TOKEN: ${{ github.token }}++ publish-registry:+ needs: publish+ runs-on: ubuntu-24.04+ permissions:+ contents: read+ id-token: write+ steps:+ - name: Checkout repository+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Publish to the MCP Registry+ run: |+ set -euo pipefail+ PACKAGE_VERSION=$(jq -r .version packages/mcp/package.json)+ IN_REGISTRY=$(curl --fail --silent --show-error --max-time 30 \+ "https://registry.modelcontextprotocol.io/v0/servers?search=io.github.usekaneo/kaneo" \+ | jq -er --arg v "$PACKAGE_VERSION" '[.servers[]? | (.server // .) | select(.name == "io.github.usekaneo/kaneo" and .version == $v)] | length')+ if [ "$IN_REGISTRY" != "0" ]; then+ echo "MCP version already registered; skipping."+ exit 0+ fi+ curl --fail --silent --show-error --location --max-time 120 \+ --output "$RUNNER_TEMP/mcp-publisher.tar.gz" \+ "https://github.com/modelcontextprotocol/registry/releases/download/v1.8.1/mcp-publisher_linux_amd64.tar.gz"+ echo "a06c9096dcb9727c13555b6be26c7effa707b01f06a4c561ba7a3635443cf2cc $RUNNER_TEMP/mcp-publisher.tar.gz" | sha256sum --check --strict+ tar -xzf "$RUNNER_TEMP/mcp-publisher.tar.gz" -C "$RUNNER_TEMP" mcp-publisher+ cd packages/mcp+ jq --arg v "$PACKAGE_VERSION" '.version = $v | .packages[0].version = $v' server.json > server.tmp+ mv server.tmp server.json+ "$RUNNER_TEMP/mcp-publisher" login github-oidc+ "$RUNNER_TEMP/mcp-publisher" publishdiff --git a/.github/workflows/publish-planka-import.yml b/.github/workflows/publish-planka-import.ymlindex 0319d6a95..e47af027b 100644--- a/.github/workflows/publish-planka-import.yml+++ b/.github/workflows/publish-planka-import.yml@@ -23,12 +23,23 @@ jobs:steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:persist-credentials: false+ fetch-depth: 0++ - name: Require reviewed release source+ env:+ EVENT_NAME: ${{ github.event_name }}+ run: |+ set -euo pipefail+ if [ "$EVENT_NAME" = push ] && [ "$GITHUB_REF" != refs/heads/main ]; then+ exit 1+ fi+ git merge-base --is-ancestor "$GITHUB_SHA" refs/remotes/origin/main- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1@@ -36,7 +47,7 @@ jobs:# NODE_AUTH_TOKEN, and npm only attempts the tokenless OIDC exchange when# no auth is configured. Node 24 is required for npm >= 11.5.1 (OIDC).- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24cache: pnpmdiff --git a/.github/workflows/release-notify.yml b/.github/workflows/release-notify.ymlindex bee33c144..d644a59dc 100644--- a/.github/workflows/release-notify.yml+++ b/.github/workflows/release-notify.yml@@ -4,9 +4,12 @@ on:release:types: [published]+permissions: {}+jobs:notify:- runs-on: ubuntu-latest+ runs-on: ubuntu-24.04+ timeout-minutes: 5steps:- name: Post to Discordenv:@@ -35,4 +38,4 @@ jobs:footer: {text: "usekaneo/kaneo"}}]}')- curl -fsS -H "Content-Type: application/json" -d "$payload" "$WEBHOOK"+ curl --connect-timeout 5 --max-time 30 -fsS -H "Content-Type: application/json" -d "$payload" "$WEBHOOK"diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e6f6e0522..cc447527d 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -45,17 +45,17 @@ jobs:fi- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:fetch-depth: 0- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -104,6 +104,7 @@ jobs:uses: ./.github/workflows/build-images.ymlsecrets: inheritwith:+ source_mode: plannedversion: ${{ needs.plan.outputs.version }}tags: type=raw,value=${{ needs.plan.outputs.version }}@@ -130,18 +131,18 @@ jobs:# The same token the API calls use, so the release commit and tag are not# pushed under a different identity than the one that was verified.- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:fetch-depth: 0token: ${{ secrets.RELEASE_TOKEN || secrets.GITHUB_TOKEN }}- name: Setup pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6with:version: 10.32.1- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 24.19.0cache: pnpm@@ -156,11 +157,14 @@ jobs:env:GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITHUB_TOKEN }}RELEASE_TYPE: ${{ inputs.release_type }}+ PLANNED_VERSION: ${{ needs.plan.outputs.version }}GIT_AUTHOR_NAME: github-actions[bot]GIT_AUTHOR_EMAIL: github-actions[bot]@users.noreply.github.comGIT_COMMITTER_NAME: github-actions[bot]GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com- run: pnpm exec semantic-release+ run: |+ node scripts/security/verify-release-source.mjs planned "$PLANNED_VERSION"+ pnpm exec semantic-release- name: Verify the released version matches the built imagesenv:@@ -181,7 +185,7 @@ jobs:packages: writesteps:- name: Log in to GitHub Container Registry- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4with:registry: ghcr.iousername: ${{ github.actor }}diff --git a/.github/workflows/update-contributors.yml b/.github/workflows/update-contributors.ymlindex 408539d6f..2e920c0ca 100644--- a/.github/workflows/update-contributors.yml+++ b/.github/workflows/update-contributors.yml@@ -12,18 +12,21 @@ on:jobs:update-contributors:+ if: github.ref == 'refs/heads/main'runs-on: ubuntu-latestpermissions:contents: write- pull-requests: write- actions: write+ pull-requests: read++ outputs:+ pushed: ${{ steps.commit.outputs.pushed }}steps:- name: Checkout repository- uses: actions/[email protected]+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Generate Contributors Images- uses: jaywcjlove/github-action-contributors@main+ uses: jaywcjlove/github-action-contributors@86707f6d4c2469ce6b46bc3367253ebd41ee242c # mainwith:token: ${{ secrets.GITHUB_TOKEN }}filter-author: (renovate\[bot\]|renovate-bot|dependabot\[bot\])@@ -32,7 +35,7 @@ jobs:- name: Generate Sponsors Sectionif: ${{ github.repository_owner == 'usekaneo' }}- uses: JamesIves/github-sponsors-readme-action@v1+ uses: JamesIves/github-sponsors-readme-action@02650b8cd445fc16dfef73195f9c406dce041623 # v1with:token: ${{ secrets.GH_ANDREJ }}file: 'README.md'@@ -58,8 +61,14 @@ jobs:echo "pushed=false" >> "$GITHUB_OUTPUT"fi+ deploy-site:+ needs: update-contributors+ if: needs.update-contributors.outputs.pushed == 'true' && github.ref == 'refs/heads/main'+ runs-on: ubuntu-24.04+ permissions:+ actions: write+ steps:- name: Deploy Site- if: ${{ steps.commit.outputs.pushed == 'true' }}env:GH_TOKEN: ${{ github.token }}- run: gh workflow run deploy-site.yml --repo "${GITHUB_REPOSITORY}" --ref main\ No newline at end of file+ run: gh workflow run deploy-site.yml --repo "$GITHUB_REPOSITORY" --ref maindiff --git a/Dockerfile.kaneo b/Dockerfile.kaneoindex 7823c0b9f..74396f7cd 100644--- a/Dockerfile.kaneo+++ b/Dockerfile.kaneo@@ -79,7 +79,7 @@ WORKDIR /app/packages/permissionsRUN pnpm run buildWORKDIR /app/apps/web-RUN pnpm run build+RUN pnpm run build && find dist -type f -name '*.map' -deleteFROM node:24.19.0-alpine AS runtime@@ -103,6 +103,7 @@ COPY --from=web-builder --chown=appuser:appuser /app/apps/web/dist /usr/share/ngCOPY --chown=appuser:appuser apps/web/nginx.kaneo.conf /etc/nginx/conf.d/default.confRUN chown -R appuser:appuser /etc/nginx/conf.dCOPY --chown=appuser:appuser apps/web/env.sh /docker-entrypoint.d/env.sh+COPY --chown=appuser:appuser apps/web/env.awk /docker-entrypoint.d/env.awkCOPY --chown=appuser:appuser deploy/kaneo-entrypoint.sh /usr/local/bin/kaneo-entrypoint.shRUN chmod +x /docker-entrypoint.d/env.sh /usr/local/bin/kaneo-entrypoint.shdiff --git a/ENVIRONMENT_SETUP.md b/ENVIRONMENT_SETUP.mdindex 1a6380e19..6c5c60538 100644--- a/ENVIRONMENT_SETUP.md+++ b/ENVIRONMENT_SETUP.md@@ -81,11 +81,11 @@ For sending emails (workspace invitations, magic links, etc.), configure these v- `SMTP_USER` - SMTP username- `SMTP_PASSWORD` - SMTP password- `SMTP_FROM` - From email address-- `SMTP_SECURE` - Use TLS (default: `true`, set to `false` to disable)-- `SMTP_REQUIRE_TLS` - Require TLS (default: `false`, set to `true` to require)-- `SMTP_IGNORE_TLS` - Ignore TLS certificate errors (default: `false`, set to `true` for self-signed certificates)+- `SMTP_SECURE` - Use TLS immediately (default: `true`, typically port 465). Set to `false` for STARTTLS, typically on port 587.+- `SMTP_REQUIRE_TLS` - Require a STARTTLS upgrade when `SMTP_SECURE=false` (default: `true`). Sending fails if the server cannot upgrade. Only set to `false` for an intentionally unencrypted local development relay.+- `SMTP_IGNORE_TLS` - Removed: `true` is rejected because this option disabled STARTTLS and could send credentials and emails in plaintext.-> **Note:** If you're using an SMTP server with a self-signed or invalid TLS certificate, set `SMTP_IGNORE_TLS=true` to bypass certificate validation.+For a private SMTP certificate authority, configure Node's `NODE_EXTRA_CA_CERTS` with the path to a trusted CA PEM file before starting the API. Fix expired certificates or hostname mismatches instead of bypassing validation. When upgrading an existing installation, remove `SMTP_IGNORE_TLS=true` and check SMTP delivery with the corrected trust configuration before rollout.When SMTP is configured, sign-in uses email verification codes by default. Set `DISABLE_EMAIL_OTP_SIGN_IN=true` to use email/password sign-in instead (workspace invitation emails still use SMTP).@@ -131,7 +131,7 @@ For a complete list of all environment variables, their descriptions, and config```CORS_ORIGINS=http://localhost:5173,https://yourdomain.com```- - For development, you can leave `CORS_ORIGINS` empty to allow all origins+ - In development, unconfigured HTTP CORS may reflect origins. WebSocket connections always require an allowed origin (`KANEO_CLIENT_URL`, `KANEO_API_URL`, or an explicit `CORS_ORIGINS` entry).- **Note:** `CORS_ORIGINS` should match `KANEO_CLIENT_URL` for proper authentication3. **Check Protocol Consistency:**@@ -210,7 +210,7 @@ For a complete list of all environment variables, their descriptions, and config### Development- Use `http://localhost` for both frontend and API-- Leave `CORS_ORIGINS` empty to allow all origins (or set it to match your local URLs)+- Set `KANEO_CLIENT_URL` and `KANEO_API_URL` to your local URLs; list any additional frontend origins in `CORS_ORIGINS`. WebSocket origins are checked even in development (defaults are `http://localhost:5173` and `http://localhost:1337` when the corresponding URL is unset).- Use simple secrets for `AUTH_SECRET` (not for production)- The web app will use `VITE_API_URL` if set, otherwise defaults to `http://localhost:1337`diff --git a/README.md b/README.mdindex 01ce01c7e..1320ec002 100644--- a/README.md+++ b/README.md@@ -54,12 +54,13 @@ Kaneo is open source. If you find it useful, consider [sponsoring the project](h## Getting Started-### One-Click Deployment with drim+### Deployment with drimFor straightforward deployments, use [drim](https://github.com/usekaneo/drim) - a CLI tool that handles everything for you:+Install drim using the [version-pinned download and checksum verification](https://kaneo.app/docs/core/installation/drim#installation), then run:+```bash-curl -fsSL https://assets.kaneo.app/install.sh | shdrim setup```@@ -77,13 +78,14 @@ services:image: postgres:16-alpineenv_file:- .env- ports:- - "5432:5432"+ environment:+ POSTGRES_USER: ${POSTGRES_USER:-kaneo}+ POSTGRES_DB: ${POSTGRES_DB:-kaneo}volumes:- postgres_data:/var/lib/postgresql/datarestart: unless-stoppedhealthcheck:- test: ["CMD-SHELL", "pg_isready -U kaneo -d kaneo"]+ test: ["CMD-SHELL", 'pg_isready -U "$${POSTGRES_USER}" -d "$${POSTGRES_DB}"']interval: 10stimeout: 5sretries: 5@@ -106,7 +108,7 @@ volumes:Save this as `compose.yml`, copy `.env.sample` to `.env`, uncomment `KANEO_CLIENT_URL=http://localhost:5173`, and set `POSTGRES_PASSWORD=<password>` and `AUTH_SECRET=<output of openssl rand -hex 32>`, run `docker compose up -d`, and open [http://localhost:5173](http://localhost:5173).In Docker Compose, the bundled Kaneo container reaches PostgreSQL at the service hostname `postgres`.-If you run the API on your host instead of inside Compose, use `localhost` or set `DATABASE_URL` explicitly.+The database is reachable only inside the Compose network. If you run the API on your host, explicitly add a loopback-only database mapping (`127.0.0.1:5432:5432`) for development and configure `DATABASE_URL` accordingly.> **Important:** See our [full documentation](https://kaneo.app/docs/core) for detailed setup instructions, environment variable configuration, and troubleshooting guides.diff --git a/apps/api/drizzle/0046_repair_task_number_counters.sql b/apps/api/drizzle/0046_repair_task_number_counters.sqlnew file mode 100644index 000000000..1186cb113--- /dev/null+++ b/apps/api/drizzle/0046_repair_task_number_counters.sql@@ -0,0 +1,11 @@+-- Imports in older versions allocated task numbers without advancing the+-- project counter. Preserve every existing number and raise only stale counters.+UPDATE "project" AS p+SET "last_task_number" = greatest(p."last_task_number", counts.max_number)+FROM (+ SELECT "project_id", max("number") AS max_number+ FROM "task"+ GROUP BY "project_id"+) AS counts+WHERE p."id" = counts."project_id"+ AND p."last_task_number" < counts.max_number;diff --git a/apps/api/drizzle/0047_repair_legacy_auth_ownership.sql b/apps/api/drizzle/0047_repair_legacy_auth_ownership.sqlnew file mode 100644index 000000000..e912047ea--- /dev/null+++ b/apps/api/drizzle/0047_repair_legacy_auth_ownership.sql@@ -0,0 +1,24 @@+-- An older journal used the same timestamp for a comment-only migration.+-- A new migration must repair those upgrades; changing migration 0015 cannot.+ALTER TABLE "project" ADD COLUMN IF NOT EXISTS "archived_at" timestamp;+--> statement-breakpoint+-- Backfill only keys without a reference from an existing legacy owner. Never+-- reinterpret a non-null reference as a different owner's credential.+UPDATE "apikey" AS k+SET "reference_id" = k."user_id"+FROM "user" AS u+WHERE k."reference_id" IS NULL AND k."user_id" = u."id";+--> statement-breakpoint+-- Ownerless/orphaned credentials cannot meet the ownership invariant and must+-- not remain authenticatable. Valid credentials and their hashes stay intact.+DELETE FROM "apikey" AS k+WHERE k."reference_id" IS NULL+ OR NOT EXISTS (SELECT 1 FROM "user" AS u WHERE u."id" = k."reference_id");+--> statement-breakpoint+ALTER TABLE "apikey" ALTER COLUMN "reference_id" SET NOT NULL;+--> statement-breakpoint+ALTER TABLE "apikey" DROP CONSTRAINT IF EXISTS "apikey_reference_id_user_id_fk";+--> statement-breakpoint+ALTER TABLE "apikey" ADD CONSTRAINT "apikey_reference_id_user_id_fk"+ FOREIGN KEY ("reference_id") REFERENCES "public"."user"("id")+ ON DELETE CASCADE ON UPDATE NO ACTION;diff --git a/apps/api/drizzle/0048_resumable_label_deletion.sql b/apps/api/drizzle/0048_resumable_label_deletion.sqlnew file mode 100644index 000000000..6bf499a8f--- /dev/null+++ b/apps/api/drizzle/0048_resumable_label_deletion.sql@@ -0,0 +1 @@+ALTER TABLE "label" ADD COLUMN "deletion_started_at" timestamp;\ No newline at end of filediff --git a/apps/api/drizzle/0049_label_cascade_index.sql b/apps/api/drizzle/0049_label_cascade_index.sqlnew file mode 100644index 000000000..07819f8be--- /dev/null+++ b/apps/api/drizzle/0049_label_cascade_index.sql@@ -0,0 +1 @@+CREATE INDEX "label_workspace_cascade_idx" ON "label" USING btree ("workspace_id","name","created_at","id") WHERE "label"."task_id" is not null;\ No newline at end of filediff --git a/apps/api/drizzle/0050_resumable_github_import.sql b/apps/api/drizzle/0050_resumable_github_import.sqlnew file mode 100644index 000000000..deaa57ab2--- /dev/null+++ b/apps/api/drizzle/0050_resumable_github_import.sql@@ -0,0 +1,8 @@+CREATE TABLE "github_import" (+ "integration_id" text PRIMARY KEY NOT NULL,+ "run_id" text NOT NULL,+ "state" jsonb NOT NULL,+ "updated_at" timestamp DEFAULT now() NOT NULL+);+--> statement-breakpoint+ALTER TABLE "github_import" ADD CONSTRAINT "github_import_integration_id_integration_id_fk" FOREIGN KEY ("integration_id") REFERENCES "public"."integration"("id") ON DELETE cascade ON UPDATE cascade;\ No newline at end of filediff --git a/apps/api/drizzle/meta/0046_snapshot.json b/apps/api/drizzle/meta/0046_snapshot.jsonnew file mode 100644index 000000000..e5ca3bc4f--- /dev/null+++ b/apps/api/drizzle/meta/0046_snapshot.json@@ -0,0 +1,4416 @@+{+ "id": "79d45579-f6eb-41a9-9c55-9b7dbc20d436",+ "prevId": "b8b6dffe-46c4-4ef5-9dc1-2242cc1fa9ab",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.activity": {+ "name": "activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_name": {+ "name": "external_user_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_avatar": {+ "name": "external_user_avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_source": {+ "name": "external_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_url": {+ "name": "external_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "activity_task_id_idx": {+ "name": "activity_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "activity_userId_idx": {+ "name": "activity_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "activity_task_id_task_id_fk": {+ "name": "activity_task_id_task_id_fk",+ "tableFrom": "activity",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "activity_user_id_user_id_fk": {+ "name": "activity_user_id_user_id_fk",+ "tableFrom": "activity",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "activity_task_external_source_external_url_unique": {+ "name": "activity_task_external_source_external_url_unique",+ "columns": ["task_id", "external_source", "external_url"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 86400000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 10+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "apikey_userId_idx": {+ "name": "apikey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "apikey_reference_id_user_id_fk": {+ "name": "apikey_reference_id_user_id_fk",+ "tableFrom": "apikey",+ "columnsFrom": ["reference_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "apikey_user_id_user_id_fk": {+ "name": "apikey_user_id_user_id_fk",+ "tableFrom": "apikey",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.asset": {+ "name": "asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activity_id": {+ "name": "activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'image'"+ },+ "surface": {+ "name": "surface",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'description'"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "asset_workspaceId_idx": {+ "name": "asset_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "asset_projectId_idx": {+ "name": "asset_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "asset_taskId_idx": {+ "name": "asset_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "asset_activityId_idx": {+ "name": "asset_activityId_idx",+ "columns": [+ {+ "expression": "activity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "asset_createdBy_idx": {+ "name": "asset_createdBy_idx",+ "columns": [+ {+ "expression": "created_by",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "asset_workspace_id_workspace_id_fk": {+ "name": "asset_workspace_id_workspace_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "asset_project_id_project_id_fk": {+ "name": "asset_project_id_project_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "asset_task_id_task_id_fk": {+ "name": "asset_task_id_task_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "asset_activity_id_activity_id_fk": {+ "name": "asset_activity_id_activity_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["activity_id"],+ "tableTo": "activity",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "asset_created_by_user_id_fk": {+ "name": "asset_created_by_user_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["created_by"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "asset_object_key_unique": {+ "name": "asset_object_key_unique",+ "columns": ["object_key"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_event": {+ "name": "billing_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_reminder_sent": {+ "name": "billing_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "billing_reminder_sent_workspaceId_idx": {+ "name": "billing_reminder_sent_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "billing_reminder_sent_userId_idx": {+ "name": "billing_reminder_sent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "billing_reminder_sent_user_id_user_id_fk": {+ "name": "billing_reminder_sent_user_id_user_id_fk",+ "tableFrom": "billing_reminder_sent",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "billing_reminder_sent_workspace_id_workspace_id_fk": {+ "name": "billing_reminder_sent_workspace_id_workspace_id_fk",+ "tableFrom": "billing_reminder_sent",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "billing_reminder_sent_user_type_unique": {+ "name": "billing_reminder_sent_user_type_unique",+ "columns": ["user_id", "reminder_type"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.column": {+ "name": "column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_final": {+ "name": "is_final",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "column_projectId_idx": {+ "name": "column_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "column_project_id_project_id_fk": {+ "name": "column_project_id_project_id_fk",+ "tableFrom": "column",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.comment": {+ "name": "comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "comment_task_idx": {+ "name": "comment_task_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "comment_user_idx": {+ "name": "comment_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "comment_task_id_task_id_fk": {+ "name": "comment_task_id_task_id_fk",+ "tableFrom": "comment",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "comment_user_id_user_id_fk": {+ "name": "comment_user_id_user_id_fk",+ "tableFrom": "comment",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_definition": {+ "name": "custom_field_definition",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "default_value": {+ "name": "default_value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_def_projectId_idx": {+ "name": "custom_field_def_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "custom_field_definition_project_id_project_id_fk": {+ "name": "custom_field_definition_project_id_project_id_fk",+ "tableFrom": "custom_field_definition",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_value": {+ "name": "custom_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_value_taskId_idx": {+ "name": "custom_field_value_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "custom_field_value_fieldId_idx": {+ "name": "custom_field_value_fieldId_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "custom_field_value_task_id_task_id_fk": {+ "name": "custom_field_value_task_id_task_id_fk",+ "tableFrom": "custom_field_value",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "custom_field_value_field_id_custom_field_definition_id_fk": {+ "name": "custom_field_value_field_id_custom_field_definition_id_fk",+ "tableFrom": "custom_field_value",+ "columnsFrom": ["field_id"],+ "tableTo": "custom_field_definition",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_value_task_field_unique": {+ "name": "custom_field_value_task_field_unique",+ "columns": ["task_id", "field_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.device_code": {+ "name": "device_code",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "device_code": {+ "name": "device_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_code": {+ "name": "user_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_polled_at": {+ "name": "last_polled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "polling_interval": {+ "name": "polling_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "device_code_device_code_uidx": {+ "name": "device_code_device_code_uidx",+ "columns": [+ {+ "expression": "device_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "device_code_user_code_uidx": {+ "name": "device_code_user_code_uidx",+ "columns": [+ {+ "expression": "user_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "device_code_user_id_idx": {+ "name": "device_code_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "device_code_user_id_user_id_fk": {+ "name": "device_code_user_id_user_id_fk",+ "tableFrom": "device_code",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_link": {+ "name": "external_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "external_link_taskId_idx": {+ "name": "external_link_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "external_link_integrationId_idx": {+ "name": "external_link_integrationId_idx",+ "columns": [+ {+ "expression": "integration_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "external_link_externalId_idx": {+ "name": "external_link_externalId_idx",+ "columns": [+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "external_link_resourceType_idx": {+ "name": "external_link_resourceType_idx",+ "columns": [+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "external_link_task_id_task_id_fk": {+ "name": "external_link_task_id_task_id_fk",+ "tableFrom": "external_link",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "external_link_integration_id_integration_id_fk": {+ "name": "external_link_integration_id_integration_id_fk",+ "tableFrom": "external_link",+ "columnsFrom": ["integration_id"],+ "tableTo": "integration",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_integration": {+ "name": "github_integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_owner": {+ "name": "repository_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_name": {+ "name": "repository_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installation_id": {+ "name": "installation_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_integration_project_id_project_id_fk": {+ "name": "github_integration_project_id_project_id_fk",+ "tableFrom": "github_integration",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "github_integration_project_id_unique": {+ "name": "github_integration_project_id_unique",+ "columns": ["project_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration": {+ "name": "integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_projectId_idx": {+ "name": "integration_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "integration_type_idx": {+ "name": "integration_type_idx",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "integration_project_id_project_id_fk": {+ "name": "integration_project_id_project_id_fk",+ "tableFrom": "integration",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "integration_project_type_unique": {+ "name": "integration_project_type_unique",+ "columns": ["project_id", "type"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_workspaceId_idx": {+ "name": "invitation_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "invitation_inviterId_idx": {+ "name": "invitation_inviterId_idx",+ "columns": [+ {+ "expression": "inviter_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "invitation_workspace_id_workspace_id_fk": {+ "name": "invitation_workspace_id_workspace_id_fk",+ "tableFrom": "invitation",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "columnsFrom": ["inviter_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.job_lease": {+ "name": "job_lease",+ "schema": "",+ "columns": {+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "label_task_id_idx": {+ "name": "label_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "label_workspace_id_idx": {+ "name": "label_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "label_workspace_name_unique": {+ "name": "label_workspace_name_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "with": {},+ "method": "btree",+ "where": "\"label\".\"task_id\" is null",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "label_task_id_task_id_fk": {+ "name": "label_task_id_task_id_fk",+ "tableFrom": "label",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "label_workspace_id_workspace_id_fk": {+ "name": "label_workspace_id_workspace_id_fk",+ "tableFrom": "label",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_task_name_unique": {+ "name": "label_task_name_unique",+ "columns": ["task_id", "name"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_state": {+ "name": "mcp_oauth_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_state_kind_key_uidx": {+ "name": "mcp_oauth_state_kind_key_uidx",+ "columns": [+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "mcp_oauth_state_expiresAt_idx": {+ "name": "mcp_oauth_state_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "is_read": {+ "name": "is_read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_userId_idx": {+ "name": "notification_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_role": {+ "name": "workspace_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_role_workspaceId_idx": {+ "name": "workspace_role_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "workspace_role_role_idx": {+ "name": "workspace_role_role_idx",+ "columns": [+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "workspace_role_workspace_id_workspace_id_fk": {+ "name": "workspace_role_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_role",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'Layout'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_task_number": {+ "name": "last_task_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {+ "project_workspaceId_position_idx": {+ "name": "project_workspaceId_position_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "project_workspace_id_workspace_id_fk": {+ "name": "project_workspace_id_workspace_id_fk",+ "tableFrom": "project",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_workspace_id_id_unique": {+ "name": "project_workspace_id_id_unique",+ "columns": ["workspace_id", "id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_team_id": {+ "name": "active_team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": ["token"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_relation": {+ "name": "task_relation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "source_task_id": {+ "name": "source_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_task_id": {+ "name": "target_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "relation_type": {+ "name": "relation_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_relation_source_idx": {+ "name": "task_relation_source_idx",+ "columns": [+ {+ "expression": "source_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "task_relation_target_idx": {+ "name": "task_relation_target_idx",+ "columns": [+ {+ "expression": "target_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "task_relation_source_task_id_task_id_fk": {+ "name": "task_relation_source_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "columnsFrom": ["source_task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "task_relation_target_task_id_task_id_fk": {+ "name": "task_relation_target_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "columnsFrom": ["target_task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_reminder_sent": {+ "name": "task_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_reminder_sent_taskId_idx": {+ "name": "task_reminder_sent_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "task_reminder_sent_task_id_task_id_fk": {+ "name": "task_reminder_sent_task_id_task_id_fk",+ "tableFrom": "task_reminder_sent",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_reminder_sent_task_type_unique": {+ "name": "task_reminder_sent_task_type_unique",+ "columns": ["task_id", "reminder_type"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task": {+ "name": "task",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "assignee_id": {+ "name": "assignee_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'to-do'"+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'low'"+ },+ "start_date": {+ "name": "start_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_projectId_idx": {+ "name": "task_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "task_dueDate_idx": {+ "name": "task_dueDate_idx",+ "columns": [+ {+ "expression": "due_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "task_assigneeId_idx": {+ "name": "task_assigneeId_idx",+ "columns": [+ {+ "expression": "assignee_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "task_columnId_idx": {+ "name": "task_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "task_project_id_project_id_fk": {+ "name": "task_project_id_project_id_fk",+ "tableFrom": "task",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "task_assignee_id_user_id_fk": {+ "name": "task_assignee_id_user_id_fk",+ "tableFrom": "task",+ "columnsFrom": ["assignee_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ },+ "task_column_id_column_id_fk": {+ "name": "task_column_id_column_id_fk",+ "tableFrom": "task",+ "columnsFrom": ["column_id"],+ "tableTo": "column",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_project_number_unique": {+ "name": "task_project_number_unique",+ "columns": ["project_id", "number"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_workspaceId_idx": {+ "name": "team_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "teamMember_teamId_idx": {+ "name": "teamMember_teamId_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "teamMember_userId_idx": {+ "name": "teamMember_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "columnsFrom": ["team_id"],+ "tableTo": "team",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.time_entry": {+ "name": "time_entry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "duration": {+ "name": "duration",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "time_entry_taskId_idx": {+ "name": "time_entry_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "time_entry_userId_idx": {+ "name": "time_entry_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "time_entry_task_id_task_id_fk": {+ "name": "time_entry_task_id_task_id_fk",+ "tableFrom": "time_entry",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "time_entry_user_id_user_id_fk": {+ "name": "time_entry_user_id_user_id_fk",+ "tableFrom": "time_entry",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.trial_grant": {+ "name": "trial_grant",+ "schema": "",+ "columns": {+ "email_hash": {+ "name": "email_hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_anonymous": {+ "name": "is_anonymous",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "ban_reason": {+ "name": "ban_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ban_expires": {+ "name": "ban_expires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "columns": ["email"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_avatar": {+ "name": "user_avatar",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "data": {+ "name": "data",+ "type": "bytea",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_avatar_userId_idx": {+ "name": "user_avatar_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "user_avatar_user_id_user_id_fk": {+ "name": "user_avatar_user_id_user_id_fk",+ "tableFrom": "user_avatar",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_avatar_user_id_unique": {+ "name": "user_avatar_user_id_unique",+ "columns": ["user_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_server_url": {+ "name": "ntfy_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_topic": {+ "name": "ntfy_topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_token": {+ "name": "ntfy_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_server_url": {+ "name": "gotify_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_token": {+ "name": "gotify_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_secret": {+ "name": "webhook_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "task_assignment_enabled": {+ "name": "task_assignment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_comment_enabled": {+ "name": "task_comment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_status_change_enabled": {+ "name": "task_status_change_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_enabled": {+ "name": "due_date_reminder_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_lead_time_minutes": {+ "name": "due_date_reminder_lead_time_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1440+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_preference_user_id_unique": {+ "name": "user_notification_preference_user_id_unique",+ "columns": ["user_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_project": {+ "name": "user_notification_workspace_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_rule_id": {+ "name": "workspace_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_project_ruleId_idx": {+ "name": "user_notification_workspace_project_ruleId_idx",+ "columns": [+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "user_notification_workspace_project_projectId_idx": {+ "name": "user_notification_workspace_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "user_notification_workspace_project_workspaceId_projectId_idx": {+ "name": "user_notification_workspace_project_workspaceId_projectId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "unwp_workspaceId_workspaceRuleId_idx": {+ "name": "unwp_workspaceId_workspaceRuleId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "user_notification_workspace_project_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "columnsFrom": ["workspace_id", "workspace_rule_id"],+ "tableTo": "user_notification_workspace_rule",+ "columnsTo": ["workspace_id", "id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "columnsFrom": ["workspace_id", "project_id"],+ "tableTo": "project",+ "columnsTo": ["workspace_id", "id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_project_rule_project_unique": {+ "name": "user_notification_workspace_project_rule_project_unique",+ "columns": ["workspace_rule_id", "project_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_rule": {+ "name": "user_notification_workspace_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "project_mode": {+ "name": "project_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_rule_userId_idx": {+ "name": "user_notification_workspace_rule_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "user_notification_workspace_rule_workspaceId_idx": {+ "name": "user_notification_workspace_rule_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "user_notification_workspace_rule_user_id_user_id_fk": {+ "name": "user_notification_workspace_rule_user_id_user_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "user_notification_workspace_rule_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_rule_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_rule_user_workspace_unique": {+ "name": "user_notification_workspace_rule_user_workspace_unique",+ "columns": ["user_id", "workspace_id"],+ "nullsNotDistinct": false+ },+ "user_notification_workspace_rule_workspace_id_id_unique": {+ "name": "user_notification_workspace_rule_workspace_id_id_unique",+ "columns": ["workspace_id", "id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workflow_rule": {+ "name": "workflow_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_type": {+ "name": "integration_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workflow_rule_projectId_idx": {+ "name": "workflow_rule_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "workflow_rule_columnId_idx": {+ "name": "workflow_rule_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "workflow_rule_project_id_project_id_fk": {+ "name": "workflow_rule_project_id_project_id_fk",+ "tableFrom": "workflow_rule",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "workflow_rule_column_id_column_id_fk": {+ "name": "workflow_rule_column_id_column_id_fk",+ "tableFrom": "workflow_rule",+ "columnsFrom": ["column_id"],+ "tableTo": "column",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "columns": ["slug"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_billing": {+ "name": "workspace_billing",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "founding_free": {+ "name": "founding_free",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "creem_customer_id": {+ "name": "creem_customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_subscription_id": {+ "name": "creem_subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_product_id": {+ "name": "creem_product_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "billing_interval": {+ "name": "billing_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "seats": {+ "name": "seats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "canceled_at": {+ "name": "canceled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_billing_workspaceId_idx": {+ "name": "workspace_billing_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "workspace_billing_workspace_id_workspace_id_fk": {+ "name": "workspace_billing_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_billing",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_billing_workspace_id_unique": {+ "name": "workspace_billing_workspace_id_unique",+ "columns": ["workspace_id"],+ "nullsNotDistinct": false+ },+ "workspace_billing_creem_subscription_id_unique": {+ "name": "workspace_billing_creem_subscription_id_unique",+ "columns": ["creem_subscription_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member": {+ "name": "workspace_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "joined_at": {+ "name": "joined_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "workspace_member_workspaceId_idx": {+ "name": "workspace_member_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "workspace_member_userId_idx": {+ "name": "workspace_member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "workspace_member_workspace_id_workspace_id_fk": {+ "name": "workspace_member_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "workspace_member_user_id_user_id_fk": {+ "name": "workspace_member_user_id_user_id_fk",+ "tableFrom": "workspace_member",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "views": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/apps/api/drizzle/meta/0047_snapshot.json b/apps/api/drizzle/meta/0047_snapshot.jsonnew file mode 100644index 000000000..6b6f7ecd5--- /dev/null+++ b/apps/api/drizzle/meta/0047_snapshot.json@@ -0,0 +1,4416 @@+{+ "id": "42dfe85b-7a06-41ee-bfcb-a133057afee0",+ "prevId": "79d45579-f6eb-41a9-9c55-9b7dbc20d436",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.activity": {+ "name": "activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_name": {+ "name": "external_user_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_avatar": {+ "name": "external_user_avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_source": {+ "name": "external_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_url": {+ "name": "external_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "activity_task_id_idx": {+ "name": "activity_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "activity_userId_idx": {+ "name": "activity_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "activity_task_id_task_id_fk": {+ "name": "activity_task_id_task_id_fk",+ "tableFrom": "activity",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "activity_user_id_user_id_fk": {+ "name": "activity_user_id_user_id_fk",+ "tableFrom": "activity",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "activity_task_external_source_external_url_unique": {+ "name": "activity_task_external_source_external_url_unique",+ "columns": ["task_id", "external_source", "external_url"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 86400000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 10+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "apikey_userId_idx": {+ "name": "apikey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "apikey_reference_id_user_id_fk": {+ "name": "apikey_reference_id_user_id_fk",+ "tableFrom": "apikey",+ "columnsFrom": ["reference_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "apikey_user_id_user_id_fk": {+ "name": "apikey_user_id_user_id_fk",+ "tableFrom": "apikey",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.asset": {+ "name": "asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activity_id": {+ "name": "activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'image'"+ },+ "surface": {+ "name": "surface",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'description'"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "asset_workspaceId_idx": {+ "name": "asset_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "asset_projectId_idx": {+ "name": "asset_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "asset_taskId_idx": {+ "name": "asset_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "asset_activityId_idx": {+ "name": "asset_activityId_idx",+ "columns": [+ {+ "expression": "activity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "asset_createdBy_idx": {+ "name": "asset_createdBy_idx",+ "columns": [+ {+ "expression": "created_by",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "asset_workspace_id_workspace_id_fk": {+ "name": "asset_workspace_id_workspace_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "asset_project_id_project_id_fk": {+ "name": "asset_project_id_project_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "asset_task_id_task_id_fk": {+ "name": "asset_task_id_task_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "asset_activity_id_activity_id_fk": {+ "name": "asset_activity_id_activity_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["activity_id"],+ "tableTo": "activity",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "asset_created_by_user_id_fk": {+ "name": "asset_created_by_user_id_fk",+ "tableFrom": "asset",+ "columnsFrom": ["created_by"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "asset_object_key_unique": {+ "name": "asset_object_key_unique",+ "columns": ["object_key"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_event": {+ "name": "billing_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_reminder_sent": {+ "name": "billing_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "billing_reminder_sent_workspaceId_idx": {+ "name": "billing_reminder_sent_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "billing_reminder_sent_userId_idx": {+ "name": "billing_reminder_sent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "billing_reminder_sent_user_id_user_id_fk": {+ "name": "billing_reminder_sent_user_id_user_id_fk",+ "tableFrom": "billing_reminder_sent",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "billing_reminder_sent_workspace_id_workspace_id_fk": {+ "name": "billing_reminder_sent_workspace_id_workspace_id_fk",+ "tableFrom": "billing_reminder_sent",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "billing_reminder_sent_user_type_unique": {+ "name": "billing_reminder_sent_user_type_unique",+ "columns": ["user_id", "reminder_type"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.column": {+ "name": "column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_final": {+ "name": "is_final",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "column_projectId_idx": {+ "name": "column_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "column_project_id_project_id_fk": {+ "name": "column_project_id_project_id_fk",+ "tableFrom": "column",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.comment": {+ "name": "comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "comment_task_idx": {+ "name": "comment_task_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "comment_user_idx": {+ "name": "comment_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "comment_task_id_task_id_fk": {+ "name": "comment_task_id_task_id_fk",+ "tableFrom": "comment",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "comment_user_id_user_id_fk": {+ "name": "comment_user_id_user_id_fk",+ "tableFrom": "comment",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_definition": {+ "name": "custom_field_definition",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "default_value": {+ "name": "default_value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_def_projectId_idx": {+ "name": "custom_field_def_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "custom_field_definition_project_id_project_id_fk": {+ "name": "custom_field_definition_project_id_project_id_fk",+ "tableFrom": "custom_field_definition",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_value": {+ "name": "custom_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_value_taskId_idx": {+ "name": "custom_field_value_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "custom_field_value_fieldId_idx": {+ "name": "custom_field_value_fieldId_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "custom_field_value_task_id_task_id_fk": {+ "name": "custom_field_value_task_id_task_id_fk",+ "tableFrom": "custom_field_value",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "custom_field_value_field_id_custom_field_definition_id_fk": {+ "name": "custom_field_value_field_id_custom_field_definition_id_fk",+ "tableFrom": "custom_field_value",+ "columnsFrom": ["field_id"],+ "tableTo": "custom_field_definition",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_value_task_field_unique": {+ "name": "custom_field_value_task_field_unique",+ "columns": ["task_id", "field_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.device_code": {+ "name": "device_code",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "device_code": {+ "name": "device_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_code": {+ "name": "user_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_polled_at": {+ "name": "last_polled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "polling_interval": {+ "name": "polling_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "device_code_device_code_uidx": {+ "name": "device_code_device_code_uidx",+ "columns": [+ {+ "expression": "device_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "device_code_user_code_uidx": {+ "name": "device_code_user_code_uidx",+ "columns": [+ {+ "expression": "user_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "device_code_user_id_idx": {+ "name": "device_code_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "device_code_user_id_user_id_fk": {+ "name": "device_code_user_id_user_id_fk",+ "tableFrom": "device_code",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_link": {+ "name": "external_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "external_link_taskId_idx": {+ "name": "external_link_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "external_link_integrationId_idx": {+ "name": "external_link_integrationId_idx",+ "columns": [+ {+ "expression": "integration_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "external_link_externalId_idx": {+ "name": "external_link_externalId_idx",+ "columns": [+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "external_link_resourceType_idx": {+ "name": "external_link_resourceType_idx",+ "columns": [+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "external_link_task_id_task_id_fk": {+ "name": "external_link_task_id_task_id_fk",+ "tableFrom": "external_link",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "external_link_integration_id_integration_id_fk": {+ "name": "external_link_integration_id_integration_id_fk",+ "tableFrom": "external_link",+ "columnsFrom": ["integration_id"],+ "tableTo": "integration",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_integration": {+ "name": "github_integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_owner": {+ "name": "repository_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_name": {+ "name": "repository_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installation_id": {+ "name": "installation_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_integration_project_id_project_id_fk": {+ "name": "github_integration_project_id_project_id_fk",+ "tableFrom": "github_integration",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "github_integration_project_id_unique": {+ "name": "github_integration_project_id_unique",+ "columns": ["project_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration": {+ "name": "integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_projectId_idx": {+ "name": "integration_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "integration_type_idx": {+ "name": "integration_type_idx",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "integration_project_id_project_id_fk": {+ "name": "integration_project_id_project_id_fk",+ "tableFrom": "integration",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "integration_project_type_unique": {+ "name": "integration_project_type_unique",+ "columns": ["project_id", "type"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_workspaceId_idx": {+ "name": "invitation_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "invitation_inviterId_idx": {+ "name": "invitation_inviterId_idx",+ "columns": [+ {+ "expression": "inviter_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "invitation_workspace_id_workspace_id_fk": {+ "name": "invitation_workspace_id_workspace_id_fk",+ "tableFrom": "invitation",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "columnsFrom": ["inviter_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.job_lease": {+ "name": "job_lease",+ "schema": "",+ "columns": {+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "label_task_id_idx": {+ "name": "label_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "label_workspace_id_idx": {+ "name": "label_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "label_workspace_name_unique": {+ "name": "label_workspace_name_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "with": {},+ "method": "btree",+ "where": "\"label\".\"task_id\" is null",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "label_task_id_task_id_fk": {+ "name": "label_task_id_task_id_fk",+ "tableFrom": "label",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "label_workspace_id_workspace_id_fk": {+ "name": "label_workspace_id_workspace_id_fk",+ "tableFrom": "label",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_task_name_unique": {+ "name": "label_task_name_unique",+ "columns": ["task_id", "name"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_state": {+ "name": "mcp_oauth_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_state_kind_key_uidx": {+ "name": "mcp_oauth_state_kind_key_uidx",+ "columns": [+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "mcp_oauth_state_expiresAt_idx": {+ "name": "mcp_oauth_state_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "is_read": {+ "name": "is_read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_userId_idx": {+ "name": "notification_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_role": {+ "name": "workspace_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_role_workspaceId_idx": {+ "name": "workspace_role_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "workspace_role_role_idx": {+ "name": "workspace_role_role_idx",+ "columns": [+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "workspace_role_workspace_id_workspace_id_fk": {+ "name": "workspace_role_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_role",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'Layout'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_task_number": {+ "name": "last_task_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {+ "project_workspaceId_position_idx": {+ "name": "project_workspaceId_position_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "project_workspace_id_workspace_id_fk": {+ "name": "project_workspace_id_workspace_id_fk",+ "tableFrom": "project",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_workspace_id_id_unique": {+ "name": "project_workspace_id_id_unique",+ "columns": ["workspace_id", "id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_team_id": {+ "name": "active_team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "columns": ["token"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_relation": {+ "name": "task_relation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "source_task_id": {+ "name": "source_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_task_id": {+ "name": "target_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "relation_type": {+ "name": "relation_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_relation_source_idx": {+ "name": "task_relation_source_idx",+ "columns": [+ {+ "expression": "source_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "task_relation_target_idx": {+ "name": "task_relation_target_idx",+ "columns": [+ {+ "expression": "target_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "task_relation_source_task_id_task_id_fk": {+ "name": "task_relation_source_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "columnsFrom": ["source_task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "task_relation_target_task_id_task_id_fk": {+ "name": "task_relation_target_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "columnsFrom": ["target_task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_reminder_sent": {+ "name": "task_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_reminder_sent_taskId_idx": {+ "name": "task_reminder_sent_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "task_reminder_sent_task_id_task_id_fk": {+ "name": "task_reminder_sent_task_id_task_id_fk",+ "tableFrom": "task_reminder_sent",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_reminder_sent_task_type_unique": {+ "name": "task_reminder_sent_task_type_unique",+ "columns": ["task_id", "reminder_type"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task": {+ "name": "task",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "assignee_id": {+ "name": "assignee_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'to-do'"+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'low'"+ },+ "start_date": {+ "name": "start_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_projectId_idx": {+ "name": "task_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "task_dueDate_idx": {+ "name": "task_dueDate_idx",+ "columns": [+ {+ "expression": "due_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "task_assigneeId_idx": {+ "name": "task_assigneeId_idx",+ "columns": [+ {+ "expression": "assignee_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "task_columnId_idx": {+ "name": "task_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "task_project_id_project_id_fk": {+ "name": "task_project_id_project_id_fk",+ "tableFrom": "task",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "task_assignee_id_user_id_fk": {+ "name": "task_assignee_id_user_id_fk",+ "tableFrom": "task",+ "columnsFrom": ["assignee_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ },+ "task_column_id_column_id_fk": {+ "name": "task_column_id_column_id_fk",+ "tableFrom": "task",+ "columnsFrom": ["column_id"],+ "tableTo": "column",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_project_number_unique": {+ "name": "task_project_number_unique",+ "columns": ["project_id", "number"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_workspaceId_idx": {+ "name": "team_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "teamMember_teamId_idx": {+ "name": "teamMember_teamId_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "teamMember_userId_idx": {+ "name": "teamMember_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "columnsFrom": ["team_id"],+ "tableTo": "team",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.time_entry": {+ "name": "time_entry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "duration": {+ "name": "duration",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "time_entry_taskId_idx": {+ "name": "time_entry_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "time_entry_userId_idx": {+ "name": "time_entry_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "time_entry_task_id_task_id_fk": {+ "name": "time_entry_task_id_task_id_fk",+ "tableFrom": "time_entry",+ "columnsFrom": ["task_id"],+ "tableTo": "task",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "time_entry_user_id_user_id_fk": {+ "name": "time_entry_user_id_user_id_fk",+ "tableFrom": "time_entry",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.trial_grant": {+ "name": "trial_grant",+ "schema": "",+ "columns": {+ "email_hash": {+ "name": "email_hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_anonymous": {+ "name": "is_anonymous",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "ban_reason": {+ "name": "ban_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ban_expires": {+ "name": "ban_expires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "columns": ["email"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_avatar": {+ "name": "user_avatar",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "data": {+ "name": "data",+ "type": "bytea",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_avatar_userId_idx": {+ "name": "user_avatar_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "user_avatar_user_id_user_id_fk": {+ "name": "user_avatar_user_id_user_id_fk",+ "tableFrom": "user_avatar",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_avatar_user_id_unique": {+ "name": "user_avatar_user_id_unique",+ "columns": ["user_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_server_url": {+ "name": "ntfy_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_topic": {+ "name": "ntfy_topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_token": {+ "name": "ntfy_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_server_url": {+ "name": "gotify_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_token": {+ "name": "gotify_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_secret": {+ "name": "webhook_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "task_assignment_enabled": {+ "name": "task_assignment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_comment_enabled": {+ "name": "task_comment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_status_change_enabled": {+ "name": "task_status_change_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_enabled": {+ "name": "due_date_reminder_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_lead_time_minutes": {+ "name": "due_date_reminder_lead_time_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1440+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_preference_user_id_unique": {+ "name": "user_notification_preference_user_id_unique",+ "columns": ["user_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_project": {+ "name": "user_notification_workspace_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_rule_id": {+ "name": "workspace_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_project_ruleId_idx": {+ "name": "user_notification_workspace_project_ruleId_idx",+ "columns": [+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "user_notification_workspace_project_projectId_idx": {+ "name": "user_notification_workspace_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "user_notification_workspace_project_workspaceId_projectId_idx": {+ "name": "user_notification_workspace_project_workspaceId_projectId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "unwp_workspaceId_workspaceRuleId_idx": {+ "name": "unwp_workspaceId_workspaceRuleId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "user_notification_workspace_project_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "columnsFrom": ["workspace_id", "workspace_rule_id"],+ "tableTo": "user_notification_workspace_rule",+ "columnsTo": ["workspace_id", "id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "columnsFrom": ["workspace_id", "project_id"],+ "tableTo": "project",+ "columnsTo": ["workspace_id", "id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_project_rule_project_unique": {+ "name": "user_notification_workspace_project_rule_project_unique",+ "columns": ["workspace_rule_id", "project_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_rule": {+ "name": "user_notification_workspace_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "project_mode": {+ "name": "project_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_rule_userId_idx": {+ "name": "user_notification_workspace_rule_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "user_notification_workspace_rule_workspaceId_idx": {+ "name": "user_notification_workspace_rule_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "user_notification_workspace_rule_user_id_user_id_fk": {+ "name": "user_notification_workspace_rule_user_id_user_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "user_notification_workspace_rule_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_rule_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_rule_user_workspace_unique": {+ "name": "user_notification_workspace_rule_user_workspace_unique",+ "columns": ["user_id", "workspace_id"],+ "nullsNotDistinct": false+ },+ "user_notification_workspace_rule_workspace_id_id_unique": {+ "name": "user_notification_workspace_rule_workspace_id_id_unique",+ "columns": ["workspace_id", "id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workflow_rule": {+ "name": "workflow_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_type": {+ "name": "integration_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workflow_rule_projectId_idx": {+ "name": "workflow_rule_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "workflow_rule_columnId_idx": {+ "name": "workflow_rule_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "workflow_rule_project_id_project_id_fk": {+ "name": "workflow_rule_project_id_project_id_fk",+ "tableFrom": "workflow_rule",+ "columnsFrom": ["project_id"],+ "tableTo": "project",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ },+ "workflow_rule_column_id_column_id_fk": {+ "name": "workflow_rule_column_id_column_id_fk",+ "tableFrom": "workflow_rule",+ "columnsFrom": ["column_id"],+ "tableTo": "column",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "columns": ["slug"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_billing": {+ "name": "workspace_billing",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "founding_free": {+ "name": "founding_free",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "creem_customer_id": {+ "name": "creem_customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_subscription_id": {+ "name": "creem_subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_product_id": {+ "name": "creem_product_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "billing_interval": {+ "name": "billing_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "seats": {+ "name": "seats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "canceled_at": {+ "name": "canceled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_billing_workspaceId_idx": {+ "name": "workspace_billing_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "workspace_billing_workspace_id_workspace_id_fk": {+ "name": "workspace_billing_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_billing",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "cascade",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_billing_workspace_id_unique": {+ "name": "workspace_billing_workspace_id_unique",+ "columns": ["workspace_id"],+ "nullsNotDistinct": false+ },+ "workspace_billing_creem_subscription_id_unique": {+ "name": "workspace_billing_creem_subscription_id_unique",+ "columns": ["creem_subscription_id"],+ "nullsNotDistinct": false+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member": {+ "name": "workspace_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "joined_at": {+ "name": "joined_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "workspace_member_workspaceId_idx": {+ "name": "workspace_member_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ },+ "workspace_member_userId_idx": {+ "name": "workspace_member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "with": {},+ "method": "btree",+ "concurrently": false+ }+ },+ "foreignKeys": {+ "workspace_member_workspace_id_workspace_id_fk": {+ "name": "workspace_member_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member",+ "columnsFrom": ["workspace_id"],+ "tableTo": "workspace",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ },+ "workspace_member_user_id_user_id_fk": {+ "name": "workspace_member_user_id_user_id_fk",+ "tableFrom": "workspace_member",+ "columnsFrom": ["user_id"],+ "tableTo": "user",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "views": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/apps/api/drizzle/meta/0048_snapshot.json b/apps/api/drizzle/meta/0048_snapshot.jsonnew file mode 100644index 000000000..afa31bc1b--- /dev/null+++ b/apps/api/drizzle/meta/0048_snapshot.json@@ -0,0 +1,4422 @@+{+ "id": "fa488353-84ad-4f0f-b69d-e893cb5fbff2",+ "prevId": "42dfe85b-7a06-41ee-bfcb-a133057afee0",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.activity": {+ "name": "activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_name": {+ "name": "external_user_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_avatar": {+ "name": "external_user_avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_source": {+ "name": "external_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_url": {+ "name": "external_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "activity_task_id_idx": {+ "name": "activity_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_userId_idx": {+ "name": "activity_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "activity_task_id_task_id_fk": {+ "name": "activity_task_id_task_id_fk",+ "tableFrom": "activity",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "activity_user_id_user_id_fk": {+ "name": "activity_user_id_user_id_fk",+ "tableFrom": "activity",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "activity_task_external_source_external_url_unique": {+ "name": "activity_task_external_source_external_url_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "external_source", "external_url"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 86400000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 10+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_userId_idx": {+ "name": "apikey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "apikey_reference_id_user_id_fk": {+ "name": "apikey_reference_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": ["reference_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "apikey_user_id_user_id_fk": {+ "name": "apikey_user_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.asset": {+ "name": "asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activity_id": {+ "name": "activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'image'"+ },+ "surface": {+ "name": "surface",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'description'"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "asset_workspaceId_idx": {+ "name": "asset_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_projectId_idx": {+ "name": "asset_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_taskId_idx": {+ "name": "asset_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_activityId_idx": {+ "name": "asset_activityId_idx",+ "columns": [+ {+ "expression": "activity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_createdBy_idx": {+ "name": "asset_createdBy_idx",+ "columns": [+ {+ "expression": "created_by",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "asset_workspace_id_workspace_id_fk": {+ "name": "asset_workspace_id_workspace_id_fk",+ "tableFrom": "asset",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_project_id_project_id_fk": {+ "name": "asset_project_id_project_id_fk",+ "tableFrom": "asset",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_task_id_task_id_fk": {+ "name": "asset_task_id_task_id_fk",+ "tableFrom": "asset",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_activity_id_activity_id_fk": {+ "name": "asset_activity_id_activity_id_fk",+ "tableFrom": "asset",+ "tableTo": "activity",+ "columnsFrom": ["activity_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_created_by_user_id_fk": {+ "name": "asset_created_by_user_id_fk",+ "tableFrom": "asset",+ "tableTo": "user",+ "columnsFrom": ["created_by"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "asset_object_key_unique": {+ "name": "asset_object_key_unique",+ "nullsNotDistinct": false,+ "columns": ["object_key"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_event": {+ "name": "billing_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_reminder_sent": {+ "name": "billing_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "billing_reminder_sent_workspaceId_idx": {+ "name": "billing_reminder_sent_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "billing_reminder_sent_userId_idx": {+ "name": "billing_reminder_sent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "billing_reminder_sent_user_id_user_id_fk": {+ "name": "billing_reminder_sent_user_id_user_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "billing_reminder_sent_workspace_id_workspace_id_fk": {+ "name": "billing_reminder_sent_workspace_id_workspace_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "billing_reminder_sent_user_type_unique": {+ "name": "billing_reminder_sent_user_type_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id", "reminder_type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.column": {+ "name": "column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_final": {+ "name": "is_final",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "column_projectId_idx": {+ "name": "column_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "column_project_id_project_id_fk": {+ "name": "column_project_id_project_id_fk",+ "tableFrom": "column",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.comment": {+ "name": "comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "comment_task_idx": {+ "name": "comment_task_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "comment_user_idx": {+ "name": "comment_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "comment_task_id_task_id_fk": {+ "name": "comment_task_id_task_id_fk",+ "tableFrom": "comment",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "comment_user_id_user_id_fk": {+ "name": "comment_user_id_user_id_fk",+ "tableFrom": "comment",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_definition": {+ "name": "custom_field_definition",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "default_value": {+ "name": "default_value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_def_projectId_idx": {+ "name": "custom_field_def_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_definition_project_id_project_id_fk": {+ "name": "custom_field_definition_project_id_project_id_fk",+ "tableFrom": "custom_field_definition",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_value": {+ "name": "custom_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_value_taskId_idx": {+ "name": "custom_field_value_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "custom_field_value_fieldId_idx": {+ "name": "custom_field_value_fieldId_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_value_task_id_task_id_fk": {+ "name": "custom_field_value_task_id_task_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "custom_field_value_field_id_custom_field_definition_id_fk": {+ "name": "custom_field_value_field_id_custom_field_definition_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "custom_field_definition",+ "columnsFrom": ["field_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_value_task_field_unique": {+ "name": "custom_field_value_task_field_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "field_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.device_code": {+ "name": "device_code",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "device_code": {+ "name": "device_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_code": {+ "name": "user_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_polled_at": {+ "name": "last_polled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "polling_interval": {+ "name": "polling_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "device_code_device_code_uidx": {+ "name": "device_code_device_code_uidx",+ "columns": [+ {+ "expression": "device_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_code_uidx": {+ "name": "device_code_user_code_uidx",+ "columns": [+ {+ "expression": "user_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_id_idx": {+ "name": "device_code_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "device_code_user_id_user_id_fk": {+ "name": "device_code_user_id_user_id_fk",+ "tableFrom": "device_code",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_link": {+ "name": "external_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "external_link_taskId_idx": {+ "name": "external_link_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_integrationId_idx": {+ "name": "external_link_integrationId_idx",+ "columns": [+ {+ "expression": "integration_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_externalId_idx": {+ "name": "external_link_externalId_idx",+ "columns": [+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_resourceType_idx": {+ "name": "external_link_resourceType_idx",+ "columns": [+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "external_link_task_id_task_id_fk": {+ "name": "external_link_task_id_task_id_fk",+ "tableFrom": "external_link",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "external_link_integration_id_integration_id_fk": {+ "name": "external_link_integration_id_integration_id_fk",+ "tableFrom": "external_link",+ "tableTo": "integration",+ "columnsFrom": ["integration_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_integration": {+ "name": "github_integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_owner": {+ "name": "repository_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_name": {+ "name": "repository_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installation_id": {+ "name": "installation_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_integration_project_id_project_id_fk": {+ "name": "github_integration_project_id_project_id_fk",+ "tableFrom": "github_integration",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "github_integration_project_id_unique": {+ "name": "github_integration_project_id_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration": {+ "name": "integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_projectId_idx": {+ "name": "integration_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "integration_type_idx": {+ "name": "integration_type_idx",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_project_id_project_id_fk": {+ "name": "integration_project_id_project_id_fk",+ "tableFrom": "integration",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "integration_project_type_unique": {+ "name": "integration_project_type_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id", "type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_workspaceId_idx": {+ "name": "invitation_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_inviterId_idx": {+ "name": "invitation_inviterId_idx",+ "columns": [+ {+ "expression": "inviter_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_workspace_id_workspace_id_fk": {+ "name": "invitation_workspace_id_workspace_id_fk",+ "tableFrom": "invitation",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": ["inviter_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.job_lease": {+ "name": "job_lease",+ "schema": "",+ "columns": {+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "deletion_started_at": {+ "name": "deletion_started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "label_task_id_idx": {+ "name": "label_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_id_idx": {+ "name": "label_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_name_unique": {+ "name": "label_workspace_name_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"label\".\"task_id\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "label_task_id_task_id_fk": {+ "name": "label_task_id_task_id_fk",+ "tableFrom": "label",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "label_workspace_id_workspace_id_fk": {+ "name": "label_workspace_id_workspace_id_fk",+ "tableFrom": "label",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_task_name_unique": {+ "name": "label_task_name_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "name"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_state": {+ "name": "mcp_oauth_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_state_kind_key_uidx": {+ "name": "mcp_oauth_state_kind_key_uidx",+ "columns": [+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_state_expiresAt_idx": {+ "name": "mcp_oauth_state_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "is_read": {+ "name": "is_read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_userId_idx": {+ "name": "notification_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_role": {+ "name": "workspace_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_role_workspaceId_idx": {+ "name": "workspace_role_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_role_role_idx": {+ "name": "workspace_role_role_idx",+ "columns": [+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_role_workspace_id_workspace_id_fk": {+ "name": "workspace_role_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_role",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'Layout'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_task_number": {+ "name": "last_task_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {+ "project_workspaceId_position_idx": {+ "name": "project_workspaceId_position_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_workspace_id_workspace_id_fk": {+ "name": "project_workspace_id_workspace_id_fk",+ "tableFrom": "project",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_workspace_id_id_unique": {+ "name": "project_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id", "id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_team_id": {+ "name": "active_team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": ["token"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_relation": {+ "name": "task_relation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "source_task_id": {+ "name": "source_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_task_id": {+ "name": "target_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "relation_type": {+ "name": "relation_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_relation_source_idx": {+ "name": "task_relation_source_idx",+ "columns": [+ {+ "expression": "source_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_relation_target_idx": {+ "name": "task_relation_target_idx",+ "columns": [+ {+ "expression": "target_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_relation_source_task_id_task_id_fk": {+ "name": "task_relation_source_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": ["source_task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_relation_target_task_id_task_id_fk": {+ "name": "task_relation_target_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": ["target_task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_reminder_sent": {+ "name": "task_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_reminder_sent_taskId_idx": {+ "name": "task_reminder_sent_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_reminder_sent_task_id_task_id_fk": {+ "name": "task_reminder_sent_task_id_task_id_fk",+ "tableFrom": "task_reminder_sent",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_reminder_sent_task_type_unique": {+ "name": "task_reminder_sent_task_type_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "reminder_type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task": {+ "name": "task",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "assignee_id": {+ "name": "assignee_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'to-do'"+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'low'"+ },+ "start_date": {+ "name": "start_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_projectId_idx": {+ "name": "task_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_dueDate_idx": {+ "name": "task_dueDate_idx",+ "columns": [+ {+ "expression": "due_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_assigneeId_idx": {+ "name": "task_assigneeId_idx",+ "columns": [+ {+ "expression": "assignee_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_columnId_idx": {+ "name": "task_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_project_id_project_id_fk": {+ "name": "task_project_id_project_id_fk",+ "tableFrom": "task",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_assignee_id_user_id_fk": {+ "name": "task_assignee_id_user_id_fk",+ "tableFrom": "task",+ "tableTo": "user",+ "columnsFrom": ["assignee_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "task_column_id_column_id_fk": {+ "name": "task_column_id_column_id_fk",+ "tableFrom": "task",+ "tableTo": "column",+ "columnsFrom": ["column_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_project_number_unique": {+ "name": "task_project_number_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id", "number"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_workspaceId_idx": {+ "name": "team_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "teamMember_teamId_idx": {+ "name": "teamMember_teamId_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "teamMember_userId_idx": {+ "name": "teamMember_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "tableTo": "team",+ "columnsFrom": ["team_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.time_entry": {+ "name": "time_entry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "duration": {+ "name": "duration",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "time_entry_taskId_idx": {+ "name": "time_entry_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "time_entry_userId_idx": {+ "name": "time_entry_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "time_entry_task_id_task_id_fk": {+ "name": "time_entry_task_id_task_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "time_entry_user_id_user_id_fk": {+ "name": "time_entry_user_id_user_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.trial_grant": {+ "name": "trial_grant",+ "schema": "",+ "columns": {+ "email_hash": {+ "name": "email_hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_anonymous": {+ "name": "is_anonymous",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "ban_reason": {+ "name": "ban_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ban_expires": {+ "name": "ban_expires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": ["email"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_avatar": {+ "name": "user_avatar",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "data": {+ "name": "data",+ "type": "bytea",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_avatar_userId_idx": {+ "name": "user_avatar_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_avatar_user_id_user_id_fk": {+ "name": "user_avatar_user_id_user_id_fk",+ "tableFrom": "user_avatar",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_avatar_user_id_unique": {+ "name": "user_avatar_user_id_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_server_url": {+ "name": "ntfy_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_topic": {+ "name": "ntfy_topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_token": {+ "name": "ntfy_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_server_url": {+ "name": "gotify_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_token": {+ "name": "gotify_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_secret": {+ "name": "webhook_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "task_assignment_enabled": {+ "name": "task_assignment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_comment_enabled": {+ "name": "task_comment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_status_change_enabled": {+ "name": "task_status_change_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_enabled": {+ "name": "due_date_reminder_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_lead_time_minutes": {+ "name": "due_date_reminder_lead_time_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1440+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_preference_user_id_unique": {+ "name": "user_notification_preference_user_id_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_project": {+ "name": "user_notification_workspace_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_rule_id": {+ "name": "workspace_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_project_ruleId_idx": {+ "name": "user_notification_workspace_project_ruleId_idx",+ "columns": [+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_projectId_idx": {+ "name": "user_notification_workspace_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_workspaceId_projectId_idx": {+ "name": "user_notification_workspace_project_workspaceId_projectId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "unwp_workspaceId_workspaceRuleId_idx": {+ "name": "unwp_workspaceId_workspaceRuleId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_project_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "user_notification_workspace_rule",+ "columnsFrom": ["workspace_id", "workspace_rule_id"],+ "columnsTo": ["workspace_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "project",+ "columnsFrom": ["workspace_id", "project_id"],+ "columnsTo": ["workspace_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_project_rule_project_unique": {+ "name": "user_notification_workspace_project_rule_project_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_rule_id", "project_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_rule": {+ "name": "user_notification_workspace_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "project_mode": {+ "name": "project_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_rule_userId_idx": {+ "name": "user_notification_workspace_rule_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_rule_workspaceId_idx": {+ "name": "user_notification_workspace_rule_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_rule_user_id_user_id_fk": {+ "name": "user_notification_workspace_rule_user_id_user_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_rule_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_rule_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_rule_user_workspace_unique": {+ "name": "user_notification_workspace_rule_user_workspace_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id", "workspace_id"]+ },+ "user_notification_workspace_rule_workspace_id_id_unique": {+ "name": "user_notification_workspace_rule_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id", "id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workflow_rule": {+ "name": "workflow_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_type": {+ "name": "integration_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workflow_rule_projectId_idx": {+ "name": "workflow_rule_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workflow_rule_columnId_idx": {+ "name": "workflow_rule_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workflow_rule_project_id_project_id_fk": {+ "name": "workflow_rule_project_id_project_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "workflow_rule_column_id_column_id_fk": {+ "name": "workflow_rule_column_id_column_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "column",+ "columnsFrom": ["column_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "nullsNotDistinct": false,+ "columns": ["slug"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_billing": {+ "name": "workspace_billing",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "founding_free": {+ "name": "founding_free",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "creem_customer_id": {+ "name": "creem_customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_subscription_id": {+ "name": "creem_subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_product_id": {+ "name": "creem_product_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "billing_interval": {+ "name": "billing_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "seats": {+ "name": "seats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "canceled_at": {+ "name": "canceled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_billing_workspaceId_idx": {+ "name": "workspace_billing_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_billing_workspace_id_workspace_id_fk": {+ "name": "workspace_billing_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_billing",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_billing_workspace_id_unique": {+ "name": "workspace_billing_workspace_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id"]+ },+ "workspace_billing_creem_subscription_id_unique": {+ "name": "workspace_billing_creem_subscription_id_unique",+ "nullsNotDistinct": false,+ "columns": ["creem_subscription_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member": {+ "name": "workspace_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "joined_at": {+ "name": "joined_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "workspace_member_workspaceId_idx": {+ "name": "workspace_member_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_member_userId_idx": {+ "name": "workspace_member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_workspace_id_workspace_id_fk": {+ "name": "workspace_member_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_user_id_user_id_fk": {+ "name": "workspace_member_user_id_user_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/apps/api/drizzle/meta/0049_snapshot.json b/apps/api/drizzle/meta/0049_snapshot.jsonnew file mode 100644index 000000000..76b16ee59--- /dev/null+++ b/apps/api/drizzle/meta/0049_snapshot.json@@ -0,0 +1,4456 @@+{+ "id": "330dc3f0-66d6-4ebb-bfd5-0e40aac5a651",+ "prevId": "fa488353-84ad-4f0f-b69d-e893cb5fbff2",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.activity": {+ "name": "activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_name": {+ "name": "external_user_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_avatar": {+ "name": "external_user_avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_source": {+ "name": "external_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_url": {+ "name": "external_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "activity_task_id_idx": {+ "name": "activity_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_userId_idx": {+ "name": "activity_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "activity_task_id_task_id_fk": {+ "name": "activity_task_id_task_id_fk",+ "tableFrom": "activity",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "activity_user_id_user_id_fk": {+ "name": "activity_user_id_user_id_fk",+ "tableFrom": "activity",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "activity_task_external_source_external_url_unique": {+ "name": "activity_task_external_source_external_url_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "external_source", "external_url"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 86400000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 10+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_userId_idx": {+ "name": "apikey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "apikey_reference_id_user_id_fk": {+ "name": "apikey_reference_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": ["reference_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "apikey_user_id_user_id_fk": {+ "name": "apikey_user_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.asset": {+ "name": "asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activity_id": {+ "name": "activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'image'"+ },+ "surface": {+ "name": "surface",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'description'"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "asset_workspaceId_idx": {+ "name": "asset_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_projectId_idx": {+ "name": "asset_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_taskId_idx": {+ "name": "asset_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_activityId_idx": {+ "name": "asset_activityId_idx",+ "columns": [+ {+ "expression": "activity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_createdBy_idx": {+ "name": "asset_createdBy_idx",+ "columns": [+ {+ "expression": "created_by",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "asset_workspace_id_workspace_id_fk": {+ "name": "asset_workspace_id_workspace_id_fk",+ "tableFrom": "asset",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_project_id_project_id_fk": {+ "name": "asset_project_id_project_id_fk",+ "tableFrom": "asset",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_task_id_task_id_fk": {+ "name": "asset_task_id_task_id_fk",+ "tableFrom": "asset",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_activity_id_activity_id_fk": {+ "name": "asset_activity_id_activity_id_fk",+ "tableFrom": "asset",+ "tableTo": "activity",+ "columnsFrom": ["activity_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_created_by_user_id_fk": {+ "name": "asset_created_by_user_id_fk",+ "tableFrom": "asset",+ "tableTo": "user",+ "columnsFrom": ["created_by"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "asset_object_key_unique": {+ "name": "asset_object_key_unique",+ "nullsNotDistinct": false,+ "columns": ["object_key"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_event": {+ "name": "billing_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_reminder_sent": {+ "name": "billing_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "billing_reminder_sent_workspaceId_idx": {+ "name": "billing_reminder_sent_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "billing_reminder_sent_userId_idx": {+ "name": "billing_reminder_sent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "billing_reminder_sent_user_id_user_id_fk": {+ "name": "billing_reminder_sent_user_id_user_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "billing_reminder_sent_workspace_id_workspace_id_fk": {+ "name": "billing_reminder_sent_workspace_id_workspace_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "billing_reminder_sent_user_type_unique": {+ "name": "billing_reminder_sent_user_type_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id", "reminder_type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.column": {+ "name": "column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_final": {+ "name": "is_final",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "column_projectId_idx": {+ "name": "column_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "column_project_id_project_id_fk": {+ "name": "column_project_id_project_id_fk",+ "tableFrom": "column",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.comment": {+ "name": "comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "comment_task_idx": {+ "name": "comment_task_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "comment_user_idx": {+ "name": "comment_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "comment_task_id_task_id_fk": {+ "name": "comment_task_id_task_id_fk",+ "tableFrom": "comment",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "comment_user_id_user_id_fk": {+ "name": "comment_user_id_user_id_fk",+ "tableFrom": "comment",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_definition": {+ "name": "custom_field_definition",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "default_value": {+ "name": "default_value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_def_projectId_idx": {+ "name": "custom_field_def_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_definition_project_id_project_id_fk": {+ "name": "custom_field_definition_project_id_project_id_fk",+ "tableFrom": "custom_field_definition",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_value": {+ "name": "custom_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_value_taskId_idx": {+ "name": "custom_field_value_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "custom_field_value_fieldId_idx": {+ "name": "custom_field_value_fieldId_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_value_task_id_task_id_fk": {+ "name": "custom_field_value_task_id_task_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "custom_field_value_field_id_custom_field_definition_id_fk": {+ "name": "custom_field_value_field_id_custom_field_definition_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "custom_field_definition",+ "columnsFrom": ["field_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_value_task_field_unique": {+ "name": "custom_field_value_task_field_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "field_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.device_code": {+ "name": "device_code",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "device_code": {+ "name": "device_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_code": {+ "name": "user_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_polled_at": {+ "name": "last_polled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "polling_interval": {+ "name": "polling_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "device_code_device_code_uidx": {+ "name": "device_code_device_code_uidx",+ "columns": [+ {+ "expression": "device_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_code_uidx": {+ "name": "device_code_user_code_uidx",+ "columns": [+ {+ "expression": "user_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_id_idx": {+ "name": "device_code_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "device_code_user_id_user_id_fk": {+ "name": "device_code_user_id_user_id_fk",+ "tableFrom": "device_code",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_link": {+ "name": "external_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "external_link_taskId_idx": {+ "name": "external_link_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_integrationId_idx": {+ "name": "external_link_integrationId_idx",+ "columns": [+ {+ "expression": "integration_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_externalId_idx": {+ "name": "external_link_externalId_idx",+ "columns": [+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_resourceType_idx": {+ "name": "external_link_resourceType_idx",+ "columns": [+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "external_link_task_id_task_id_fk": {+ "name": "external_link_task_id_task_id_fk",+ "tableFrom": "external_link",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "external_link_integration_id_integration_id_fk": {+ "name": "external_link_integration_id_integration_id_fk",+ "tableFrom": "external_link",+ "tableTo": "integration",+ "columnsFrom": ["integration_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_integration": {+ "name": "github_integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_owner": {+ "name": "repository_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_name": {+ "name": "repository_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installation_id": {+ "name": "installation_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_integration_project_id_project_id_fk": {+ "name": "github_integration_project_id_project_id_fk",+ "tableFrom": "github_integration",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "github_integration_project_id_unique": {+ "name": "github_integration_project_id_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration": {+ "name": "integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_projectId_idx": {+ "name": "integration_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "integration_type_idx": {+ "name": "integration_type_idx",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_project_id_project_id_fk": {+ "name": "integration_project_id_project_id_fk",+ "tableFrom": "integration",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "integration_project_type_unique": {+ "name": "integration_project_type_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id", "type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_workspaceId_idx": {+ "name": "invitation_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_inviterId_idx": {+ "name": "invitation_inviterId_idx",+ "columns": [+ {+ "expression": "inviter_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_workspace_id_workspace_id_fk": {+ "name": "invitation_workspace_id_workspace_id_fk",+ "tableFrom": "invitation",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": ["inviter_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.job_lease": {+ "name": "job_lease",+ "schema": "",+ "columns": {+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "deletion_started_at": {+ "name": "deletion_started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "label_task_id_idx": {+ "name": "label_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_id_idx": {+ "name": "label_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_cascade_idx": {+ "name": "label_workspace_cascade_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"label\".\"task_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_name_unique": {+ "name": "label_workspace_name_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"label\".\"task_id\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "label_task_id_task_id_fk": {+ "name": "label_task_id_task_id_fk",+ "tableFrom": "label",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "label_workspace_id_workspace_id_fk": {+ "name": "label_workspace_id_workspace_id_fk",+ "tableFrom": "label",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_task_name_unique": {+ "name": "label_task_name_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "name"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_state": {+ "name": "mcp_oauth_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_state_kind_key_uidx": {+ "name": "mcp_oauth_state_kind_key_uidx",+ "columns": [+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_state_expiresAt_idx": {+ "name": "mcp_oauth_state_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "is_read": {+ "name": "is_read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_userId_idx": {+ "name": "notification_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_role": {+ "name": "workspace_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_role_workspaceId_idx": {+ "name": "workspace_role_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_role_role_idx": {+ "name": "workspace_role_role_idx",+ "columns": [+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_role_workspace_id_workspace_id_fk": {+ "name": "workspace_role_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_role",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'Layout'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_task_number": {+ "name": "last_task_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {+ "project_workspaceId_position_idx": {+ "name": "project_workspaceId_position_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_workspace_id_workspace_id_fk": {+ "name": "project_workspace_id_workspace_id_fk",+ "tableFrom": "project",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_workspace_id_id_unique": {+ "name": "project_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id", "id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_team_id": {+ "name": "active_team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": ["token"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_relation": {+ "name": "task_relation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "source_task_id": {+ "name": "source_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_task_id": {+ "name": "target_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "relation_type": {+ "name": "relation_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_relation_source_idx": {+ "name": "task_relation_source_idx",+ "columns": [+ {+ "expression": "source_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_relation_target_idx": {+ "name": "task_relation_target_idx",+ "columns": [+ {+ "expression": "target_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_relation_source_task_id_task_id_fk": {+ "name": "task_relation_source_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": ["source_task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_relation_target_task_id_task_id_fk": {+ "name": "task_relation_target_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": ["target_task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_reminder_sent": {+ "name": "task_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_reminder_sent_taskId_idx": {+ "name": "task_reminder_sent_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_reminder_sent_task_id_task_id_fk": {+ "name": "task_reminder_sent_task_id_task_id_fk",+ "tableFrom": "task_reminder_sent",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_reminder_sent_task_type_unique": {+ "name": "task_reminder_sent_task_type_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "reminder_type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task": {+ "name": "task",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "assignee_id": {+ "name": "assignee_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'to-do'"+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'low'"+ },+ "start_date": {+ "name": "start_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_projectId_idx": {+ "name": "task_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_dueDate_idx": {+ "name": "task_dueDate_idx",+ "columns": [+ {+ "expression": "due_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_assigneeId_idx": {+ "name": "task_assigneeId_idx",+ "columns": [+ {+ "expression": "assignee_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_columnId_idx": {+ "name": "task_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_project_id_project_id_fk": {+ "name": "task_project_id_project_id_fk",+ "tableFrom": "task",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_assignee_id_user_id_fk": {+ "name": "task_assignee_id_user_id_fk",+ "tableFrom": "task",+ "tableTo": "user",+ "columnsFrom": ["assignee_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "task_column_id_column_id_fk": {+ "name": "task_column_id_column_id_fk",+ "tableFrom": "task",+ "tableTo": "column",+ "columnsFrom": ["column_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_project_number_unique": {+ "name": "task_project_number_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id", "number"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_workspaceId_idx": {+ "name": "team_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "teamMember_teamId_idx": {+ "name": "teamMember_teamId_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "teamMember_userId_idx": {+ "name": "teamMember_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "tableTo": "team",+ "columnsFrom": ["team_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.time_entry": {+ "name": "time_entry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "duration": {+ "name": "duration",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "time_entry_taskId_idx": {+ "name": "time_entry_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "time_entry_userId_idx": {+ "name": "time_entry_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "time_entry_task_id_task_id_fk": {+ "name": "time_entry_task_id_task_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "time_entry_user_id_user_id_fk": {+ "name": "time_entry_user_id_user_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.trial_grant": {+ "name": "trial_grant",+ "schema": "",+ "columns": {+ "email_hash": {+ "name": "email_hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_anonymous": {+ "name": "is_anonymous",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "ban_reason": {+ "name": "ban_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ban_expires": {+ "name": "ban_expires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": ["email"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_avatar": {+ "name": "user_avatar",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "data": {+ "name": "data",+ "type": "bytea",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_avatar_userId_idx": {+ "name": "user_avatar_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_avatar_user_id_user_id_fk": {+ "name": "user_avatar_user_id_user_id_fk",+ "tableFrom": "user_avatar",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_avatar_user_id_unique": {+ "name": "user_avatar_user_id_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_server_url": {+ "name": "ntfy_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_topic": {+ "name": "ntfy_topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_token": {+ "name": "ntfy_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_server_url": {+ "name": "gotify_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_token": {+ "name": "gotify_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_secret": {+ "name": "webhook_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "task_assignment_enabled": {+ "name": "task_assignment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_comment_enabled": {+ "name": "task_comment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_status_change_enabled": {+ "name": "task_status_change_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_enabled": {+ "name": "due_date_reminder_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_lead_time_minutes": {+ "name": "due_date_reminder_lead_time_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1440+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_preference_user_id_unique": {+ "name": "user_notification_preference_user_id_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_project": {+ "name": "user_notification_workspace_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_rule_id": {+ "name": "workspace_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_project_ruleId_idx": {+ "name": "user_notification_workspace_project_ruleId_idx",+ "columns": [+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_projectId_idx": {+ "name": "user_notification_workspace_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_workspaceId_projectId_idx": {+ "name": "user_notification_workspace_project_workspaceId_projectId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "unwp_workspaceId_workspaceRuleId_idx": {+ "name": "unwp_workspaceId_workspaceRuleId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_project_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "user_notification_workspace_rule",+ "columnsFrom": ["workspace_id", "workspace_rule_id"],+ "columnsTo": ["workspace_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "project",+ "columnsFrom": ["workspace_id", "project_id"],+ "columnsTo": ["workspace_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_project_rule_project_unique": {+ "name": "user_notification_workspace_project_rule_project_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_rule_id", "project_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_rule": {+ "name": "user_notification_workspace_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "project_mode": {+ "name": "project_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_rule_userId_idx": {+ "name": "user_notification_workspace_rule_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_rule_workspaceId_idx": {+ "name": "user_notification_workspace_rule_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_rule_user_id_user_id_fk": {+ "name": "user_notification_workspace_rule_user_id_user_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_rule_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_rule_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_rule_user_workspace_unique": {+ "name": "user_notification_workspace_rule_user_workspace_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id", "workspace_id"]+ },+ "user_notification_workspace_rule_workspace_id_id_unique": {+ "name": "user_notification_workspace_rule_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id", "id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workflow_rule": {+ "name": "workflow_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_type": {+ "name": "integration_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workflow_rule_projectId_idx": {+ "name": "workflow_rule_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workflow_rule_columnId_idx": {+ "name": "workflow_rule_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workflow_rule_project_id_project_id_fk": {+ "name": "workflow_rule_project_id_project_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "workflow_rule_column_id_column_id_fk": {+ "name": "workflow_rule_column_id_column_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "column",+ "columnsFrom": ["column_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "nullsNotDistinct": false,+ "columns": ["slug"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_billing": {+ "name": "workspace_billing",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "founding_free": {+ "name": "founding_free",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "creem_customer_id": {+ "name": "creem_customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_subscription_id": {+ "name": "creem_subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_product_id": {+ "name": "creem_product_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "billing_interval": {+ "name": "billing_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "seats": {+ "name": "seats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "canceled_at": {+ "name": "canceled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_billing_workspaceId_idx": {+ "name": "workspace_billing_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_billing_workspace_id_workspace_id_fk": {+ "name": "workspace_billing_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_billing",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_billing_workspace_id_unique": {+ "name": "workspace_billing_workspace_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id"]+ },+ "workspace_billing_creem_subscription_id_unique": {+ "name": "workspace_billing_creem_subscription_id_unique",+ "nullsNotDistinct": false,+ "columns": ["creem_subscription_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member": {+ "name": "workspace_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "joined_at": {+ "name": "joined_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "workspace_member_workspaceId_idx": {+ "name": "workspace_member_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_member_userId_idx": {+ "name": "workspace_member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_workspace_id_workspace_id_fk": {+ "name": "workspace_member_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_user_id_user_id_fk": {+ "name": "workspace_member_user_id_user_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/apps/api/drizzle/meta/0050_snapshot.json b/apps/api/drizzle/meta/0050_snapshot.jsonnew file mode 100644index 000000000..2f7e95a8b--- /dev/null+++ b/apps/api/drizzle/meta/0050_snapshot.json@@ -0,0 +1,4504 @@+{+ "id": "f9757406-e33b-407b-9849-36c7af901b05",+ "prevId": "330dc3f0-66d6-4ebb-bfd5-0e40aac5a651",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.activity": {+ "name": "activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_name": {+ "name": "external_user_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_user_avatar": {+ "name": "external_user_avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_source": {+ "name": "external_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_url": {+ "name": "external_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "activity_task_id_idx": {+ "name": "activity_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_userId_idx": {+ "name": "activity_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "activity_task_id_task_id_fk": {+ "name": "activity_task_id_task_id_fk",+ "tableFrom": "activity",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "activity_user_id_user_id_fk": {+ "name": "activity_user_id_user_id_fk",+ "tableFrom": "activity",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "activity_task_external_source_external_url_unique": {+ "name": "activity_task_external_source_external_url_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "external_source", "external_url"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 86400000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 10+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_userId_idx": {+ "name": "apikey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "apikey_reference_id_user_id_fk": {+ "name": "apikey_reference_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": ["reference_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "apikey_user_id_user_id_fk": {+ "name": "apikey_user_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.asset": {+ "name": "asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activity_id": {+ "name": "activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'image'"+ },+ "surface": {+ "name": "surface",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'description'"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "asset_workspaceId_idx": {+ "name": "asset_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_projectId_idx": {+ "name": "asset_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_taskId_idx": {+ "name": "asset_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_activityId_idx": {+ "name": "asset_activityId_idx",+ "columns": [+ {+ "expression": "activity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "asset_createdBy_idx": {+ "name": "asset_createdBy_idx",+ "columns": [+ {+ "expression": "created_by",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "asset_workspace_id_workspace_id_fk": {+ "name": "asset_workspace_id_workspace_id_fk",+ "tableFrom": "asset",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_project_id_project_id_fk": {+ "name": "asset_project_id_project_id_fk",+ "tableFrom": "asset",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_task_id_task_id_fk": {+ "name": "asset_task_id_task_id_fk",+ "tableFrom": "asset",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_activity_id_activity_id_fk": {+ "name": "asset_activity_id_activity_id_fk",+ "tableFrom": "asset",+ "tableTo": "activity",+ "columnsFrom": ["activity_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "asset_created_by_user_id_fk": {+ "name": "asset_created_by_user_id_fk",+ "tableFrom": "asset",+ "tableTo": "user",+ "columnsFrom": ["created_by"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "asset_object_key_unique": {+ "name": "asset_object_key_unique",+ "nullsNotDistinct": false,+ "columns": ["object_key"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_event": {+ "name": "billing_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_reminder_sent": {+ "name": "billing_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "billing_reminder_sent_workspaceId_idx": {+ "name": "billing_reminder_sent_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "billing_reminder_sent_userId_idx": {+ "name": "billing_reminder_sent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "billing_reminder_sent_user_id_user_id_fk": {+ "name": "billing_reminder_sent_user_id_user_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "billing_reminder_sent_workspace_id_workspace_id_fk": {+ "name": "billing_reminder_sent_workspace_id_workspace_id_fk",+ "tableFrom": "billing_reminder_sent",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "billing_reminder_sent_user_type_unique": {+ "name": "billing_reminder_sent_user_type_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id", "reminder_type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.column": {+ "name": "column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_final": {+ "name": "is_final",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "column_projectId_idx": {+ "name": "column_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "column_project_id_project_id_fk": {+ "name": "column_project_id_project_id_fk",+ "tableFrom": "column",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.comment": {+ "name": "comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "comment_task_idx": {+ "name": "comment_task_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "comment_user_idx": {+ "name": "comment_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "comment_task_id_task_id_fk": {+ "name": "comment_task_id_task_id_fk",+ "tableFrom": "comment",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "comment_user_id_user_id_fk": {+ "name": "comment_user_id_user_id_fk",+ "tableFrom": "comment",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_definition": {+ "name": "custom_field_definition",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "default_value": {+ "name": "default_value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_def_projectId_idx": {+ "name": "custom_field_def_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_definition_project_id_project_id_fk": {+ "name": "custom_field_definition_project_id_project_id_fk",+ "tableFrom": "custom_field_definition",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field_value": {+ "name": "custom_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "custom_field_value_taskId_idx": {+ "name": "custom_field_value_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "custom_field_value_fieldId_idx": {+ "name": "custom_field_value_fieldId_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "custom_field_value_task_id_task_id_fk": {+ "name": "custom_field_value_task_id_task_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "custom_field_value_field_id_custom_field_definition_id_fk": {+ "name": "custom_field_value_field_id_custom_field_definition_id_fk",+ "tableFrom": "custom_field_value",+ "tableTo": "custom_field_definition",+ "columnsFrom": ["field_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_value_task_field_unique": {+ "name": "custom_field_value_task_field_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "field_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.device_code": {+ "name": "device_code",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "device_code": {+ "name": "device_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_code": {+ "name": "user_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_polled_at": {+ "name": "last_polled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "polling_interval": {+ "name": "polling_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "device_code_device_code_uidx": {+ "name": "device_code_device_code_uidx",+ "columns": [+ {+ "expression": "device_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_code_uidx": {+ "name": "device_code_user_code_uidx",+ "columns": [+ {+ "expression": "user_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "device_code_user_id_idx": {+ "name": "device_code_user_id_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "device_code_user_id_user_id_fk": {+ "name": "device_code_user_id_user_id_fk",+ "tableFrom": "device_code",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_link": {+ "name": "external_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "external_link_taskId_idx": {+ "name": "external_link_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_integrationId_idx": {+ "name": "external_link_integrationId_idx",+ "columns": [+ {+ "expression": "integration_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_externalId_idx": {+ "name": "external_link_externalId_idx",+ "columns": [+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_resourceType_idx": {+ "name": "external_link_resourceType_idx",+ "columns": [+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "external_link_task_id_task_id_fk": {+ "name": "external_link_task_id_task_id_fk",+ "tableFrom": "external_link",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "external_link_integration_id_integration_id_fk": {+ "name": "external_link_integration_id_integration_id_fk",+ "tableFrom": "external_link",+ "tableTo": "integration",+ "columnsFrom": ["integration_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_import": {+ "name": "github_import",+ "schema": "",+ "columns": {+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_import_integration_id_integration_id_fk": {+ "name": "github_import_integration_id_integration_id_fk",+ "tableFrom": "github_import",+ "tableTo": "integration",+ "columnsFrom": ["integration_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_integration": {+ "name": "github_integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_owner": {+ "name": "repository_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_name": {+ "name": "repository_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installation_id": {+ "name": "installation_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_integration_project_id_project_id_fk": {+ "name": "github_integration_project_id_project_id_fk",+ "tableFrom": "github_integration",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "github_integration_project_id_unique": {+ "name": "github_integration_project_id_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration": {+ "name": "integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_projectId_idx": {+ "name": "integration_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "integration_type_idx": {+ "name": "integration_type_idx",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_project_id_project_id_fk": {+ "name": "integration_project_id_project_id_fk",+ "tableFrom": "integration",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "integration_project_type_unique": {+ "name": "integration_project_type_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id", "type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_workspaceId_idx": {+ "name": "invitation_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_inviterId_idx": {+ "name": "invitation_inviterId_idx",+ "columns": [+ {+ "expression": "inviter_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_workspace_id_workspace_id_fk": {+ "name": "invitation_workspace_id_workspace_id_fk",+ "tableFrom": "invitation",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": ["inviter_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.job_lease": {+ "name": "job_lease",+ "schema": "",+ "columns": {+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "owner": {+ "name": "owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "deletion_started_at": {+ "name": "deletion_started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "label_task_id_idx": {+ "name": "label_task_id_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_id_idx": {+ "name": "label_workspace_id_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_cascade_idx": {+ "name": "label_workspace_cascade_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"label\".\"task_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "label_workspace_name_unique": {+ "name": "label_workspace_name_unique",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"label\".\"task_id\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "label_task_id_task_id_fk": {+ "name": "label_task_id_task_id_fk",+ "tableFrom": "label",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "label_workspace_id_workspace_id_fk": {+ "name": "label_workspace_id_workspace_id_fk",+ "tableFrom": "label",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_task_name_unique": {+ "name": "label_task_name_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "name"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_state": {+ "name": "mcp_oauth_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_state_kind_key_uidx": {+ "name": "mcp_oauth_state_kind_key_uidx",+ "columns": [+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_state_expiresAt_idx": {+ "name": "mcp_oauth_state_expiresAt_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "event_data": {+ "name": "event_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "is_read": {+ "name": "is_read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_userId_idx": {+ "name": "notification_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_role": {+ "name": "workspace_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission": {+ "name": "permission",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_role_workspaceId_idx": {+ "name": "workspace_role_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_role_role_idx": {+ "name": "workspace_role_role_idx",+ "columns": [+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_role_workspace_id_workspace_id_fk": {+ "name": "workspace_role_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_role",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'Layout'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_task_number": {+ "name": "last_task_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {+ "project_workspaceId_position_idx": {+ "name": "project_workspaceId_position_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_workspace_id_workspace_id_fk": {+ "name": "project_workspace_id_workspace_id_fk",+ "tableFrom": "project",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_workspace_id_id_unique": {+ "name": "project_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id", "id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_team_id": {+ "name": "active_team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "impersonated_by": {+ "name": "impersonated_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": ["token"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_relation": {+ "name": "task_relation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "source_task_id": {+ "name": "source_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_task_id": {+ "name": "target_task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "relation_type": {+ "name": "relation_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_relation_source_idx": {+ "name": "task_relation_source_idx",+ "columns": [+ {+ "expression": "source_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_relation_target_idx": {+ "name": "task_relation_target_idx",+ "columns": [+ {+ "expression": "target_task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_relation_source_task_id_task_id_fk": {+ "name": "task_relation_source_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": ["source_task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_relation_target_task_id_task_id_fk": {+ "name": "task_relation_target_task_id_task_id_fk",+ "tableFrom": "task_relation",+ "tableTo": "task",+ "columnsFrom": ["target_task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task_reminder_sent": {+ "name": "task_reminder_sent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reminder_type": {+ "name": "reminder_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_reminder_sent_taskId_idx": {+ "name": "task_reminder_sent_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_reminder_sent_task_id_task_id_fk": {+ "name": "task_reminder_sent_task_id_task_id_fk",+ "tableFrom": "task_reminder_sent",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_reminder_sent_task_type_unique": {+ "name": "task_reminder_sent_task_type_unique",+ "nullsNotDistinct": false,+ "columns": ["task_id", "reminder_type"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task": {+ "name": "task",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "assignee_id": {+ "name": "assignee_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'to-do'"+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'low'"+ },+ "start_date": {+ "name": "start_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "task_projectId_idx": {+ "name": "task_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_dueDate_idx": {+ "name": "task_dueDate_idx",+ "columns": [+ {+ "expression": "due_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_assigneeId_idx": {+ "name": "task_assigneeId_idx",+ "columns": [+ {+ "expression": "assignee_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "task_columnId_idx": {+ "name": "task_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "task_project_id_project_id_fk": {+ "name": "task_project_id_project_id_fk",+ "tableFrom": "task",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_assignee_id_user_id_fk": {+ "name": "task_assignee_id_user_id_fk",+ "tableFrom": "task",+ "tableTo": "user",+ "columnsFrom": ["assignee_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "task_column_id_column_id_fk": {+ "name": "task_column_id_column_id_fk",+ "tableFrom": "task",+ "tableTo": "column",+ "columnsFrom": ["column_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "task_project_number_unique": {+ "name": "task_project_number_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id", "number"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_workspaceId_idx": {+ "name": "team_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "teamMember_teamId_idx": {+ "name": "teamMember_teamId_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "teamMember_userId_idx": {+ "name": "teamMember_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "tableTo": "team",+ "columnsFrom": ["team_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.time_entry": {+ "name": "time_entry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "duration": {+ "name": "duration",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "time_entry_taskId_idx": {+ "name": "time_entry_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "time_entry_userId_idx": {+ "name": "time_entry_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "time_entry_task_id_task_id_fk": {+ "name": "time_entry_task_id_task_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "time_entry_user_id_user_id_fk": {+ "name": "time_entry_user_id_user_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.trial_grant": {+ "name": "trial_grant",+ "schema": "",+ "columns": {+ "email_hash": {+ "name": "email_hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_anonymous": {+ "name": "is_anonymous",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "ban_reason": {+ "name": "ban_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ban_expires": {+ "name": "ban_expires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": ["email"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_avatar": {+ "name": "user_avatar",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size": {+ "name": "size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "data": {+ "name": "data",+ "type": "bytea",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_avatar_userId_idx": {+ "name": "user_avatar_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_avatar_user_id_user_id_fk": {+ "name": "user_avatar_user_id_user_id_fk",+ "tableFrom": "user_avatar",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_avatar_user_id_unique": {+ "name": "user_avatar_user_id_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_server_url": {+ "name": "ntfy_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_topic": {+ "name": "ntfy_topic",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ntfy_token": {+ "name": "ntfy_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_server_url": {+ "name": "gotify_server_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "gotify_token": {+ "name": "gotify_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_secret": {+ "name": "webhook_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "task_assignment_enabled": {+ "name": "task_assignment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_comment_enabled": {+ "name": "task_comment_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "task_status_change_enabled": {+ "name": "task_status_change_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_enabled": {+ "name": "due_date_reminder_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "due_date_reminder_lead_time_minutes": {+ "name": "due_date_reminder_lead_time_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1440+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_preference_user_id_unique": {+ "name": "user_notification_preference_user_id_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_project": {+ "name": "user_notification_workspace_project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_rule_id": {+ "name": "workspace_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_project_ruleId_idx": {+ "name": "user_notification_workspace_project_ruleId_idx",+ "columns": [+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_projectId_idx": {+ "name": "user_notification_workspace_project_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_project_workspaceId_projectId_idx": {+ "name": "user_notification_workspace_project_workspaceId_projectId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "unwp_workspaceId_workspaceRuleId_idx": {+ "name": "unwp_workspaceId_workspaceRuleId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "workspace_rule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_project_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_workspace_rule_id_user_notification_workspace_rule_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "user_notification_workspace_rule",+ "columnsFrom": ["workspace_id", "workspace_rule_id"],+ "columnsTo": ["workspace_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk": {+ "name": "user_notification_workspace_project_workspace_id_project_id_project_workspace_id_id_fk",+ "tableFrom": "user_notification_workspace_project",+ "tableTo": "project",+ "columnsFrom": ["workspace_id", "project_id"],+ "columnsTo": ["workspace_id", "id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_project_rule_project_unique": {+ "name": "user_notification_workspace_project_rule_project_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_rule_id", "project_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_workspace_rule": {+ "name": "user_notification_workspace_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "email_enabled": {+ "name": "email_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "ntfy_enabled": {+ "name": "ntfy_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "gotify_enabled": {+ "name": "gotify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "webhook_enabled": {+ "name": "webhook_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "project_mode": {+ "name": "project_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'all'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_notification_workspace_rule_userId_idx": {+ "name": "user_notification_workspace_rule_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_notification_workspace_rule_workspaceId_idx": {+ "name": "user_notification_workspace_rule_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_notification_workspace_rule_user_id_user_id_fk": {+ "name": "user_notification_workspace_rule_user_id_user_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "user_notification_workspace_rule_workspace_id_workspace_id_fk": {+ "name": "user_notification_workspace_rule_workspace_id_workspace_id_fk",+ "tableFrom": "user_notification_workspace_rule",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_workspace_rule_user_workspace_unique": {+ "name": "user_notification_workspace_rule_user_workspace_unique",+ "nullsNotDistinct": false,+ "columns": ["user_id", "workspace_id"]+ },+ "user_notification_workspace_rule_workspace_id_id_unique": {+ "name": "user_notification_workspace_rule_workspace_id_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id", "id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workflow_rule": {+ "name": "workflow_rule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_type": {+ "name": "integration_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workflow_rule_projectId_idx": {+ "name": "workflow_rule_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workflow_rule_columnId_idx": {+ "name": "workflow_rule_columnId_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workflow_rule_project_id_project_id_fk": {+ "name": "workflow_rule_project_id_project_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "workflow_rule_column_id_column_id_fk": {+ "name": "workflow_rule_column_id_column_id_fk",+ "tableFrom": "workflow_rule",+ "tableTo": "column",+ "columnsFrom": ["column_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "nullsNotDistinct": false,+ "columns": ["slug"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_billing": {+ "name": "workspace_billing",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "founding_free": {+ "name": "founding_free",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "trial_ends_at": {+ "name": "trial_ends_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "creem_customer_id": {+ "name": "creem_customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_subscription_id": {+ "name": "creem_subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "creem_product_id": {+ "name": "creem_product_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "billing_interval": {+ "name": "billing_interval",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "seats": {+ "name": "seats",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "canceled_at": {+ "name": "canceled_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_billing_workspaceId_idx": {+ "name": "workspace_billing_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_billing_workspace_id_workspace_id_fk": {+ "name": "workspace_billing_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_billing",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_billing_workspace_id_unique": {+ "name": "workspace_billing_workspace_id_unique",+ "nullsNotDistinct": false,+ "columns": ["workspace_id"]+ },+ "workspace_billing_creem_subscription_id_unique": {+ "name": "workspace_billing_creem_subscription_id_unique",+ "nullsNotDistinct": false,+ "columns": ["creem_subscription_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member": {+ "name": "workspace_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "joined_at": {+ "name": "joined_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "workspace_member_workspaceId_idx": {+ "name": "workspace_member_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_member_userId_idx": {+ "name": "workspace_member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_workspace_id_workspace_id_fk": {+ "name": "workspace_member_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_user_id_user_id_fk": {+ "name": "workspace_member_user_id_user_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.jsonindex 0c7e55ca7..cd6b9400b 100644--- a/apps/api/drizzle/meta/_journal.json+++ b/apps/api/drizzle/meta/_journal.json@@ -323,6 +323,41 @@"when": 1787499154673,"tag": "0045_fantastic_princess_powerful","breakpoints": true+ },+ {+ "idx": 46,+ "version": "7",+ "when": 1789848584765,+ "tag": "0046_repair_task_number_counters",+ "breakpoints": true+ },+ {+ "idx": 47,+ "version": "7",+ "when": 1789848658630,+ "tag": "0047_repair_legacy_auth_ownership",+ "breakpoints": true+ },+ {+ "idx": 48,+ "version": "7",+ "when": 1789850930398,+ "tag": "0048_resumable_label_deletion",+ "breakpoints": true+ },+ {+ "idx": 49,+ "version": "7",+ "when": 1789851005279,+ "tag": "0049_label_cascade_index",+ "breakpoints": true+ },+ {+ "idx": 50,+ "version": "7",+ "when": 1789853277231,+ "tag": "0050_resumable_github_import",+ "breakpoints": true}]}diff --git a/apps/api/package.json b/apps/api/package.jsonindex d58be8864..94bbe8818 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -10,9 +10,6 @@"default": "./dist/index.js"}},- "overrides": {- "esbuild": "^0.25.0"- },"scripts": {"dev": "tsx watch src/index.ts","build": "esbuild src/index.ts --bundle --platform=node --outdir=dist --format=esm --packages=external --external:fs --external:path --external:crypto --external:os --external:util --external:stream --external:buffer --external:events --external:url --external:querystring --external:http --external:https --external:net --external:tls --external:zlib --external:@modelcontextprotocol/sdk",@@ -26,7 +23,6 @@"db:generate": "drizzle-kit generate","db:migrate": "drizzle-kit migrate","db:studio": "drizzle-kit studio",- "db:seed:user-data": "tsx scripts/seed-user-data.ts","openapi:export": "tsx scripts/export-openapi.ts"},"dependencies": {diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 651b00b29..cebe15ac9 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -1,5 +1,6 @@import { apiKey } from "@better-auth/api-key";import {+ OTP_EXPIRY_SECONDS,sendMagicLinkEmail,sendOtpEmail,sendWorkspaceInvitationEmail,@@ -33,7 +34,7 @@ import {import type { AccessControl } from "better-auth/plugins/access";import type { UserWithAnonymous } from "better-auth/plugins/anonymous";import { config } from "dotenv-mono";-import { count, eq, sql } from "drizzle-orm";+import { eq } from "drizzle-orm";import {findBillableWorkspaces,formatBillableWorkspacesMessage,@@ -50,10 +51,19 @@ import { getDefaultCookieAttributes } from "./utils/get-default-cookie-attributeimport { getInvitationEmailSubject } from "./utils/get-invitation-email-subject";import { getWorkspaceInvitationEmailCopy } from "./utils/get-workspace-invitation-email-copy";import { getGithubSsoOAuthCredentials } from "./utils/github-sso-env";+import {+ hasRegisteredUsers,+ promoteInitialAdministrator,+} from "./utils/instance-bootstrap";import { isCloud } from "./utils/is-cloud";import { isDisposableEmail } from "./utils/is-disposable-email";import { isLocalSignInPath } from "./utils/is-local-sign-in-path";-import { verifyTurnstile } from "./utils/verify-turnstile";+import {+ assertGuestRegistrationAllowed,+ assertUserRegistrationAllowed,+ normalizeInvitationId,+} from "./utils/registration-policy";+import { authCaptchaPaths, verifyTurnstile } from "./utils/verify-turnstile";config();@@ -68,18 +78,6 @@ const isEmailOtpSignInDisabled =const isWorkspaceCreationDisabled =process.env.DISABLE_WORKSPACE_CREATION === "true";-function normalizeInvitationId(value: unknown): string | undefined {- if (typeof value !== "string") return undefined;- const normalized = value.trim();- if (!/^[a-z0-9_-]{1,128}$/i.test(normalized)) return undefined;- return normalized;-}--function isOAuthCallbackPath(path: unknown): boolean {- if (typeof path !== "string") return false;- return path.startsWith("/callback/") || path.startsWith("/oauth2/callback/");-}-const apiUrl = process.env.KANEO_API_URL || "http://localhost:1337";const clientUrl = process.env.KANEO_CLIENT_URL || "http://localhost:5173";@@ -131,8 +129,8 @@ function getAuthEmailCopy(locale?: string | null) {if (localeKey === "de") {return {- magicLinkSubject: "Anmeldelink fuer Kaneo",- otpSubject: "Bestaetigungscode fuer Kaneo",+ magicLinkSubject: "Anmeldelink für Kaneo",+ otpSubject: "Bestätigungscode für Kaneo",};}@@ -169,25 +167,6 @@ function getDeviceAuthClientIds(): Set<string> {return new Set(["kaneo-cli", "kaneo-mcp"]);}-const DEFAULT_TRUSTED_PROXIES = [- "127.0.0.0/8",- "::1/128",- "10.0.0.0/8",- "172.16.0.0/12",- "192.168.0.0/16",-];--function trustedProxies(): string[] {- const raw = process.env.TRUSTED_PROXIES?.trim();- if (!raw) {- return DEFAULT_TRUSTED_PROXIES;- }- return raw- .split(",")- .map((entry) => entry.trim())- .filter(Boolean);-}-function getDeviceAuthVerificationUri(): string {const base = clientUrl.replace(/\/$/, "");return `${base}/device`;@@ -233,11 +212,9 @@ export const auth = betterAuth({},account: {accountLinking: {- // Link an OAuth/OIDC sign-in to an existing account that shares the same- // email instead of failing with error=account_not_linked. The listed- // providers verify the email on their side, so they are trusted to link.+ // Require the provider's verified-email claim for implicit linking;+ // configuration alone must not make an unverified identity trusted.enabled: true,- trustedProviders: ["github", "google", "discord", "custom"],// Only link to an existing local account after its email has been// verified. Without this check, an attacker could pre-register a victim's// email with a password account and retain access after the victim signs@@ -283,6 +260,7 @@ export const auth = betterAuth({: []),lastLoginMethod(),magicLink({+ disableSignUp: isPasswordRegistrationDisabled,sendMagicLink: async ({ email, url }) => {try {const locale = await getUserLocale(email);@@ -300,6 +278,8 @@ export const auth = betterAuth({? []: [emailOTP({+ expiresIn: OTP_EXPIRY_SECONDS,+ disableSignUp: isPasswordRegistrationDisabled,async sendVerificationOTP({ email, otp, type }) {if (type === "sign-in") {const locale = await getUserLocale(email);@@ -568,6 +548,7 @@ export const auth = betterAuth({max: 100,customRules: {"/sign-up/email": { window: 60, max: 3 },+ "/sign-in/anonymous": { window: 60, max: 3 },"/organization/invite-member": { window: 60, max: 5 },},},@@ -575,44 +556,16 @@ export const auth = betterAuth({user: {create: {before: async (user, ctx) => {- // The anonymous() plugin creates ephemeral users for guest- // access; registration limits don't apply to them (guest- // availability is governed by DISABLE_GUEST_ACCESS instead).- // `isAnonymous` is `input: false` in the plugin schema, so a- // regular signup request cannot spoof it.- const userWithAnonymous = user as Partial<UserWithAnonymous>;- if (userWithAnonymous.isAnonymous) {- return;- }-- // Allow the very first signup through even when registration- // is disabled: that's the instance-admin bootstrap flow.- // Otherwise a fresh instance with DISABLE_REGISTRATION=true- // could never be set up because `checkRegistrationAllowed`- // would reject the first user (qodo bot #3).- const [userCountRow] = await db- .select({ value: count() })- .from(schema.userTable);- const existingUserCount = userCountRow?.value ?? 0;- if (existingUserCount === 0) {- return;- }-- const invitationId = normalizeInvitationId(- ctx?.body?.invitationId ||- ctx?.query?.invitationId ||- ctx?.headers?.get("x-invitation-id"),- );- const result = await checkRegistrationAllowed(- user.email,- invitationId,- { allowInvitationByEmail: isOAuthCallbackPath(ctx?.path) },+ await assertUserRegistrationAllowed(+ user as Partial<UserWithAnonymous> & { email: string },+ {+ path: ctx?.path,+ invitationId:+ ctx?.body?.invitationId ||+ ctx?.query?.invitationId ||+ ctx?.headers?.get("x-invitation-id"),+ },);- if (!result.allowed) {- throw new APIError("FORBIDDEN", {- message: result.reason,- });- }},after: async (user) => {// The anonymous() plugin creates ephemeral users for guest@@ -625,42 +578,7 @@ export const auth = betterAuth({return;}- // Promote the first user to instance admin atomically.- //- // A previous version of this code checked the user count in- // the `before` hook and returned `role: "admin"`, but the- // count and the eventual INSERT happened in separate- // transactions, so two concurrent first-signups could both- // see count=0 and both become admins (qodo bot #5).- //- // We now run the check + promote inside a single transaction- // guarded by a Postgres advisory lock. Whichever transaction- // wins the lock first promotes its user; any concurrent- // transaction then sees totalUserCount > 1 and skips.- //- // Note: we count total users (not admins) so that upgrading- // an existing instance (where every existing user has- // role=NULL from the new column) doesn't promote the next- // signup to admin (qodo bot #4).- await db.transaction(async (tx) => {- await tx.execute(sql`SELECT pg_advisory_xact_lock(2026)`);-- const totalRows = await tx- .select({ value: count() })- .from(schema.userTable);- const totalUserCount = totalRows[0]?.value ?? 0;-- // This hook runs after the user row is inserted, so the- // just-created user is included in the count. If they are- // the only row in the table, this is a fresh-instance- // bootstrap and they get promoted to admin.- if (totalUserCount === 1) {- await tx- .update(schema.userTable)- .set({ role: "admin" })- .where(eq(schema.userTable.id, user.id));- }- });+ await promoteInitialAdministrator(user.id);},},},@@ -674,6 +592,18 @@ export const auth = betterAuth({});}+ if (ctx.path === "/sign-in/anonymous") {+ await assertGuestRegistrationAllowed();+ }++ if (authCaptchaPaths.has(ctx.path)) {+ const verdict = await verifyTurnstile(+ ctx.headers?.get("x-turnstile-token") ?? ctx.body?.turnstileToken,+ );+ if (!verdict.ok)+ throw new APIError("FORBIDDEN", { message: verdict.reason });+ }+// Block invite-member calls on cloud from anonymous users or to// disposable-email addresses. The 2026-05-28 incident saw ~14k phishing// invites sent from throwaway disposable-email signups; gating here@@ -711,11 +641,7 @@ export const auth = betterAuth({return;}- const userCountRows = await db- .select({ value: count() })- .from(schema.userTable);- const existingUserCount = userCountRows[0]?.value ?? 0;- const isInstanceAdminSetup = existingUserCount === 0;+ const isInstanceAdminSetup = !(await hasRegisteredUsers());if (ctx.path === "/sign-up/email") {if (isPasswordRegistrationDisabled && !isInstanceAdminSetup) {@@ -725,8 +651,8 @@ export const auth = betterAuth({});}- // Cloud-only abuse gates on password signup. Self-hosted instances- // leave KANEO_CLOUD/TURNSTILE_SECRET_KEY unset and skip both.+ // Cloud-only disposable-email check; CAPTCHA is enforced above+ // on every account-creation initiation when configured.if (isCloud() && !isInstanceAdminSetup) {const signupEmail = (ctx.body?.email as string | undefined) ?? "";if (signupEmail && isDisposableEmail(signupEmail)) {@@ -735,19 +661,6 @@ export const auth = betterAuth({"Sign-up with disposable email addresses is not allowed.",});}-- const turnstileToken =- (ctx.body?.turnstileToken as string | undefined) ??- ctx.headers?.get("x-turnstile-token") ??- null;- const remoteIp =- ctx.headers?.get("cf-connecting-ip") ??- ctx.headers?.get("x-forwarded-for")?.split(",")[0]?.trim() ??- null;- const verdict = await verifyTurnstile(turnstileToken, remoteIp);- if (!verdict.ok) {- throw new APIError("FORBIDDEN", { message: verdict.reason });- }}}@@ -798,8 +711,9 @@ export const auth = betterAuth({},advanced: {ipAddress: {- ipAddressHeaders: ["cf-connecting-ip", "x-forwarded-for"],- trustedProxies: trustedProxies(),+ // Set only by the Node transport middleware, never accepted from clients.+ ipAddressHeaders: ["x-kaneo-client-ip"],+ trustedProxies: [],},defaultCookieAttributes: getDefaultCookieAttributes({apiUrl,diff --git a/apps/api/src/billing/index.ts b/apps/api/src/billing/index.tsindex b466c5f91..e11acf78e 100644--- a/apps/api/src/billing/index.ts+++ b/apps/api/src/billing/index.ts@@ -10,6 +10,7 @@ import {errorResponse,jsonResponse,} from "../openapi";+import { requireUserSession } from "../utils/require-user-session";import { validateWorkspaceAccess } from "../utils/validate-workspace-access";import { creemWebhookSecret, isBillingEnabled } from "./config";import createCheckout from "./controllers/create-checkout";@@ -92,6 +93,7 @@ const getWorkspaceBillingRoute = createRoute({});const createCheckoutRoute = createRoute({+ middleware: [requireUserSession] as const,...cloudOnly,method: "post",operationId: "createBillingCheckout",@@ -115,6 +117,7 @@ const createCheckoutRoute = createRoute({});const createPortalRoute = createRoute({+ middleware: [requireUserSession] as const,...cloudOnly,method: "post",operationId: "createBillingPortalSession",diff --git a/apps/api/src/comment/index.ts b/apps/api/src/comment/index.tsindex d517d5e95..1aa59f6b1 100644--- a/apps/api/src/comment/index.ts+++ b/apps/api/src/comment/index.ts@@ -1,3 +1,4 @@+import { HTTPException } from "hono/http-exception";import { activitySchema } from "../activity/response";import {apiRouter,@@ -5,7 +6,10 @@ import {errorResponse,jsonResponse,} from "../openapi";-import { requireWorkspacePermission } from "../utils/require-workspace-permission";+import {+ hasWorkspacePermission,+ requireWorkspacePermission,+} from "../utils/require-workspace-permission";import { workspaceAccess } from "../utils/workspace-access-middleware";import createComment from "./controllers/create-comment";import deleteComment from "./controllers/delete-comment";@@ -61,7 +65,7 @@ const createTaskCommentRoute = createRoute({200: jsonResponse("The created comment", activitySchema),400: errorResponse("Invalid body, or unknown task"),403: errorResponse(- "No workspace access, or missing task:update permission",+ "No workspace access, missing task:update permission, or external attribution without workspace:manage_settings",),},});@@ -121,6 +125,16 @@ const comment = apiRouter().openapi(createTaskCommentRoute, async (c) => {const { taskId } = c.req.valid("param");const { content, externalUserName, externalSource } = c.req.valid("json");+ if (+ externalUserName &&+ externalSource &&+ !(await hasWorkspacePermission(c, { workspace: ["manage_settings"] }))+ ) {+ throw new HTTPException(403, {+ message:+ "Importing external authors requires workspace:manage_settings permission",+ });+ }// Both or neither: a name without a source would render as an// unattributed impersonation of a real account.const external =diff --git a/apps/api/src/comment/schema.ts b/apps/api/src/comment/schema.tsindex fa24b297a..9144dfe5d 100644--- a/apps/api/src/comment/schema.ts+++ b/apps/api/src/comment/schema.ts@@ -10,10 +10,11 @@ export const createCommentBody = z.object({// impersonation of a real account.externalUserName: z.string().max(120).optional().openapi({description:- "Attribution for an imported comment. Ignored unless externalSource is also given.",+ "Attribution for an imported comment. Requires workspace:manage_settings and externalSource; otherwise ignored.",}),externalSource: z.enum(["planka", "trello", "jira"]).optional().openapi({- description: "The tool the comment was imported from.",+ description:+ "The tool the comment was imported from. Supplying external attribution requires workspace:manage_settings.",}),});diff --git a/apps/api/src/custom-field/controllers/create-custom-field.ts b/apps/api/src/custom-field/controllers/create-custom-field.tsindex 8cf783513..6010a20f9 100644--- a/apps/api/src/custom-field/controllers/create-custom-field.ts+++ b/apps/api/src/custom-field/controllers/create-custom-field.ts@@ -8,6 +8,8 @@ import {taskTable,} from "../../database/schema";+import { validateCustomFieldValue } from "../../task/validate-task-fields";+async function createCustomField(projectId: string,name: string,@@ -64,15 +66,9 @@ async function createCustomField(});}} else if (type === "date") {- const dateRegex = /^\d{4}-\d{2}-\d{2}$/;- if (!dateRegex.test(trimmedValue)) {- const parsedDate = new Date(trimmedValue);- if (Number.isNaN(parsedDate.getTime())) {- throw new HTTPException(400, {- message:- "Default value must be a valid date in ISO format (YYYY-MM-DD)",- });- }+ const error = validateCustomFieldValue(trimmedValue, "date", name);+ if (error) {+ throw new HTTPException(400, { message: error });}} else if (type === "dropdown") {if (options && options.length > 0) {@@ -93,6 +89,9 @@ async function createCustomField(});}+ const storedDefaultValue =+ type === "date" ? defaultValue?.trim() : defaultValue;+const [maxPositionResult] = await db.select({ maxPosition: max(customFieldDefinitionTable.position) }).from(customFieldDefinitionTable)@@ -106,7 +105,7 @@ async function createCustomField(name,type,required,- defaultValue: defaultValue ?? null,+ defaultValue: storedDefaultValue ?? null,options: options ?? null,position: (maxPositionResult?.maxPosition ?? 0) + 1,})@@ -118,7 +117,7 @@ async function createCustomField(});}- if (defaultValue != null && defaultValue.trim() !== "") {+ if (storedDefaultValue != null && storedDefaultValue.trim() !== "") {const tasks = await tx.select({ id: taskTable.id }).from(taskTable)@@ -132,7 +131,7 @@ async function createCustomField(tasks.slice(i, i + CHUNK_SIZE).map((task) => ({taskId: task.id,fieldId: created.id,- value: defaultValue,+ value: storedDefaultValue,})),).onConflictDoNothing();diff --git a/apps/api/src/custom-field/index.ts b/apps/api/src/custom-field/index.tsindex 4f663c34e..b255c4f7b 100644--- a/apps/api/src/custom-field/index.ts+++ b/apps/api/src/custom-field/index.ts@@ -38,7 +38,10 @@ const getCustomFieldsRoute = createRoute({tags: ["Custom Fields"],summary: "Get custom fields",description: "Get all custom field definitions for a project.",- middleware: [workspaceAccess.fromProject("projectId")] as const,+ middleware: [+ workspaceAccess.fromProject("projectId"),+ requireWorkspacePermission({ project: ["read"] }),+ ] as const,request: { params: projectIdParam },responses: {200: jsonResponse(@@ -48,7 +51,7 @@ const getCustomFieldsRoute = createRoute({400: errorResponse("Unknown project, or its workspace could not be determined",),- 403: errorResponse("No access to the project's workspace"),+ 403: errorResponse("No workspace access or missing read permission"),},});@@ -59,7 +62,10 @@ const getCustomFieldValuesByProjectRoute = createRoute({tags: ["Custom Fields"],summary: "Get project custom field values",description: "Get all custom field values for every task in a project.",- middleware: [workspaceAccess.fromProject("projectId")] as const,+ middleware: [+ workspaceAccess.fromProject("projectId"),+ requireWorkspacePermission({ task: ["read"] }),+ ] as const,request: { params: projectIdParam },responses: {200: jsonResponse(@@ -69,7 +75,7 @@ const getCustomFieldValuesByProjectRoute = createRoute({400: errorResponse("Unknown project, or its workspace could not be determined",),- 403: errorResponse("No access to the project's workspace"),+ 403: errorResponse("No workspace access or missing read permission"),},});@@ -80,7 +86,10 @@ const getCustomFieldValuesByTaskRoute = createRoute({tags: ["Custom Fields"],summary: "Get task custom field values",description: "Get all custom field values for a task with their definitions.",- middleware: [workspaceAccess.fromTaskId("taskId")] as const,+ middleware: [+ workspaceAccess.fromTaskId("taskId"),+ requireWorkspacePermission({ task: ["read"] }),+ ] as const,request: { params: taskIdParam },responses: {200: jsonResponse(@@ -90,7 +99,7 @@ const getCustomFieldValuesByTaskRoute = createRoute({400: errorResponse("Unknown task, or its workspace could not be determined",),- 403: errorResponse("No access to the task's workspace"),+ 403: errorResponse("No workspace access or missing task:read permission"),},});@@ -102,7 +111,10 @@ const getCustomFieldFilterValuesRoute = createRoute({summary: "Get custom field filter values",description:"Get distinct values used by tasks for each custom field of a project.",- middleware: [workspaceAccess.fromProject("projectId")] as const,+ middleware: [+ workspaceAccess.fromProject("projectId"),+ requireWorkspacePermission({ task: ["read"] }),+ ] as const,request: { params: projectIdParam },responses: {200: jsonResponse(@@ -112,7 +124,7 @@ const getCustomFieldFilterValuesRoute = createRoute({400: errorResponse("Unknown project, or its workspace could not be determined",),- 403: errorResponse("No access to the project's workspace"),+ 403: errorResponse("No workspace access or missing read permission"),},});diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.tsindex c7974a203..c32a73088 100644--- a/apps/api/src/database/index.ts+++ b/apps/api/src/database/index.ts@@ -48,6 +48,7 @@ import {customFieldValueTable,deviceCodeTable,externalLinkTable,+ githubImportTable,githubIntegrationTable,integrationTable,invitationTable,@@ -92,6 +93,7 @@ export const schema = {deviceCodeTable,externalLinkTable,githubIntegrationTable,+ githubImportTable,integrationTable,invitationTable,jobLeaseTable,diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.tsindex ddadb6f70..5c937e085 100644--- a/apps/api/src/database/schema.ts+++ b/apps/api/src/database/schema.ts@@ -13,6 +13,7 @@ import {unique,uniqueIndex,} from "drizzle-orm/pg-core";+import type { GitHubImportState } from "../github-integration/import-state";const bytea = customType<{ data: Buffer; driverData: Buffer }>({dataType() {@@ -643,6 +644,7 @@ export const labelTable = pgTable(.defaultNow().$onUpdate(() => new Date()).notNull(),+ deletionStartedAt: timestamp("deletion_started_at", { mode: "date" }),taskId: text("task_id").references(() => taskTable.id, {onDelete: "cascade",onUpdate: "cascade",@@ -655,6 +657,9 @@ export const labelTable = pgTable((table) => [index("label_task_id_idx").on(table.taskId),index("label_workspace_id_idx").on(table.workspaceId),+ index("label_workspace_cascade_idx")+ .on(table.workspaceId, table.name, table.createdAt, table.id)+ .where(sql`${table.taskId} is not null`),unique("label_task_name_unique").on(table.taskId, table.name),uniqueIndex("label_workspace_name_unique").on(table.workspaceId, table.name)@@ -892,6 +897,23 @@ export const integrationTable = pgTable(],);+export const githubImportTable = pgTable("github_import", {+ integrationId: text("integration_id")+ .primaryKey()+ .references(() => integrationTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ runId: text("run_id")+ .notNull()+ .$defaultFn(() => createId()),+ state: jsonb("state").$type<GitHubImportState>().notNull(),+ updatedAt: timestamp("updated_at", { mode: "date" })+ .defaultNow()+ .notNull()+ .$onUpdate(() => new Date()),+});+export const externalLinkTable = pgTable("external_link",{diff --git a/apps/api/src/events/index.ts b/apps/api/src/events/index.tsindex ddfcb0a9b..6c455ec59 100644--- a/apps/api/src/events/index.ts+++ b/apps/api/src/events/index.ts@@ -18,6 +18,7 @@ export async function shutdownEventBus(): Promise<void> {export async function publishEvent(eventType: string,data: unknown,+ options?: { waitForHandlers?: boolean },): Promise<void> {let enhancedData = null;if (typeof data === "object" && data !== null) {@@ -32,7 +33,14 @@ export async function publishEvent(};try {- EVENTS.emit(eventType, payload);+ if (options?.waitForHandlers) {+ // EventEmitter.emit discards promises. Bounded producers must await the+ // actual subscriber wrappers before starting their next item.+ for (const listener of EVENTS.listeners(eventType))+ await listener(payload);+ } else {+ EVENTS.emit(eventType, payload);+ }} catch (error) {console.error("Failed to publish event:", error);throw error;diff --git a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts b/apps/api/src/gitea-integration/controllers/import-gitea-issues.tsindex c1afe2caa..40440903d 100644--- a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts@@ -1,4 +1,4 @@-import { and, eq, inArray, max, notInArray } from "drizzle-orm";+import { and, eq, inArray, notInArray } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import {@@ -27,6 +27,7 @@ import {extractIssueStatus,} from "../../plugins/github/utils/extract-priority";import { formatTaskDescriptionFromIssue } from "../../plugins/github/utils/format";+import { claimTaskNumber } from "../../task/controllers/claim-task-numbers";type ImportResult = {imported: number;@@ -235,22 +236,7 @@ async function importSingleIssue(}const createdTask = await db.transaction(async (tx) => {- const [lockedProject] = await tx- .select()- .from(projectTable)- .where(eq(projectTable.id, projectId))- .for("update");-- if (!lockedProject) {- throw new Error("Project not found");- }-- const [result] = await tx- .select({ maxNumber: max(taskTable.number) })- .from(taskTable)- .where(eq(taskTable.projectId, projectId));-- const nextNumber = (result?.maxNumber ?? 0) + 1;+ const nextNumber = await claimTaskNumber(projectId, tx);const taskValues: typeof taskTable.$inferInsert = {projectId,diff --git a/apps/api/src/github-integration/controllers/create-github-integration.ts b/apps/api/src/github-integration/controllers/create-github-integration.tsindex e61d6dcb8..c050df2f4 100644--- a/apps/api/src/github-integration/controllers/create-github-integration.ts+++ b/apps/api/src/github-integration/controllers/create-github-integration.ts@@ -1,27 +1,25 @@import { and, eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";+import * as v from "valibot";import db from "../../database";import { integrationTable, projectTable } from "../../database/schema";-import { defaultGitHubConfig } from "../../plugins/github/config";-import { getGithubApp } from "../../plugins/github/utils/github-app";+import {+ defaultGitHubConfig,+ githubConfigSchema,+} from "../../plugins/github/config";+import { verifyRepositoryOwner } from "./verify-repository-owner";async function createGithubIntegration({+ userId,projectId,repositoryOwner,repositoryName,}: {+ userId: string;projectId: string;repositoryOwner: string;repositoryName: string;}) {- const githubApp = getGithubApp();-- if (!githubApp) {- throw new HTTPException(500, {- message: "GitHub app not configured",- });- }-const project = await db.query.projectTable.findFirst({where: eq(projectTable.id, projectId),});@@ -30,43 +28,12 @@ async function createGithubIntegration({throw new HTTPException(404, { message: "Project not found" });}- const allGitHubIntegrations = await db.query.integrationTable.findMany({- where: eq(integrationTable.type, "github"),- });-- for (const integration of allGitHubIntegrations) {- if (integration.projectId === projectId) {- continue;- }-- try {- const config = JSON.parse(integration.config);- if (- config.repositoryOwner === repositoryOwner &&- config.repositoryName === repositoryName- ) {- throw new HTTPException(409, {- message: `Repository ${repositoryOwner}/${repositoryName} is already linked to another project`,- });- }- } catch (error) {- if (error instanceof HTTPException) {- throw error;- }- }- }-- let installationId: number | null = null;- try {- const { data: installation } =- await githubApp.octokit.rest.apps.getRepoInstallation({- owner: repositoryOwner,- repo: repositoryName,- });- installationId = installation.id;- } catch (error) {- console.warn("Could not get installation ID for repository:", error);- }+ const binding = await verifyRepositoryOwner(+ userId,+ repositoryOwner,+ repositoryName,+ );+ const { installationId } = binding;const existingIntegration = await db.query.integrationTable.findFirst({where: and(@@ -75,12 +42,34 @@ async function createGithubIntegration({),});- const config = {- repositoryOwner,- repositoryName,- installationId,- ...defaultGitHubConfig,- };+ let previousConfig = {};+ if (existingIntegration) {+ let previous: unknown;+ try {+ previous = JSON.parse(existingIntegration.config);+ } catch {+ previous = null;+ }+ const parsed = v.safeParse(githubConfigSchema, previous);+ const sameRepository =+ parsed.success &&+ (parsed.output.repositoryId !== undefined+ ? parsed.output.repositoryId === binding.repositoryId+ : parsed.output.repositoryOwner.toLowerCase() ===+ binding.repositoryOwner.toLowerCase() &&+ parsed.output.repositoryName.toLowerCase() ===+ binding.repositoryName.toLowerCase());+ if (!sameRepository) {+ // External issue/PR numbers are scoped to a repository. Reusing this+ // integration ID would reinterpret its existing links in another repo.+ throw new HTTPException(409, {+ message:+ "Disconnect the current GitHub integration before connecting a different repository",+ });+ }+ if (parsed.success) previousConfig = parsed.output;+ }+ const config = { ...defaultGitHubConfig, ...previousConfig, ...binding };if (existingIntegration) {const [updatedIntegration] = await db@@ -92,18 +81,24 @@ async function createGithubIntegration({}).where(and(- eq(integrationTable.projectId, projectId),- eq(integrationTable.type, "github"),+ eq(integrationTable.id, existingIntegration.id),+ eq(integrationTable.config, existingIntegration.config),),).returning();+ if (!updatedIntegration)+ throw new HTTPException(409, {+ message: "GitHub integration changed; refresh before reconnecting",+ });+return {- id: updatedIntegration?.id,+ id: updatedIntegration.id,projectId: updatedIntegration?.projectId,- repositoryOwner,- repositoryName,+ repositoryOwner: binding.repositoryOwner,+ repositoryName: binding.repositoryName,installationId,+ requiresVerification: false,isActive: updatedIntegration?.isActive,createdAt: updatedIntegration?.createdAt,updatedAt: updatedIntegration?.updatedAt,@@ -123,9 +118,10 @@ async function createGithubIntegration({return {id: newIntegration?.id,projectId: newIntegration?.projectId,- repositoryOwner,- repositoryName,+ repositoryOwner: binding.repositoryOwner,+ repositoryName: binding.repositoryName,installationId,+ requiresVerification: false,isActive: newIntegration?.isActive,createdAt: newIntegration?.createdAt,updatedAt: newIntegration?.updatedAt,diff --git a/apps/api/src/github-integration/controllers/delete-github-integration.ts b/apps/api/src/github-integration/controllers/delete-github-integration.tsindex a2fc1ab10..fa6edfd2b 100644--- a/apps/api/src/github-integration/controllers/delete-github-integration.ts+++ b/apps/api/src/github-integration/controllers/delete-github-integration.ts@@ -17,12 +17,7 @@ async function deleteGithubIntegration(projectId: string) {await db.delete(integrationTable)- .where(- and(- eq(integrationTable.projectId, projectId),- eq(integrationTable.type, "github"),- ),- );+ .where(eq(integrationTable.id, existingIntegration.id));return { success: true, message: "GitHub integration deleted" };}diff --git a/apps/api/src/github-integration/controllers/get-github-integration.ts b/apps/api/src/github-integration/controllers/get-github-integration.tsindex 5cc0c5108..07ce39ecf 100644--- a/apps/api/src/github-integration/controllers/get-github-integration.ts+++ b/apps/api/src/github-integration/controllers/get-github-integration.ts@@ -1,11 +1,14 @@import { and, eq } from "drizzle-orm";import db from "../../database";-import { integrationTable } from "../../database/schema";+import { githubImportTable, integrationTable } from "../../database/schema";import {defaultGitHubConfig,type GitHubConfig,+ hasVerifiedGitHubBinding,} from "../../plugins/github/config";+import { importProgress } from "../import-state";+async function getGithubIntegration(projectId: string) {const integration = await db.query.integrationTable.findFirst({where: and(@@ -20,7 +23,14 @@ async function getGithubIntegration(projectId: string) {const config = JSON.parse(integration.config) as GitHubConfig;+ const run = await db.query.githubImportTable.findFirst({+ where: eq(githubImportTable.integrationId, integration.id),+ });+return {+ ...(run && run.state.repositoryId === config.repositoryId+ ? { importProgress: importProgress(run.runId, run.state) }+ : {}),id: integration.id,projectId: integration.projectId,repositoryOwner: config.repositoryOwner,@@ -28,7 +38,8 @@ async function getGithubIntegration(projectId: string) {installationId: config.installationId,branchPattern: config.branchPattern || defaultGitHubConfig.branchPattern,commentTaskLinkOnGitHubIssue: config.commentTaskLinkOnGitHubIssue !== false,- isActive: integration.isActive,+ isActive: integration.isActive && hasVerifiedGitHubBinding(config),+ requiresVerification: !hasVerifiedGitHubBinding(config),createdAt: integration.createdAt,updatedAt: integration.updatedAt,};diff --git a/apps/api/src/github-integration/controllers/import-issues.ts b/apps/api/src/github-integration/controllers/import-issues.tsindex e5bb4b6e3..b12bd4f49 100644--- a/apps/api/src/github-integration/controllers/import-issues.ts+++ b/apps/api/src/github-integration/controllers/import-issues.ts@@ -1,399 +1,514 @@-import { and, eq } from "drizzle-orm";+import { createId } from "@paralleldrive/cuid2";+import { and, asc, eq, isNull } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import {activityTable,+ columnTable,+ externalLinkTable,+ githubImportTable,integrationTable,labelTable,projectTable,taskTable,} from "../../database/schema";-import type { GitHubConfig } from "../../plugins/github/config";import {- createExternalLink,- findExternalLink,-} from "../../plugins/github/services/link-manager";-import { findTaskByNumber } from "../../plugins/github/services/task-service";+ type GitHubConfig,+ hasVerifiedGitHubBinding,+} from "../../plugins/github/config";import { extractTaskNumber } from "../../plugins/github/utils/branch-matcher";import {extractIssuePriority,extractIssueStatus,} from "../../plugins/github/utils/extract-priority";import { formatTaskDescriptionFromIssue } from "../../plugins/github/utils/format";-import { getInstallationOctokit } from "../../plugins/github/utils/github-app";+import { getVerifiedInstallationOctokit } from "../../plugins/github/utils/github-app";import { claimTaskNumber } from "../../task/controllers/claim-task-numbers";--type ImportResult = {- imported: number;- updated: number;- skipped: number;- errors?: string[];-};--type GitHubIssue = {- number: number;- title: string;- body: string | null;- html_url: string;- state: string;- labels: Array<{ name?: string; color?: string } | string>;- user: { login: string; avatar_url: string } | null;- pull_request?: unknown;-};--type GitHubComment = {- id: number;- body: string;- html_url: string;- user: { login: string; avatar_url: string } | null;- created_at: string;-};--type GitHubPullRequest = {- number: number;- title: string;- body: string | null;- html_url: string;- state: string;- head: { ref: string };- user: { login: string; avatar_url: string } | null;-};--export async function importIssues(projectId: string): Promise<ImportResult> {- const errors: string[] = [];- let imported = 0;- let updated = 0;- let skipped = 0;-- const project = await db.query.projectTable.findFirst({- where: eq(projectTable.id, projectId),- });-- if (!project) {- throw new HTTPException(404, { message: "Project not found" });+import { VIRTUAL_STATUSES } from "../../task/validate-task-fields";+import { withGithubImportLock } from "../import-lock";+import {+ commentsPageSchema,+ fetchImportPage,+ IMPORT_PAGES_PER_REQUEST,+ type ImportedComment,+ type ImportedIssue,+ type ImportedLabel,+ type ImportedPull,+ issuesPageSchema,+ labelsPageSchema,+ nextCursor,+ pullsPageSchema,+} from "../import-pages";+import {+ type GitHubImportState,+ importProgress,+ initialImportState,+} from "../import-state";++type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];+async function resolveImportedStatus(+ tx: Transaction,+ projectId: string,+ requested: string | null,+ current?: string,+) {+ for (const status of [requested, current, "to-do"]) {+ if (!status) continue;+ const column = await tx.query.columnTable.findFirst({+ where: and(+ eq(columnTable.projectId, projectId),+ eq(columnTable.slug, status),+ ),+ columns: { id: true },+ });+ if (column) return { status, columnId: column.id };+ if ((VIRTUAL_STATUSES as readonly string[]).includes(status))+ return { status, columnId: null };}-- const integration = await db.query.integrationTable.findFirst({- where: and(- eq(integrationTable.projectId, projectId),- eq(integrationTable.type, "github"),- ),+ const first = await tx.query.columnTable.findFirst({+ where: eq(columnTable.projectId, projectId),+ orderBy: asc(columnTable.position),+ columns: { id: true, slug: true },});-- if (!integration) {- throw new HTTPException(404, { message: "GitHub integration not found" });- }-- if (!integration.isActive) {+ return { status: first?.slug ?? "planned", columnId: first?.id ?? null };+}+function readConfig(integration: typeof integrationTable.$inferSelect) {+ if (!integration.isActive)throw new HTTPException(400, {message: "GitHub integration is not active",});- }-- const config = JSON.parse(integration.config) as GitHubConfig;-- if (!config.installationId) {+ let config: GitHubConfig;+ try {+ config = JSON.parse(integration.config);+ } catch {throw new HTTPException(400, {- message: "GitHub installation ID not configured",+ message: "Invalid GitHub integration configuration",});}-- const octokit = await getInstallationOctokit(config.installationId);-- const allIssues: GitHubIssue[] = [];- let page = 1;- const perPage = 100;-- while (true) {- const { data: issues } = await octokit.rest.issues.listForRepo({- owner: config.repositoryOwner,- repo: config.repositoryName,- state: "open",- per_page: perPage,- page,+ if (!hasVerifiedGitHubBinding(config) || !config.installationId)+ throw new HTTPException(400, {+ message:+ "GitHub integration must be reconnected by a repository administrator",});+ return config;+}+function conflict() {+ return new HTTPException(409, {+ message: "GitHub integration or import changed; refresh before resuming",+ });+}- if (issues.length === 0) break;-- const issuesOnly = issues.filter(- (issue) => !issue.pull_request,- ) as GitHubIssue[];- allIssues.push(...issuesOnly);-- if (issues.length < perPage) break;- page++;- }-- for (const issue of allIssues) {+export async function importIssues(projectId: string, runId?: string) {+ return withGithubImportLock(projectId, async () => {+ const project = await db.query.projectTable.findFirst({+ where: eq(projectTable.id, projectId),+ });+ if (!project)+ throw new HTTPException(404, { message: "Project not found" });+ const integration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "github"),+ ),+ });+ if (!integration)+ throw new HTTPException(404, { message: "GitHub integration not found" });+ const config = readConfig(integration);+ const repositoryId = config.repositoryId;+ if (!repositoryId) throw conflict();+ let run = await db.query.githubImportTable.findFirst({+ where: eq(githubImportTable.integrationId, integration.id),+ });+ if (+ runId &&+ (!run || run.runId !== runId || run.state.repositoryId !== repositoryId)+ )+ throw conflict();+ if (runId && run?.state.phase === "complete")+ return importProgress(run.runId, run.state);+ if (+ !run ||+ run.state.phase === "complete" ||+ run.state.repositoryId !== repositoryId+ ) {+ const [created] = await db+ .insert(githubImportTable)+ .values({+ integrationId: integration.id,+ state: initialImportState(repositoryId),+ })+ .onConflictDoUpdate({+ target: githubImportTable.integrationId,+ set: {+ runId: createId(),+ state: initialImportState(repositoryId),+ updatedAt: new Date(),+ },+ })+ .returning();+ run = created;+ }+ if (!run) throw new Error("Failed to start import");+ let octokit: Awaited<ReturnType<typeof getVerifiedInstallationOctokit>>;try {- const result = await importSingleIssue(- issue,- integration.id,- projectId,- project.workspaceId,- config,- octokit,- );+ octokit = await getVerifiedInstallationOctokit(config, true);+ } catch {+ throw new HTTPException(502, {+ message:+ "GitHub repository could not be verified; check the integration and resume",+ });+ }+ for (+ let page = 0;+ page < IMPORT_PAGES_PER_REQUEST && run.state.phase !== "complete";+ page+++ ) {+ let payload: unknown;+ try {+ payload = await fetchImportPage(octokit, config, run.state);+ } catch {+ throw new HTTPException(502, {+ message: "GitHub import paused; retry to resume saved progress",+ });+ }+ const currentRun: typeof githubImportTable.$inferSelect = run;+ run = await db.transaction(async (tx) => {+ // Serialize against integration changes and webhook issue creation. No+ // provider request is made while this transaction holds row locks.+ const [currentIntegration] = await tx+ .select()+ .from(integrationTable)+ .where(eq(integrationTable.id, integration.id))+ .for("update");+ if (+ !currentIntegration ||+ currentIntegration.config !== integration.config ||+ !currentIntegration.isActive+ )+ throw conflict();+ const state = structuredClone(currentRun.state);+ await applyPage(tx, payload, state, integration.id, project, config);+ const [saved] = await tx+ .update(githubImportTable)+ .set({ state })+ .where(+ and(+ eq(githubImportTable.integrationId, integration.id),+ eq(githubImportTable.runId, currentRun.runId),+ ),+ )+ .returning();+ if (!saved) throw conflict();+ return saved;+ });+ }+ return importProgress(run.runId, run.state);+ });+}- if (result === "imported") {- imported++;- } else if (result === "updated") {- updated++;- } else {- skipped++;+function finishIssue(state: GitHubImportState) {+ state.currentIssue = null;+ state.phase = state.moreIssues ? "issues" : "pulls";+}+function nextIssuePart(state: GitHubImportState) {+ const current = state.currentIssue;+ if (current && current.labelsRemaining > 0) state.phase = "labels";+ else if (current?.moreComments && current.commentsRemaining > 0)+ state.phase = "comments";+ else finishIssue(state);+}+function repositoryMatches(actual: number, state: GitHubImportState) {+ if (actual !== state.repositoryId) throw conflict();+}+function pageError() {+ return new HTTPException(502, {+ message:+ "GitHub returned an invalid import page; saved progress can be resumed",+ });+}+function cursor(+ info: { hasNextPage: boolean; endCursor: string | null },+ previous: string | null,+) {+ try {+ return nextCursor(info, previous);+ } catch {+ throw pageError();+ }+}+async function applyPage(+ tx: Transaction,+ payload: unknown,+ state: GitHubImportState,+ integrationId: string,+ project: typeof projectTable.$inferSelect,+ config: GitHubConfig,+) {+ if (state.phase === "issues") {+ const parsed = issuesPageSchema.safeParse(payload);+ if (!parsed.success) throw pageError();+ repositoryMatches(parsed.data.repository.databaseId, state);+ const page = parsed.data.repository.issues;+ state.issueCursor = cursor(page.pageInfo, state.issueCursor);+ state.moreIssues = page.pageInfo.hasNextPage;+ const issue = page.nodes[0];+ if (!issue || Date.parse(issue.createdAt) > Date.parse(state.startedAt)) {+ state.moreIssues = false;+ finishIssue(state);+ return;+ }+ const task = await importIssue(tx, issue, integrationId, project.id);+ if (!task) {+ state.skipped++;+ finishIssue(state);+ return;+ }+ state[task.result]++;+ const labelsRemaining = pageRemaining(issue.labels);+ const commentsRemaining = pageRemaining(issue.comments);+ state.currentIssue = {+ number: issue.number,+ taskId: task.id,+ labelCursor: cursor(issue.labels.pageInfo, null),+ commentCursor: cursor(issue.comments.pageInfo, null),+ labelsRemaining,+ commentsRemaining,+ moreComments: issue.comments.pageInfo.hasNextPage,+ statusSeen: issue.labels.nodes.some((label) =>+ label.name.startsWith("status:"),+ ),+ prioritySeen: issue.labels.nodes.some((label) =>+ label.name.startsWith("priority:"),+ ),+ };+ await importLabels(tx, issue.labels.nodes, task.id, project.workspaceId);+ await importComments(tx, issue.comments.nodes, task.id, state.startedAt);+ nextIssuePart(state);+ return;+ }+ if (state.phase === "pulls") {+ const parsed = pullsPageSchema.safeParse(payload);+ if (!parsed.success) throw pageError();+ repositoryMatches(parsed.data.repository.databaseId, state);+ const page = parsed.data.repository.pullRequests;+ state.pullCursor = cursor(page.pageInfo, state.pullCursor);+ for (const pull of page.nodes) {+ if (Date.parse(pull.createdAt) > Date.parse(state.startedAt)) {+ state.phase = "complete";+ return;}- } catch (error) {- const errorMessage =- error instanceof Error ? error.message : String(error);- errors.push(`Issue #${issue.number}: ${errorMessage}`);+ await linkPull(tx, pull, integrationId, project, config);}+ if (!page.pageInfo.hasNextPage || page.nodes.length === 0)+ state.phase = "complete";+ return;}-- const allPRs: GitHubPullRequest[] = [];- page = 1;-- while (true) {- const { data: pulls } = await octokit.rest.pulls.list({- owner: config.repositoryOwner,- repo: config.repositoryName,- state: "open",- per_page: perPage,- page,- });-- if (pulls.length === 0) break;-- allPRs.push(...(pulls as GitHubPullRequest[]));-- if (pulls.length < perPage) break;- page++;+ const current = state.currentIssue;+ if (!current) throw new Error("Import continuation missing");+ const task = await tx.query.taskTable.findFirst({+ where: and(+ eq(taskTable.id, current.taskId),+ eq(taskTable.projectId, project.id),+ ),+ });+ if (!task) {+ state.skipped++;+ finishIssue(state);+ return;}-- for (const pr of allPRs) {- try {- await linkPullRequestToTask(- pr,- integration.id,- projectId,- project.slug,- config,- );- } catch (error) {- const errorMessage =- error instanceof Error ? error.message : String(error);- errors.push(`PR #${pr.number}: ${errorMessage}`);+ if (state.phase === "labels") {+ const parsed = labelsPageSchema.safeParse(payload);+ if (!parsed.success) throw pageError();+ repositoryMatches(parsed.data.repository.databaseId, state);+ const page = parsed.data.repository.issue?.labels;+ if (!page) {+ state.skipped++;+ finishIssue(state);+ return;+ }+ const labels = page.nodes.slice(0, current.labelsRemaining);+ current.labelCursor = cursor(page.pageInfo, current.labelCursor);+ current.labelsRemaining =+ page.pageInfo.hasNextPage && labels.length+ ? Math.max(0, current.labelsRemaining - labels.length)+ : 0;+ const priority = current.prioritySeen ? null : extractIssuePriority(labels);+ const status = current.statusSeen ? null : extractIssueStatus(labels);+ if (priority || status)+ await tx+ .update(taskTable)+ .set({+ ...(priority ? { priority } : {}),+ ...(status+ ? await resolveImportedStatus(tx, project.id, status, task.status)+ : {}),+ })+ .where(+ and(eq(taskTable.id, task.id), eq(taskTable.projectId, project.id)),+ );+ current.prioritySeen ||= labels.some((label) =>+ label.name.startsWith("priority:"),+ );+ current.statusSeen ||= labels.some((label) =>+ label.name.startsWith("status:"),+ );+ await importLabels(tx, labels, task.id, project.workspaceId);+ nextIssuePart(state);+ } else if (state.phase === "comments") {+ const parsed = commentsPageSchema.safeParse(payload);+ if (!parsed.success) throw pageError();+ repositoryMatches(parsed.data.repository.databaseId, state);+ const page = parsed.data.repository.issue?.comments;+ if (!page) {+ state.skipped++;+ finishIssue(state);+ return;}+ const comments = page.nodes.slice(0, current.commentsRemaining);+ current.commentCursor = cursor(page.pageInfo, current.commentCursor);+ current.commentsRemaining = Math.max(+ 0,+ current.commentsRemaining - comments.length,+ );+ current.moreComments = page.pageInfo.hasNextPage && comments.length > 0;+ await importComments(tx, comments, task.id, state.startedAt);+ nextIssuePart(state);}-- return {- imported,- updated,- skipped,- ...(errors.length > 0 ? { errors } : {}),- };}--async function importSingleIssue(- issue: GitHubIssue,+function pageRemaining(page: {+ totalCount: number;+ nodes: unknown[];+ pageInfo: { hasNextPage: boolean };+}) {+ return page.pageInfo.hasNextPage+ ? Math.max(0, page.totalCount - page.nodes.length)+ : 0;+}+async function findLink(+ tx: Transaction,+ integrationId: string,+ resourceType: string,+ externalId: number,+) {+ return tx.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.integrationId, integrationId),+ eq(externalLinkTable.resourceType, resourceType),+ eq(externalLinkTable.externalId, String(externalId)),+ ),+ });+}+async function importIssue(+ tx: Transaction,+ issue: ImportedIssue,integrationId: string,projectId: string,- workspaceId: string,- config: GitHubConfig,- octokit: Awaited<ReturnType<typeof getInstallationOctokit>>,-): Promise<"imported" | "updated" | "skipped"> {- const existingLink = await findExternalLink(- integrationId,- "issue",- issue.number.toString(),- );-- const priority = extractIssuePriority(issue.labels);- const status = extractIssueStatus(issue.labels);-- if (existingLink) {- const updateData: Record<string, unknown> = {- title: issue.title,- description: formatTaskDescriptionFromIssue(issue.body),- };-- if (priority) updateData.priority = priority;- if (status) updateData.status = status;-- await db+): Promise<{ id: string; result: "imported" | "updated" } | null> {+ const link = await findLink(tx, integrationId, "issue", issue.number);+ const priority = extractIssuePriority(issue.labels.nodes);+ const status = extractIssueStatus(issue.labels.nodes);+ if (link) {+ const task = await tx.query.taskTable.findFirst({+ where: and(+ eq(taskTable.id, link.taskId),+ eq(taskTable.projectId, projectId),+ ),+ });+ if (!task) return null;+ const [updated] = await tx.update(taskTable)- .set(updateData)- .where(eq(taskTable.id, existingLink.taskId));-- await importLabelsForTask(issue.labels, existingLink.taskId, workspaceId);-- await importCommentsForTask(- issue.number,- existingLink.taskId,- config,- octokit,- );-- return "updated";+ .set({+ title: issue.title,+ description: formatTaskDescriptionFromIssue(issue.body, task.id),+ ...(await resolveImportedStatus(tx, projectId, status, task.status)),+ ...(priority ? { priority } : {}),+ })+ .where(and(eq(taskTable.id, task.id), eq(taskTable.projectId, projectId)))+ .returning({ id: taskTable.id });+ return updated ? { id: updated.id, result: "updated" } : null;}-- const nextTaskNumber = await claimTaskNumber(projectId);-- const taskValues: typeof taskTable.$inferInsert = {- projectId,- userId: null,- title: issue.title,- description: formatTaskDescriptionFromIssue(issue.body),- status: status || "to-do",- priority: priority ?? "low",- number: nextTaskNumber,- };-- const [createdTask] = await db+ const number = await claimTaskNumber(projectId, tx);+ const [created] = await tx.insert(taskTable)- .values(taskValues)- .returning();-- if (!createdTask) {- throw new Error("Failed to create task");- }-- await createExternalLink({- taskId: createdTask.id,+ .values({+ projectId,+ userId: null,+ title: issue.title,+ description: formatTaskDescriptionFromIssue(issue.body),+ ...(await resolveImportedStatus(tx, projectId, status)),+ priority: priority ?? "low",+ number,+ })+ .returning({ id: taskTable.id });+ if (!created) throw new Error("Failed to create imported task");+ await tx.insert(externalLinkTable).values({+ taskId: created.id,integrationId,resourceType: "issue",- externalId: issue.number.toString(),- url: issue.html_url,+ externalId: String(issue.number),+ url: issue.url,title: issue.title,- metadata: {- state: issue.state,+ metadata: JSON.stringify({+ state: issue.state.toLowerCase(),createdFrom: "github-import",- author: issue.user?.login,- },+ author: issue.author?.login,+ }),});-- await importLabelsForTask(issue.labels, createdTask.id, workspaceId);-- await importCommentsForTask(issue.number, createdTask.id, config, octokit);-- return "imported";+ return { id: created.id, result: "imported" };}--async function importLabelsForTask(- issueLabels: GitHubIssue["labels"],+async function importLabels(+ tx: Transaction,+ labels: ImportedLabel[],taskId: string,workspaceId: string,-): Promise<void> {- const nonSystemLabels = issueLabels- .map((label) => {- if (typeof label === "string") {- return { name: label, color: "#6B7280" };- }- return {- name: label.name,- color: label.color ? `#${label.color}` : "#6B7280",- };- })- .filter(- (label) =>- label.name &&- !label.name.startsWith("priority:") &&- !label.name.startsWith("status:"),- ) as Array<{ name: string; color: string }>;-- for (const labelData of nonSystemLabels) {- const existingLabelOnTask = await db.query.labelTable.findFirst({- where: and(- eq(labelTable.taskId, taskId),- eq(labelTable.name, labelData.name),- ),- });-- if (existingLabelOnTask) {+) {+ for (const label of labels) {+ if (label.name.startsWith("priority:") || label.name.startsWith("status:"))continue;- }-- const existingWorkspaceLabel = await db.query.labelTable.findFirst({+ const root = await tx.query.labelTable.findFirst({where: and(eq(labelTable.workspaceId, workspaceId),- eq(labelTable.name, labelData.name),+ eq(labelTable.name, label.name),+ isNull(labelTable.taskId),),});-- const colorToUse = existingWorkspaceLabel?.color || labelData.color;-- await db+ await tx.insert(labelTable).values({- name: labelData.name,- color: colorToUse,+ name: label.name,+ color: root?.color || `#${label.color}`,taskId,workspaceId,})- .onConflictDoNothing({- target: [labelTable.taskId, labelTable.name],- });+ .onConflictDoNothing({ target: [labelTable.taskId, labelTable.name] });}}--async function importCommentsForTask(- issueNumber: number,+async function importComments(+ tx: Transaction,+ comments: ImportedComment[],taskId: string,- config: GitHubConfig,- octokit: Awaited<ReturnType<typeof getInstallationOctokit>>,-): Promise<void> {- const allComments: GitHubComment[] = [];- let page = 1;- const perPage = 100;-- while (true) {- const { data: comments } = await octokit.rest.issues.listComments({- owner: config.repositoryOwner,- repo: config.repositoryName,- issue_number: issueNumber,- per_page: perPage,- page,- });-- if (comments.length === 0) break;-- allComments.push(...(comments as GitHubComment[]));-- if (comments.length < perPage) break;- page++;- }-- const existingActivities = await db.query.activityTable.findMany({- where: and(- eq(activityTable.taskId, taskId),- eq(activityTable.externalSource, "github"),- ),- });-- const existingExternalUrls = new Set(- existingActivities.filter((a) => a.externalUrl).map((a) => a.externalUrl),- );-- for (const comment of allComments) {- const username = comment.user?.login ?? "";- if (username.endsWith("[bot]")) {- continue;- }-- if (existingExternalUrls.has(comment.html_url)) {- continue;- }-- await db+ startedAt: string,+) {+ const values = comments+ .filter(+ (comment) =>+ comment.author?.__typename !== "Bot" &&+ !comment.author?.login.endsWith("[bot]") &&+ Date.parse(comment.createdAt) <= Date.parse(startedAt),+ )+ .map((comment) => ({+ taskId,+ type: "comment",+ content: comment.body,+ externalUserName: comment.author?.login ?? "Unknown",+ externalUserAvatar: comment.author?.avatarUrl ?? null,+ externalSource: "github",+ externalUrl: comment.url,+ }));+ if (values.length)+ await tx.insert(activityTable)- .values({- taskId,- type: "comment",- content: comment.body,- externalUserName: comment.user?.login ?? "Unknown",- externalUserAvatar: comment.user?.avatar_url ?? null,- externalSource: "github",- externalUrl: comment.html_url,- })+ .values(values).onConflictDoNothing({target: [activityTable.taskId,@@ -401,55 +516,44 @@ async function importCommentsForTask(activityTable.externalUrl,],});- }}--async function linkPullRequestToTask(- pr: GitHubPullRequest,+async function linkPull(+ tx: Transaction,+ pull: ImportedPull,integrationId: string,- projectId: string,- projectSlug: string,+ project: typeof projectTable.$inferSelect,config: GitHubConfig,-): Promise<void> {- const taskNumber = extractTaskNumber(- pr.head.ref,- pr.title,- pr.body ?? undefined,+) {+ const number = extractTaskNumber(+ pull.headRefName,+ pull.title,+ pull.body ?? undefined,config,- projectSlug,+ project.slug,);-- if (!taskNumber) {- return;- }-- const task = await findTaskByNumber(projectId, taskNumber);-- if (!task) {+ if (+ !number ||+ (await findLink(tx, integrationId, "pull_request", pull.number))+ )return;- }-- const existingLink = await findExternalLink(- integrationId,- "pull_request",- pr.number.toString(),- );-- if (existingLink) {- return;- }-- await createExternalLink({+ const task = await tx.query.taskTable.findFirst({+ where: and(+ eq(taskTable.projectId, project.id),+ eq(taskTable.number, number),+ ),+ });+ if (!task) return;+ await tx.insert(externalLinkTable).values({taskId: task.id,integrationId,resourceType: "pull_request",- externalId: pr.number.toString(),- url: pr.html_url,- title: pr.title,- metadata: {- state: pr.state,- branch: pr.head.ref,- author: pr.user?.login,- },+ externalId: String(pull.number),+ url: pull.url,+ title: pull.title,+ metadata: JSON.stringify({+ state: pull.state.toLowerCase(),+ branch: pull.headRefName,+ author: pull.author?.login,+ }),});}diff --git a/apps/api/src/github-integration/controllers/list-user-repositories.ts b/apps/api/src/github-integration/controllers/list-user-repositories.tsindex ffbab73e4..35ddfca17 100644--- a/apps/api/src/github-integration/controllers/list-user-repositories.ts+++ b/apps/api/src/github-integration/controllers/list-user-repositories.ts@@ -1,113 +1,105 @@import { HTTPException } from "hono/http-exception";import { getGithubApp } from "../../plugins/github/utils/github-app";+import { getGithubAccount } from "./verify-repository-owner";-async function listUserRepositories() {- const githubApp = getGithubApp();+export type RepositoryPage = {+ installationPage: number;+ repositoryPage: number;+};+const PAGE_SIZE = 20;- if (!githubApp) {- throw new HTTPException(500, {- message: "GitHub app not configured",+/** One bounded page. Never return other users' repository or installation metadata. */+async function listUserRepositories(userId: string, page: RepositoryPage) {+ const account = await getGithubAccount(userId);+ const app = getGithubApp(true);+ if (!app)+ throw new HTTPException(503, {+ message: "GitHub integration is unavailable",});+ const request = { timeout: 10_000 };+ const { data: installations } = await app.octokit.rest.apps.listInstallations(+ {+ per_page: 1,+ page: page.installationPage,+ request,+ },+ );+ const installation = installations[0];+ if (!installation)+ return { repositories: [], installations: [], total: 0, nextPage: null };+ const octokit = await app.getInstallationOctokit(installation.id);+ const { data: identity } = await octokit.rest.users.getById({+ account_id: Number(account.accountId),+ request,+ });+ if (String(identity.id) !== account.accountId)+ throw new HTTPException(403, {+ message: "GitHub identity could not be verified",+ });+ const { data } = await octokit.rest.apps.listReposAccessibleToInstallation({+ per_page: PAGE_SIZE,+ page: page.repositoryPage,+ request,+ });+ const repositories = [];+ // Bound concurrent requests as well as the total per page.+ for (let offset = 0; offset < data.repositories.length; offset += 4) {+ const candidates = data.repositories.slice(offset, offset + 4);+ const authorized = await Promise.all(+ candidates.map(async (repo) => {+ try {+ const { data: permission } =+ await octokit.rest.repos.getCollaboratorPermissionLevel({+ owner: repo.owner.login,+ repo: repo.name,+ username: identity.login,+ request,+ });+ if (permission.permission !== "admin") return null;+ return {+ id: repo.id,+ name: repo.name,+ full_name: repo.full_name,+ private: repo.private,+ owner: {+ login: repo.owner.login,+ avatar_url: repo.owner.avatar_url,+ type: repo.owner.type,+ },+ description: repo.description,+ html_url: repo.html_url,+ updated_at: repo.updated_at ?? "",+ installation_id: installation.id,+ };+ } catch (error) {+ if ((error as { status?: number }).status === 404) return null;+ throw new HTTPException(502, {+ message: "GitHub access verification is temporarily unavailable",+ });+ }+ }),+ );+ repositories.push(...authorized.filter((repo) => repo !== null));}-- try {- const { data: installations } =- await githubApp.octokit.rest.apps.listInstallations();-- const allRepositories = [];- const installationsWithRepos = [];-- for (const installation of installations) {- try {- const installationOctokit = await githubApp.getInstallationOctokit(- installation.id,- );-- // Use pagination to fetch ALL repositories for this installation- const repos = await installationOctokit.paginate(- installationOctokit.rest.apps.listReposAccessibleToInstallation,+ return {+ repositories,+ installations: repositories.length+ ? [{- per_page: 100, // GitHub's maximum- },- );-- // Store installation info with repository names for UI- installationsWithRepos.push({- id: installation.id,- account: installation.account- ? {- login: installation.account.login,- type: installation.account.type,- }- : null,- repositories: repos.map((repo) => repo.full_name),- });-- const mappedRepos = repos.map((repo) => ({- id: repo.id,- name: repo.name,- full_name: repo.full_name,- private: repo.private,- owner: {- login: repo.owner.login,- avatar_url: repo.owner.avatar_url,- type: repo.owner.type,+ id: installation.id,+ account: installation.account,+ repositories: repositories.map((repo) => repo.full_name),},- description: repo.description,- html_url: repo.html_url,- permissions: repo.permissions- ? {- admin: repo.permissions.admin,- push: repo.permissions.push,- pull: repo.permissions.pull,- }- : undefined,- updated_at: repo.updated_at || new Date().toISOString(),- installation_id: installation.id,- }));-- allRepositories.push(...mappedRepos);- } catch (error) {- console.warn(- `Failed to get repositories for installation ${installation.id}:`,- error,- );- // Still add installation info even if repo fetch fails- installationsWithRepos.push({- id: installation.id,- account: installation.account- ? {- login: installation.account.login,- type: installation.account.type,- }- : null,- repositories: [],- });- }- }-- // Remove duplicates and sort by most recently updated- const uniqueRepositories = allRepositories- .filter(- (repo, index, self) =>- index === self.findIndex((r) => r.id === repo.id),- )- .sort(- (a, b) =>- new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime(),- );-- return {- repositories: uniqueRepositories,- installations: installationsWithRepos,- total: uniqueRepositories.length,- };- } catch (error) {- console.error("Failed to list user repositories:", error);- throw new HTTPException(500, {- message: "Failed to fetch repositories from GitHub",- });- }+ ]+ : [],+ total: repositories.length,+ nextPage:+ data.repositories.length === PAGE_SIZE+ ? {+ installationPage: page.installationPage,+ repositoryPage: page.repositoryPage + 1,+ }+ : { installationPage: page.installationPage + 1, repositoryPage: 1 },+ };}-export default listUserRepositories;diff --git a/apps/api/src/github-integration/controllers/verify-repository-owner.ts b/apps/api/src/github-integration/controllers/verify-repository-owner.tsnew file mode 100644index 000000000..4b41b48ee--- /dev/null+++ b/apps/api/src/github-integration/controllers/verify-repository-owner.ts@@ -0,0 +1,75 @@+import { and, eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import { accountTable } from "../../database/schema";+import { getGithubApp } from "../../plugins/github/utils/github-app";++/** Account IDs come from completed OAuth, never from submitted repository data. */+export async function verifyRepositoryOwner(+ userId: string,+ repositoryOwner: string,+ repositoryName: string,+) {+ const account = await getGithubAccount(userId);+ const accountId = Number(account.accountId);+ const app = getGithubApp();+ if (!app)+ throw new HTTPException(503, {+ message: "GitHub integration is unavailable",+ });+ try {+ const { data: installation } =+ await app.octokit.rest.apps.getRepoInstallation({+ owner: repositoryOwner,+ repo: repositoryName,+ });+ const octokit = await app.getInstallationOctokit(installation.id);+ const { data: user } = await octokit.rest.users.getById({+ account_id: accountId,+ });+ if (user.id !== accountId) throw new Error("GitHub identity mismatch");+ const { data: permission } =+ await octokit.rest.repos.getCollaboratorPermissionLevel({+ owner: repositoryOwner,+ repo: repositoryName,+ username: user.login,+ });+ if (permission.permission !== "admin") {+ throw new Error("GitHub repository admin permission is required");+ }+ const { data: repository } = await octokit.rest.repos.get({+ owner: repositoryOwner,+ repo: repositoryName,+ });+ return {+ installationId: installation.id,+ repositoryId: repository.id,+ repositoryOwner: repository.owner.login,+ repositoryName: repository.name,+ verifiedGithubAccountId: account.accountId,+ verifiedByUserId: userId,+ };+ } catch {+ // Do not expose installation or repository existence to unauthorized users.+ throw new HTTPException(403, {+ message:+ "Repository access could not be verified. GitHub repository admin permission and an installed Kaneo App are required",+ });+ }+}++export async function getGithubAccount(userId: string) {+ const account = await db.query.accountTable.findFirst({+ where: and(+ eq(accountTable.userId, userId),+ eq(accountTable.providerId, "github"),+ ),+ });+ const accountId = Number(account?.accountId);+ if (!account || !Number.isSafeInteger(accountId) || accountId <= 0) {+ throw new HTTPException(403, {+ message: "Connect your GitHub account before linking a repository",+ });+ }+ return account;+}diff --git a/apps/api/src/github-integration/import-lock.ts b/apps/api/src/github-integration/import-lock.tsnew file mode 100644index 000000000..b4442d610--- /dev/null+++ b/apps/api/src/github-integration/import-lock.ts@@ -0,0 +1,77 @@+import { HTTPException } from "hono/http-exception";+import type { PoolClient } from "pg";+import { getDatabasePool } from "../database";++export const MAX_GITHUB_IMPORTS_IN_FLIGHT = 2;+const LOCK_NAMESPACE = 773623;+let active = 0;++function busy() {+ return new HTTPException(429, {+ res: new Response("GitHub import is busy; retry this request", {+ status: 429,+ headers: { "Retry-After": "1" },+ }),+ });+}++/** Session locks span awaited provider calls without holding a SQL transaction. */+export async function withGithubImportLock<T>(+ id: string,+ run: () => Promise<T>,+): Promise<T> {+ if (active >= MAX_GITHUB_IMPORTS_IN_FLIGHT) throw busy();+ active++;+ let client: PoolClient | undefined;+ let slot: number | undefined;+ let importLocked = false;+ let releaseError: Error | undefined;+ try {+ client = await getDatabasePool().connect();+ for (+ let candidate = 0;+ candidate < MAX_GITHUB_IMPORTS_IN_FLIGHT;+ candidate+++ ) {+ const { rows } = await client.query(+ "SELECT pg_try_advisory_lock($1::int, $2::int) AS acquired",+ [LOCK_NAMESPACE, candidate],+ );+ if (rows[0]?.acquired) {+ slot = candidate;+ break;+ }+ }+ if (slot === undefined) throw busy();+ const { rows } = await client.query(+ "SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS acquired",+ [`github-import:${id}`],+ );+ importLocked = rows[0]?.acquired === true;+ if (!importLocked) throw busy();+ return await run();+ } finally {+ if (client) {+ try {+ if (importLocked)+ await client.query(+ "SELECT pg_advisory_unlock(hashtextextended($1, 0))",+ [`github-import:${id}`],+ );+ if (slot !== undefined)+ await client.query("SELECT pg_advisory_unlock($1::int, $2::int)", [+ LOCK_NAMESPACE,+ slot,+ ]);+ } catch (error) {+ // Destroy a connection whose lock release was not confirmed.+ releaseError =+ error instanceof Error+ ? error+ : new Error("Import lock release failed");+ }+ client.release(releaseError);+ }+ active--;+ }+}diff --git a/apps/api/src/github-integration/import-pages.ts b/apps/api/src/github-integration/import-pages.tsnew file mode 100644index 000000000..446c5d5db--- /dev/null+++ b/apps/api/src/github-integration/import-pages.ts@@ -0,0 +1,148 @@+import { z } from "zod";+import type { GitHubConfig } from "../plugins/github/config";+import type { getVerifiedInstallationOctokit } from "../plugins/github/utils/github-app";+import type { GitHubImportState } from "./import-state";++export const IMPORT_PAGES_PER_REQUEST = 4;+export const IMPORT_LABELS_PER_PAGE = 25;+export const IMPORT_COMMENTS_PER_PAGE = 20;+export const IMPORT_PULLS_PER_PAGE = 10;+const pageInfo = z.object({+ hasNextPage: z.boolean(),+ endCursor: z.string().max(2048).nullable(),+});+const actor = z+ .object({+ login: z.string().max(255),+ avatarUrl: z.string().max(4096),+ __typename: z.string(),+ })+ .nullable();+const label = z.object({+ name: z.string().max(1024),+ color: z.string().max(64),+});+const comment = z.object({+ body: z.string().max(1_000_000),+ url: z.string().max(4096),+ author: actor,+ createdAt: z.iso.datetime(),+});+function connection<T extends z.ZodType>(node: T, limit: number) {+ return z+ .object({+ totalCount: z.number().int().nonnegative(),+ pageInfo,+ nodes: z.array(node).max(limit),+ })+ .refine(+ (page) => !page.pageInfo.hasNextPage || page.nodes.length > 0,+ "An unfinished page must contain nodes",+ );+}+const labels = connection(label, IMPORT_LABELS_PER_PAGE);+const comments = connection(comment, IMPORT_COMMENTS_PER_PAGE);+const issue = z.object({+ number: z.number().int().positive(),+ title: z.string().max(4096),+ body: z.string().max(1_000_000).nullable(),+ url: z.string().max(4096),+ state: z.enum(["OPEN", "CLOSED"]),+ createdAt: z.iso.datetime(),+ author: actor,+ labels,+ comments,+});+const pull = z.object({+ number: z.number().int().positive(),+ title: z.string().max(4096),+ body: z.string().max(1_000_000).nullable(),+ url: z.string().max(4096),+ state: z.string(),+ createdAt: z.iso.datetime(),+ headRefName: z.string().max(4096),+ author: actor,+});+const repository = z.object({ databaseId: z.number().int().positive() });+export const issuesPageSchema = z.object({+ repository: repository.extend({ issues: connection(issue, 1) }),+});+export const labelsPageSchema = z.object({+ repository: repository.extend({ issue: z.object({ labels }).nullable() }),+});+export const commentsPageSchema = z.object({+ repository: repository.extend({ issue: z.object({ comments }).nullable() }),+});+export const pullsPageSchema = z.object({+ repository: repository.extend({+ pullRequests: connection(pull, IMPORT_PULLS_PER_PAGE),+ }),+});+export type ImportedIssue = z.infer<typeof issue>;+export type ImportedPull = z.infer<typeof pull>;+export type ImportedLabel = z.infer<typeof label>;+export type ImportedComment = z.infer<typeof comment>;++const actorFields = "author { __typename login avatarUrl }";+const pageFields = "totalCount pageInfo { hasNextPage endCursor }";+// Explicit first/after connections, never paginate() or an aggregate catalog.+export const importQueries = {+ issues: `query ImportIssues($owner: String!, $repo: String!, $cursor: String) {+ repository(owner: $owner, name: $repo) { databaseId+ issues(first: 1, after: $cursor, states: OPEN, orderBy: {field: CREATED_AT, direction: ASC}) {+ ${pageFields} nodes { number title body url state createdAt ${actorFields}+ labels(first: ${IMPORT_LABELS_PER_PAGE}) { ${pageFields} nodes { name color } }+ comments(first: ${IMPORT_COMMENTS_PER_PAGE}) { ${pageFields} nodes { body url createdAt ${actorFields} } }+ }+ }+ }+ }`,+ labels: `query ImportIssueLabels($owner: String!, $repo: String!, $number: Int!, $cursor: String) {+ repository(owner: $owner, name: $repo) { databaseId issue(number: $number) {+ labels(first: ${IMPORT_LABELS_PER_PAGE}, after: $cursor) { ${pageFields} nodes { name color } }+ } }+ }`,+ comments: `query ImportIssueComments($owner: String!, $repo: String!, $number: Int!, $cursor: String) {+ repository(owner: $owner, name: $repo) { databaseId issue(number: $number) {+ comments(first: ${IMPORT_COMMENTS_PER_PAGE}, after: $cursor) { ${pageFields} nodes { body url createdAt ${actorFields} } }+ } }+ }`,+ pulls: `query ImportPullRequests($owner: String!, $repo: String!, $cursor: String) {+ repository(owner: $owner, name: $repo) { databaseId+ pullRequests(first: ${IMPORT_PULLS_PER_PAGE}, after: $cursor, states: OPEN, orderBy: {field: CREATED_AT, direction: ASC}) {+ ${pageFields} nodes { number title body url state createdAt headRefName ${actorFields} }+ }+ }+ }`,+};++export async function fetchImportPage(+ octokit: Awaited<ReturnType<typeof getVerifiedInstallationOctokit>>,+ config: GitHubConfig,+ state: GitHubImportState,+): Promise<unknown> {+ if (state.phase === "complete") throw new Error("Import already completed");+ const cursor =+ state.phase === "issues"+ ? state.issueCursor+ : state.phase === "pulls"+ ? state.pullCursor+ : state.phase === "labels"+ ? state.currentIssue?.labelCursor+ : state.currentIssue?.commentCursor;+ return octokit.graphql(importQueries[state.phase], {+ owner: config.repositoryOwner,+ repo: config.repositoryName,+ cursor,+ ...(state.currentIssue ? { number: state.currentIssue.number } : {}),+ });+}++export function nextCursor(+ info: z.infer<typeof pageInfo>,+ previous: string | null,+) {+ if (info.hasNextPage && (!info.endCursor || info.endCursor === previous))+ throw new Error("GitHub returned a non-advancing import page");+ return info.endCursor;+}diff --git a/apps/api/src/github-integration/import-state.ts b/apps/api/src/github-integration/import-state.tsnew file mode 100644index 000000000..53c5f48d2--- /dev/null+++ b/apps/api/src/github-integration/import-state.ts@@ -0,0 +1,47 @@+export type GitHubImportState = {+ phase: "issues" | "labels" | "comments" | "pulls" | "complete";+ repositoryId: number;+ startedAt: string;+ issueCursor: string | null;+ pullCursor: string | null;+ moreIssues: boolean;+ currentIssue: {+ number: number;+ taskId: string;+ labelCursor: string | null;+ commentCursor: string | null;+ moreComments: boolean;+ labelsRemaining: number;+ commentsRemaining: number;+ statusSeen: boolean;+ prioritySeen: boolean;+ } | null;+ imported: number;+ updated: number;+ skipped: number;+};++export function initialImportState(repositoryId: number): GitHubImportState {+ return {+ phase: "issues",+ repositoryId,+ startedAt: new Date().toISOString(),+ issueCursor: null,+ pullCursor: null,+ moreIssues: true,+ currentIssue: null,+ imported: 0,+ updated: 0,+ skipped: 0,+ };+}++export function importProgress(runId: string, state: GitHubImportState) {+ return {+ runId,+ pending: state.phase !== "complete",+ imported: state.imported,+ updated: state.updated,+ skipped: state.skipped,+ };+}diff --git a/apps/api/src/github-integration/index.ts b/apps/api/src/github-integration/index.tsindex 4bd3dd9fa..b6cb39116 100644--- a/apps/api/src/github-integration/index.ts+++ b/apps/api/src/github-integration/index.ts@@ -2,9 +2,9 @@ import { and, eq } from "drizzle-orm";import type { Context } from "hono";import { HTTPException } from "hono/http-exception";import db from "../database";-import { integrationTable } from "../database/schema";+import { accountTable, integrationTable } from "../database/schema";import { scopeToProjectFromBody } from "../integrations/middleware";-import { projectIdBody, projectIdParam } from "../integrations/schema";+import { projectIdParam } from "../integrations/schema";import {apiRouter,type BaseVariables,@@ -17,6 +17,8 @@ import {validateGitHubConfig,} from "../plugins/github/config";import { handleGitHubWebhook } from "../plugins/github/webhook-handler";+import { isGithubSsoConfigured } from "../utils/github-sso-env";+import { requireUserSession } from "../utils/require-user-session";import { requireWorkspacePermission } from "../utils/require-workspace-permission";import { workspaceAccess } from "../utils/workspace-access-middleware";import createGithubIntegration from "./controllers/create-github-integration";@@ -25,6 +27,7 @@ import getGithubIntegration from "./controllers/get-github-integration";import { importIssues } from "./controllers/import-issues";import listUserRepositories from "./controllers/list-user-repositories";import verifyGithubInstallation from "./controllers/verify-github-installation";+import { verifyRepositoryOwner } from "./controllers/verify-repository-owner";import {createdGithubIntegrationSchema,deleteResultSchema,@@ -35,7 +38,13 @@ import {integrationNotFoundSchema,verificationResultSchema,} from "./response";-import { createGitHubBody, updateGitHubBody, verifyGitHubBody } from "./schema";+import {+ createGitHubBody,+ importGitHubBody,+ repositoryPageQuery,+ updateGitHubBody,+ verifyGitHubBody,+} from "./schema";const manageAccess = [workspaceAccess.fromProject("projectId"),@@ -63,8 +72,8 @@ const listRepositoriesRoute = createRoute({summary: "List GitHub repositories",description:"List the repositories reachable through the installed GitHub App, for picking one to link.",- middleware: manageAccess,- request: { params: projectIdParam },+ middleware: [requireUserSession, ...manageAccess],+ request: { params: projectIdParam, query: repositoryPageQuery },responses: {200: jsonResponse("Repositories reachable through the installed App",@@ -87,7 +96,11 @@ const verifyRoute = createRoute({summary: "Verify GitHub installation",description:"Check that the GitHub App is installed on a repository and holds the permissions Kaneo needs. Always 200 -- problems are reported in the body so the client can guide the user.",- middleware: manageAccess,+ middleware: [+ requireUserSession,+ scopeToProjectFromBody,+ requireWorkspacePermission({ workspace: ["manage_settings"] }),+ ],request: {body: {required: true,@@ -131,8 +144,9 @@ const createIntegrationRoute = createRoute({path: "/project/{projectId}",tags: ["GitHub"],summary: "Create GitHub integration",- description: "Link a project to a GitHub repository.",- middleware: manageAccess,+ description:+ "Link a project to a GitHub repository. Disconnect first to switch repositories; existing issue and pull request links cannot be reused for another repository.",+ middleware: [requireUserSession, ...manageAccess],request: {params: projectIdParam,body: {@@ -142,6 +156,9 @@ const createIntegrationRoute = createRoute({},responses: {200: jsonResponse("The stored integration", createdGithubIntegrationSchema),+ 409: errorResponse(+ "Integration changed or another repository is already linked",+ ),400: errorResponse("Invalid body, or unknown project"),403: errorResponse("No workspace access, or missing workspace:manage_settings",@@ -170,6 +187,9 @@ const updateIntegrationRoute = createRoute({"The updated integration",githubIntegrationSchema.nullable(),),+ 409: errorResponse(+ "Integration changed or another repository is already linked",+ ),400: errorResponse("The resulting config failed validation"),403: errorResponse("No workspace access, or missing workspace:manage_settings",@@ -206,7 +226,7 @@ const importIssuesRoute = createRoute({tags: ["GitHub"],summary: "Import GitHub issues",description:- "Import the linked repository's issues as tasks. Issues that already have a task are skipped.",+ "Import open issues and link open pull requests in bounded steps. Existing tasks are updated. Continue 202 responses with the returned runId until 200; the same runId safely retries completion. Progress is saved after each page. New calls without runId resume an unfinished import or start a new one after completion.",middleware: [scopeToProjectFromBody,requireWorkspacePermission({ task: ["create"] }),@@ -214,11 +234,22 @@ const importIssuesRoute = createRoute({request: {body: {required: true,- content: { "application/json": { schema: projectIdBody } },+ content: { "application/json": { schema: importGitHubBody } },},},responses: {- 200: jsonResponse("Import summary", importResultSchema),+ 200: jsonResponse("Completed import summary", importResultSchema),+ 202: jsonResponse(+ "Saved import progress; continue with runId",+ importResultSchema,+ ),+ 409: errorResponse(+ "Integration or import changed; refresh before resuming",+ ),+ 429: errorResponse("Import busy; retry after one second"),+ 502: errorResponse(+ "Provider unavailable or invalid page; progress is saved",+ ),400: errorResponse("projectId is required"),403: errorResponse("No workspace access, or missing task:create permission",@@ -229,20 +260,37 @@ const importIssuesRoute = createRoute({const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>().openapi(getAppInfoRoute, async (c) => {+ const account = await db.query.accountTable.findFirst({+ where: and(+ eq(accountTable.userId, c.get("userId")),+ eq(accountTable.providerId, "github"),+ ),+ columns: { id: true },+ });return c.json({appName: process.env.GITHUB_APP_NAME || null,+ accountConnected: Boolean(account),+ accountLinkingAvailable: isGithubSsoConfigured(),},200,);}).openapi(listRepositoriesRoute, async (c) => {- const repositories = await listUserRepositories();+ const repositories = await listUserRepositories(+ c.get("userId"),+ c.req.valid("query"),+ );return c.json(repositories, 200);}).openapi(verifyRoute, async (c) => {const { repositoryOwner, repositoryName } = c.req.valid("json");+ await verifyRepositoryOwner(+ c.get("userId"),+ repositoryOwner,+ repositoryName,+ );const verification = await verifyGithubInstallation({repositoryOwner,repositoryName,@@ -260,6 +308,7 @@ const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>()const { repositoryOwner, repositoryName } = c.req.valid("json");const integration = await createGithubIntegration({+ userId: c.get("userId"),projectId,repositoryOwner,repositoryName,@@ -303,7 +352,7 @@ const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>()});}- await db+ const [saved] = await db.update(integrationTable).set({config: JSON.stringify(config),@@ -313,10 +362,15 @@ const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>()}).where(and(- eq(integrationTable.projectId, projectId),- eq(integrationTable.type, "github"),+ eq(integrationTable.id, row.id),+ eq(integrationTable.config, row.config),),- );+ )+ .returning({ id: integrationTable.id });+ if (!saved)+ throw new HTTPException(409, {+ message: "GitHub integration changed; refresh before updating",+ });const updated = await getGithubIntegration(projectId);return c.json(updated, 200);@@ -327,9 +381,9 @@ const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>()return c.json(result, 200);}).openapi(importIssuesRoute, async (c) => {- const { projectId } = c.req.valid("json");- const result = await importIssues(projectId);- return c.json(result, 200);+ const { projectId, runId } = c.req.valid("json");+ const result = await importIssues(projectId, runId);+ return result.pending ? c.json(result, 202) : c.json(result, 200);});export async function handleGithubWebhookRoute(c: Context) {diff --git a/apps/api/src/github-integration/response.ts b/apps/api/src/github-integration/response.tsindex c3b022f66..842d0e7ae 100644--- a/apps/api/src/github-integration/response.ts+++ b/apps/api/src/github-integration/response.ts@@ -1,5 +1,18 @@import { responseTimestamp, z } from "../openapi";+export const importResultSchema = z+ .object({+ runId: z.string(),+ pending: z.boolean(),+ imported: z.number(),+ updated: z.number(),+ skipped: z.number().openapi({+ description:+ "Issues whose linked task or source disappeared or belongs to another project.",+ }),+ })+ .openapi("IssueImportResult");+export const githubIntegrationSchema = z.object({id: z.string(),@@ -10,6 +23,8 @@ export const githubIntegrationSchema = zdescription:"The GitHub App installation that grants access to the repository.",}),+ requiresVerification: z.boolean(),+ importProgress: importResultSchema.optional(),branchPattern: z.string().optional().openapi({description: "Template used to name branches created for a task.",}),@@ -25,6 +40,8 @@ export const githubIntegrationSchema = zexport const githubAppInfoSchema = z.object({+ accountConnected: z.boolean(),+ accountLinkingAvailable: z.boolean(),appName: z.string().nullable().openapi({description:"The configured GitHub App slug, or null when this instance has no App set up.",@@ -84,6 +101,9 @@ export const githubRepositoryListSchema = z}),installations: z.array(githubInstallationSchema),total: z.number(),+ nextPage: z+ .object({ installationPage: z.number(), repositoryPage: z.number() })+ .nullable(),}).openapi("GitHubRepositoryList");@@ -113,16 +133,6 @@ export const verificationResultSchema = z}).openapi("GitHubVerificationResult");-export const importResultSchema = z- .object({- imported: z.number(),- skipped: z.number().openapi({- description: "Issues that already had a task, or were not importable.",- }),- errors: z.array(z.string()).optional(),- })- .openapi("IssueImportResult");-export const createdGithubIntegrationSchema = githubIntegrationSchema.partial({id: true,diff --git a/apps/api/src/github-integration/schema.ts b/apps/api/src/github-integration/schema.tsindex c38ae7fc1..5b494720d 100644--- a/apps/api/src/github-integration/schema.ts+++ b/apps/api/src/github-integration/schema.ts@@ -1,8 +1,8 @@import { z } from "../openapi";const repositoryRef = {- repositoryOwner: z.string().min(1),- repositoryName: z.string().min(1),+ repositoryOwner: z.string().min(1).max(100),+ repositoryName: z.string().min(1).max(100),};export const verifyGitHubBody = z.object({@@ -16,3 +16,21 @@ export const updateGitHubBody = z.object({isActive: z.boolean().optional(),commentTaskLinkOnGitHubIssue: z.boolean().optional(),});++export const repositoryPageQuery = z.object({+ installationPage: z+ .string()+ .regex(/^[1-9][0-9]{0,5}$/)+ .default("1")+ .transform(Number),+ repositoryPage: z+ .string()+ .regex(/^[1-9][0-9]{0,5}$/)+ .default("1")+ .transform(Number),+});++export const importGitHubBody = z.object({+ projectId: z.string().min(1).max(128),+ runId: z.string().min(1).max(128).optional(),+});diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex a057d8672..49b8ead07 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -41,7 +41,7 @@ import { migrateColumns } from "./migrations/column-migration";import notification from "./notification";import notificationPreferences from "./notification-preferences";import oauth from "./oauth";-import { createRoute, jsonResponse, z } from "./openapi";+import { createRoute, errorResponse, jsonResponse, z } from "./openapi";import { initializePlugins } from "./plugins";import { migrateGitHubIntegration } from "./plugins/github/migration";import project from "./project";@@ -51,14 +51,24 @@ import search from "./search";import slackIntegration from "./slack-integration";import { getPrivateObject } from "./storage/s3";import task from "./task";+import {+ getDescriptionPage,+ getPublicProjectDescriptionPage,+} from "./task/description-pages";+import { boardSchema, descriptionPageSchema } from "./task/response";+import { descriptionPageQuery, listTasksQuery } from "./task/schema";import taskRelation from "./task-relation";import telegramIntegration from "./telegram-integration";import timeEntry from "./time-entry";import user from "./user";import getAvatar from "./user/controllers/get-avatar";import { authenticateApiRequest } from "./utils/authenticate-api-request";-import { authorizeAssetAccess } from "./utils/authorize-asset-access";+import {+ authorizeAssetAccess,+ isPublicAsset,+} from "./utils/authorize-asset-access";import { getInvitationDetails } from "./utils/check-registration-allowed";+import { clientIpMiddleware } from "./utils/client-ip";import { migrateApiKeyReferenceId } from "./utils/migrate-apikey-reference-id";import { migrateNotificationPreferencesSchema } from "./utils/migrate-notification-preferences-schema";import { migrateSessionColumn } from "./utils/migrate-session-column";@@ -76,6 +86,11 @@ import {removeUserConnection,shutdownWebSocketAdapter,} from "./ws";+import {+ assertWebSocketOrigin,+ handleWebSocketMessage,+ MAX_WEBSOCKET_MESSAGE_BYTES,+} from "./ws/security";type ApiKey = {id: string;@@ -140,6 +155,7 @@ function buildContentDisposition(filename: string, inline: boolean) {export function createApp() {const app = new Hono<AppVariables>();+ app.use("*", clientIpMiddleware());app.onError((err, c) => {if (err instanceof HTTPException) {@@ -154,6 +170,11 @@ export function createApp() {return c.json({ message: "Internal Server Error" }, 500);});const nodeWs = createNodeWebSocket({ app });+ // node-ws exposes its ws server, but does not accept constructor options.+ // Set the receiver limit before any connection can upgrade, including+ // fragmented messages, before node-ws converts text buffers to strings.+ nodeWs.wss.options.maxPayload = MAX_WEBSOCKET_MESSAGE_BYTES;+ nodeWs.wss.options.perMessageDeflate = false;const { upgradeWebSocket, injectWebSocket } = nodeWs;const corsOriginSource = [process.env.CORS_ORIGINS,@@ -225,12 +246,124 @@ export function createApp() {async (c) => c.json(await getInstanceStatus(), 200),);- const publicProjectApi = api.get("/public-project/:id", async (c) => {- const { id } = c.req.param();- const project = await getPublicProject(id);-- return c.json(project);- });+ const publicProjectApi = api+ .openapi(+ createRoute({+ method: "get",+ operationId: "getPublicProject",+ path: "/public-project/{id}",+ tags: ["Projects"],+ summary: "Get a public project board",+ description:+ "Read a public board in bounded task pages. Visibility is checked before loading tasks. Continue through pagination.totalPages for all tasks and through relatedPage/pagination.relatedTotalPages for their complete related records.",+ security: [],+ request: {+ params: z.object({ id: z.string() }),+ query: listTasksQuery,+ },+ responses: {+ 200: jsonResponse(+ "A public board page",+ boardSchema.shape.data+ .extend({ pagination: boardSchema.shape.pagination })+ .openapi("PublicBoardPage"),+ ),+ 403: errorResponse("Project is not public"),+ 404: errorResponse("Project not found"),+ 400: errorResponse("Invalid pagination or filters"),+ 503: errorResponse("Task list request timed out"),+ },+ }),+ async (c) => {+ const { id } = c.req.valid("param");+ const project = await getPublicProject(id, c.req.valid("query"));+ return c.json(project, 200);+ },+ (result) => {+ if (!result.success)+ throw new HTTPException(400, {+ message: "Invalid task pagination or filters",+ });+ },+ )+ .openapi(+ createRoute({+ method: "get",+ operationId: "getPublicProjectDescriptionPage",+ path: "/public-project/{id}/description",+ tags: ["Projects"],+ summary: "Read a public project description page",+ security: [],+ request: {+ params: z.object({ id: z.string() }),+ query: descriptionPageQuery,+ },+ responses: {+ 200: jsonResponse(+ "Public project description page",+ descriptionPageSchema,+ ),+ 400: errorResponse("Invalid description cursor"),+ 404: errorResponse("Public project not found"),+ 409: errorResponse("Description changed or no longer public"),+ 503: errorResponse("Description request timed out"),+ },+ }),+ async (c) =>+ c.json(+ await getPublicProjectDescriptionPage(+ c.req.valid("param").id,+ c.req.valid("query"),+ ),+ 200,+ ),+ (result) => {+ if (!result.success)+ throw new HTTPException(400, {+ message: "Invalid description cursor",+ });+ },+ )+ .openapi(+ createRoute({+ method: "get",+ operationId: "getPublicTaskDescriptionPage",+ path: "/public-project/{id}/task/{taskId}/description",+ tags: ["Projects"],+ summary: "Read a public task description page",+ security: [],+ request: {+ params: z.object({ id: z.string(), taskId: z.string() }),+ query: descriptionPageQuery,+ },+ responses: {+ 200: jsonResponse(+ "Public task description page",+ descriptionPageSchema,+ ),+ 400: errorResponse("Invalid description cursor"),+ 404: errorResponse("Public task not found"),+ 409: errorResponse("Description changed or no longer public"),+ 503: errorResponse("Description request timed out"),+ },+ }),+ async (c) => {+ const { id, taskId } = c.req.valid("param");+ return c.json(+ await getDescriptionPage(taskId, {+ ...c.req.valid("query"),+ publicProjectId: id,+ }),+ 200,+ );+ },+ (result) => {+ if (!result.success)+ throw new HTTPException(400, {+ message: "Invalid description cursor",+ });+ },+ );api.post("/github-integration/webhook", handleGithubWebhookRoute);@@ -293,6 +426,7 @@ export function createApp() {objectKey: schema.assetTable.objectKey,mimeType: schema.assetTable.mimeType,filename: schema.assetTable.filename,+ surface: schema.assetTable.surface,workspaceId: schema.assetTable.workspaceId,isPublic: schema.projectTable.isPublic,})@@ -321,7 +455,7 @@ export function createApp() {return new Response(object.body as BodyInit, {headers: {- "Cache-Control": asset.isPublic+ "Cache-Control": isPublicAsset(asset)? "public, max-age=300": "private, max-age=120","Content-Disposition": buildContentDisposition(@@ -632,6 +766,7 @@ export function createApp() {api.get("/ws/user",upgradeWebSocket(async (c) => {+ assertWebSocketOrigin(c.req.raw.headers);try {await authenticateApiRequest(c);} catch (error) {@@ -651,24 +786,7 @@ export function createApp() {conn = addUserConnection(userId, ws);}},- onMessage(evt) {- try {- const raw =- typeof evt.data === "string"- ? evt.data- : Buffer.isBuffer(evt.data)- ? evt.data.toString()- : null;- if (raw) {- const msg = JSON.parse(raw) as { type?: string };- if (msg?.type === "ping") {- // keepalive, no-op- }- }- } catch {- // Ignore malformed messages- }- },+ onMessage: handleWebSocketMessage,onClose() {if (conn && userId) {removeUserConnection(userId, conn);@@ -681,6 +799,7 @@ export function createApp() {api.get("/ws/:projectId",upgradeWebSocket(async (c) => {+ assertWebSocketOrigin(c.req.raw.headers);const projectId = c.req.param("projectId");try {@@ -719,27 +838,7 @@ export function createApp() {conn = addConnection(projectId, ws, userId, initiatorId);}},- onMessage(evt) {- // Respond to client keepalive pings (sent every 30s to prevent- // Cloudflare from closing idle connections at 100s timeout)- try {- const raw =- typeof evt.data === "string"- ? evt.data- : Buffer.isBuffer(evt.data)- ? evt.data.toString()- : null;- if (raw) {- const msg = JSON.parse(raw) as { type?: string };- if (msg?.type === "ping") {- // No-op: receiving the ping is enough to satisfy Cloudflare.- // A pong response is optional but helps confirm liveness.- }- }- } catch {- // Ignore malformed messages- }- },+ onMessage: handleWebSocketMessage,onClose() {if (conn && projectId) {removeConnection(projectId, conn);diff --git a/apps/api/src/instance/controllers/get-instance-status.ts b/apps/api/src/instance/controllers/get-instance-status.tsindex 79e44640a..8af1ad21b 100644--- a/apps/api/src/instance/controllers/get-instance-status.ts+++ b/apps/api/src/instance/controllers/get-instance-status.ts@@ -1,5 +1,6 @@import { count, eq } from "drizzle-orm";import db, { schema } from "../../database";+import { hasRegisteredUsers } from "../../utils/instance-bootstrap";export type InstanceStatus = {hasUsers: boolean;@@ -7,14 +8,14 @@ export type InstanceStatus = {};async function getInstanceStatus(): Promise<InstanceStatus> {- const [totalRow] = await db.select({ value: count() }).from(schema.userTable);+ const hasUsers = await hasRegisteredUsers();const [adminRow] = await db.select({ value: count() }).from(schema.userTable).where(eq(schema.userTable.role, "admin"));return {- hasUsers: (totalRow?.value ?? 0) > 0,+ hasUsers,hasAdmin: (adminRow?.value ?? 0) > 0,};}diff --git a/apps/api/src/instrument.ts b/apps/api/src/instrument.tsindex 034e00d61..e92d848aa 100644--- a/apps/api/src/instrument.ts+++ b/apps/api/src/instrument.ts@@ -1,6 +1,7 @@import { readFileSync } from "node:fs";import * as Sentry from "@sentry/node";import { nodeProfilingIntegration } from "@sentry/profiling-node";+import { isSensitiveOutboundRequest } from "./utils/sensitive-outbound";function parseSampleRate(value: string | undefined) {const n = Number(value);@@ -33,6 +34,14 @@ if (process.env.SENTRY_DSN) {sendDefaultPii: false,tracesSampleRate,profilesSampleRate,- integrations: [nodeProfilingIntegration()],+ integrations: [+ nodeProfilingIntegration(),+ Sentry.httpIntegration({+ ignoreOutgoingRequests: isSensitiveOutboundRequest,+ }),+ Sentry.nativeNodeFetchIntegration({+ ignoreOutgoingRequests: isSensitiveOutboundRequest,+ }),+ ],});}diff --git a/apps/api/src/label/controllers/assign-label-to-task.ts b/apps/api/src/label/controllers/assign-label-to-task.tsindex 6e7adaa05..469a393fc 100644--- a/apps/api/src/label/controllers/assign-label-to-task.ts+++ b/apps/api/src/label/controllers/assign-label-to-task.ts@@ -30,6 +30,9 @@ async function assignLabelToTask(id: string, taskId: string, userId: string) {});}+ if (label.deletionStartedAt)+ throw new HTTPException(409, { message: "This label is being deleted" });+const [task] = await db.select({id: taskTable.id,@@ -75,6 +78,11 @@ async function assignLabelToTask(id: string, taskId: string, userId: string) {});}+ if (currentLabel.deletionStartedAt)+ throw new HTTPException(409, {+ message: "This label is being deleted",+ });+if (currentLabel.workspaceId &¤tLabel.workspaceId !== task.workspaceIddiff --git a/apps/api/src/label/controllers/create-label.ts b/apps/api/src/label/controllers/create-label.tsindex 33dcce2e6..89334cad7 100644--- a/apps/api/src/label/controllers/create-label.ts+++ b/apps/api/src/label/controllers/create-label.ts@@ -13,6 +13,16 @@ async function createLabel(workspaceId: string,userId: string,) {+ const deleting = await db.query.labelTable.findFirst({+ where: and(+ eq(labelTable.workspaceId, workspaceId),+ eq(labelTable.name, name),+ isNull(labelTable.taskId),+ ),+ });+ if (deleting?.deletionStartedAt)+ throw new HTTPException(409, { message: "This label is being deleted" });+if (taskId) {const [task] = await db.select({diff --git a/apps/api/src/label/controllers/delete-label.ts b/apps/api/src/label/controllers/delete-label.tsindex 3abd1cfde..4c9550260 100644--- a/apps/api/src/label/controllers/delete-label.ts+++ b/apps/api/src/label/controllers/delete-label.ts@@ -1,142 +1,130 @@-import { and, eq, isNotNull } from "drizzle-orm";+import { and, asc, eq, isNotNull, lte, sql } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { labelTable, projectTable, taskTable } from "../../database/schema";import { publishEvent } from "../../events";import { removeLabelFromGitea } from "../../plugins/gitea/utils/sync-label-to-gitea";import { removeLabelFromGitHub } from "../../plugins/github/utils/sync-label-to-github";+import { withLabelDeletionLock } from "../deletion-lock";-async function deleteLabel(id: string, userId: string) {- const label = await db.query.labelTable.findFirst({- where: (label, { eq }) => eq(label.id, id),- });-- if (!label) {- throw new HTTPException(404, {- message: "Label not found",- });- }-- if (label.taskId) {- // Task-level label: fetch task, delete with event + GitHub sync- const [task] = await db- .select({- id: taskTable.id,- projectId: taskTable.projectId,- workspaceId: projectTable.workspaceId,- })- .from(taskTable)- .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))- .where(eq(taskTable.id, label.taskId))- .limit(1);-- if (!task) {- throw new HTTPException(404, {- message: "Task not found",- });- }-- const [deletedLabel] = await db- .delete(labelTable)- .where(eq(labelTable.id, id))- .returning();-- if (!deletedLabel) {- throw new HTTPException(404, {- message: "Label not found",- });- }-- if (deletedLabel.taskId) {- removeLabelFromGitHub(deletedLabel.taskId, deletedLabel.name).catch(- (error) => {- console.error("Failed to remove label from GitHub:", error);- },- );- }-- await publishEvent("task.label_deleted", {- label: deletedLabel,- task,- projectId: task.projectId,- taskId: task.id,- userId,- type: "label_deleted",- });-- return deletedLabel;- }-- // Workspace-level label: delete the label and cascade to all task-level copies- const [deletedLabel] = await db- .delete(labelTable)- .where(eq(labelTable.id, id))- .returning();-- if (!deletedLabel) {- throw new HTTPException(404, {- message: "Label not found",- });- }+export const LABEL_DELETE_BATCH_SIZE = 25;+type Label = typeof labelTable.$inferSelect;- // Label without a workspace: the cascade filter below could never match- if (label.workspaceId === null) {- return deletedLabel;- }-- // Capture affected task-level labels before cascading so we have data- // for events and provider sync- const affectedLabels = await db+async function notifyDeletion(label: Label, userId: string) {+ if (!label.taskId) return;+ const [task] = await db.select({- label: labelTable,- taskId: taskTable.id,- projectId: projectTable.id,+ id: taskTable.id,+ projectId: taskTable.projectId,workspaceId: projectTable.workspaceId,})- .from(labelTable)- .innerJoin(taskTable, eq(labelTable.taskId, taskTable.id))+ .from(taskTable).innerJoin(projectTable, eq(taskTable.projectId, projectTable.id)).where(and(- eq(labelTable.workspaceId, label.workspaceId),- eq(labelTable.name, label.name),- isNotNull(labelTable.taskId),- ),- );-- // Cascade: delete all task-level copies of this label so existing tasks lose it- await db- .delete(labelTable)- .where(- and(- eq(labelTable.workspaceId, label.workspaceId),- eq(labelTable.name, label.name),- isNotNull(labelTable.taskId),+ eq(taskTable.id, label.taskId),+ eq(projectTable.workspaceId, label.workspaceId ?? ""),),- );-- // Emit events and sync providers for each affected task- for (const { label: l, taskId, projectId } of affectedLabels) {- if (l.taskId) {- removeLabelFromGitHub(l.taskId, l.name).catch((error) => {- console.error("Failed to remove label from GitHub:", error);- });- removeLabelFromGitea(l.taskId, l.name).catch((error) => {- console.error("Failed to remove label from Gitea:", error);- });+ )+ .limit(1);+ // Legacy inconsistent rows may be cleaned up, but never emit foreign events.+ if (!task) return;+ for (const remove of [removeLabelFromGitHub, removeLabelFromGitea]) {+ try {+ await remove(task.id, label.name);+ } catch {+ console.error(+ "Failed to synchronize a label removal with an external provider",+ );}-- await publishEvent("task.label_deleted", {- label: l,- task: { id: taskId, projectId },- projectId,- taskId,+ }+ await publishEvent(+ "task.label_deleted",+ {+ label,+ task,+ projectId: task.projectId,+ taskId: task.id,userId,type: "label_deleted",+ },+ { waitForHandlers: true },+ );+}++async function deleteLabel(+ id: string,+ userId: string,+): Promise<Label & { pendingDeletion?: true }> {+ return withLabelDeletionLock(id, async () => {+ const label = await db.query.labelTable.findFirst({+ where: eq(labelTable.id, id),});- }+ if (!label) throw new HTTPException(404, { message: "Label not found" });++ if (label.taskId) {+ const [task] = await db+ .select({ workspaceId: projectTable.workspaceId })+ .from(taskTable)+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(eq(taskTable.id, label.taskId))+ .limit(1);+ if (!task || task.workspaceId !== label.workspaceId)+ throw new HTTPException(404, { message: "Task not found" });+ const [deleted] = await db+ .delete(labelTable)+ .where(eq(labelTable.id, id))+ .returning();+ if (!deleted)+ throw new HTTPException(404, { message: "Label not found" });+ await notifyDeletion(deleted, userId);+ return deleted;+ }- return deletedLabel;+ // Persist the snapshot boundary before the first batch. A disconnect or+ // restart leaves this root available for the same DELETE request to resume.+ const [root] = await db+ .update(labelTable)+ .set({+ deletionStartedAt: sql`coalesce(${labelTable.deletionStartedAt}, clock_timestamp())`,+ })+ .where(eq(labelTable.id, id))+ .returning();+ if (!root) throw new HTTPException(404, { message: "Label not found" });+ if (root.workspaceId) {+ const predicate = and(+ eq(labelTable.workspaceId, root.workspaceId),+ eq(labelTable.name, root.name),+ isNotNull(labelTable.taskId),+ lte(+ labelTable.createdAt,+ sql`(select deletion_started_at from label where id = ${id})`,+ ),+ );+ const rows = await db+ .select({ id: labelTable.id })+ .from(labelTable)+ .where(predicate)+ .orderBy(asc(labelTable.createdAt), asc(labelTable.id))+ .limit(LABEL_DELETE_BATCH_SIZE + 1);+ for (const row of rows.slice(0, LABEL_DELETE_BATCH_SIZE)) {+ // Recheck the snapshot/name if a concurrent edit changed this copy.+ const [deleted] = await db+ .delete(labelTable)+ .where(and(eq(labelTable.id, row.id), predicate))+ .returning();+ if (deleted) await notifyDeletion(deleted, userId);+ }+ if (rows.length > LABEL_DELETE_BATCH_SIZE)+ return { ...root, pendingDeletion: true };+ }+ const [deleted] = await db+ .delete(labelTable)+ .where(eq(labelTable.id, id))+ .returning();+ if (!deleted) throw new HTTPException(404, { message: "Label not found" });+ return deleted;+ });}export default deleteLabel;diff --git a/apps/api/src/label/controllers/unassign-label-from-task.ts b/apps/api/src/label/controllers/unassign-label-from-task.tsindex 85475ae11..68b335e2d 100644--- a/apps/api/src/label/controllers/unassign-label-from-task.ts+++ b/apps/api/src/label/controllers/unassign-label-from-task.ts@@ -33,7 +33,7 @@ async function unassignLabelFromTask(id: string, userId: string) {.where(eq(taskTable.id, label.taskId)).limit(1);- if (!task) {+ if (!task || task.workspaceId !== label.workspaceId) {throw new HTTPException(404, {message: "Task not found",});diff --git a/apps/api/src/label/controllers/update-label.ts b/apps/api/src/label/controllers/update-label.tsindex 789d01a57..cd465ec33 100644--- a/apps/api/src/label/controllers/update-label.ts+++ b/apps/api/src/label/controllers/update-label.ts@@ -1,4 +1,4 @@-import { and, eq, isNotNull } from "drizzle-orm";+import { and, eq, isNotNull, isNull } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { labelTable } from "../../database/schema";@@ -15,12 +15,20 @@ async function updateLabel(id: string, name: string, color: string) {});}+ if (label.deletionStartedAt)+ throw new HTTPException(409, {+ message: "This label is being deleted; resume its deletion instead",+ });+const [updatedLabel] = await tx.update(labelTable).set({ name, color })- .where(eq(labelTable.id, id))+ .where(and(eq(labelTable.id, id), isNull(labelTable.deletionStartedAt))).returning();+ if (!updatedLabel)+ throw new HTTPException(409, { message: "This label is being deleted" });+// If this is a workspace-level label, cascade the changes to all// task-level copies so existing label assignments reflect the new color/nameif (!label.taskId && label.workspaceId) {diff --git a/apps/api/src/label/deletion-lock.ts b/apps/api/src/label/deletion-lock.tsnew file mode 100644index 000000000..48634e7b6--- /dev/null+++ b/apps/api/src/label/deletion-lock.ts@@ -0,0 +1,77 @@+import { HTTPException } from "hono/http-exception";+import type { PoolClient } from "pg";+import { getDatabasePool } from "../database";++export const MAX_LABEL_DELETIONS_IN_FLIGHT = 4;+const LOCK_NAMESPACE = 773622;+let active = 0;++function busy() {+ return new HTTPException(429, {+ res: new Response("Label deletion is busy; retry this request", {+ status: 429,+ headers: { "Retry-After": "1" },+ }),+ });+}++/** Session locks span awaited provider calls without holding a SQL transaction. */+export async function withLabelDeletionLock<T>(+ id: string,+ run: () => Promise<T>,+): Promise<T> {+ if (active >= MAX_LABEL_DELETIONS_IN_FLIGHT) throw busy();+ active++;+ let client: PoolClient | undefined;+ let slot: number | undefined;+ let labelLocked = false;+ let releaseError: Error | undefined;+ try {+ client = await getDatabasePool().connect();+ for (+ let candidate = 0;+ candidate < MAX_LABEL_DELETIONS_IN_FLIGHT;+ candidate+++ ) {+ const { rows } = await client.query(+ "SELECT pg_try_advisory_lock($1::int, $2::int) AS acquired",+ [LOCK_NAMESPACE, candidate],+ );+ if (rows[0]?.acquired) {+ slot = candidate;+ break;+ }+ }+ if (slot === undefined) throw busy();+ const { rows } = await client.query(+ "SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS acquired",+ [`label-delete:${id}`],+ );+ labelLocked = rows[0]?.acquired === true;+ if (!labelLocked) throw busy();+ return await run();+ } finally {+ if (client) {+ try {+ if (labelLocked)+ await client.query(+ "SELECT pg_advisory_unlock(hashtextextended($1, 0))",+ [`label-delete:${id}`],+ );+ if (slot !== undefined)+ await client.query("SELECT pg_advisory_unlock($1::int, $2::int)", [+ LOCK_NAMESPACE,+ slot,+ ]);+ } catch (error) {+ // Destroy a connection whose lock release was not confirmed.+ releaseError =+ error instanceof Error+ ? error+ : new Error("Label lock release failed");+ }+ client.release(releaseError);+ }+ active--;+ }+}diff --git a/apps/api/src/label/index.ts b/apps/api/src/label/index.tsindex f3dfc5a4a..5db6b629b 100644--- a/apps/api/src/label/index.ts+++ b/apps/api/src/label/index.ts@@ -14,7 +14,11 @@ import getLabelsByTaskId from "./controllers/get-labels-by-task-id";import getLabelsByWorkspaceId from "./controllers/get-labels-by-workspace-id";import unassignLabelFromTask from "./controllers/unassign-label-from-task";import updateLabel from "./controllers/update-label";-import { labelListSchema, labelSchema } from "./response";+import {+ labelListSchema,+ labelSchema,+ pendingLabelDeletionSchema,+} from "./response";import {attachLabelBody,createLabelBody,@@ -82,6 +86,7 @@ const createLabelRoute = createRoute({"No workspace access, or missing label:create permission",),404: errorResponse("Task not found"),+ 409: errorResponse("The workspace label is being deleted"),},});@@ -130,6 +135,7 @@ const attachLabelToTaskRoute = createRoute({"No workspace access, or missing label:update permission",),404: errorResponse("Task not found"),+ 409: errorResponse("The workspace label is being deleted"),},});@@ -175,6 +181,7 @@ const updateLabelRoute = createRoute({},responses: {200: jsonResponse("Label updated successfully", labelSchema),+ 409: errorResponse("The workspace label is being deleted"),400: errorResponse("Invalid body, or unknown label"),403: errorResponse("No workspace access, or missing label:update permission",@@ -188,7 +195,8 @@ const deleteLabelRoute = createRoute({path: "/{id}",tags: ["Labels"],summary: "Delete label",- description: "Delete a label by ID",+ description:+ "Delete a label by ID. Large workspace cascades remove at most 25 task copies per request. Repeat DELETE with the same ID after HTTP 202 until HTTP 200 completes the operation. The persisted start boundary allows safe resumption after a disconnect. HTTP 429 asks the caller to retry later.",middleware: [workspaceAccess.fromLabel(),requireWorkspacePermission({ label: ["delete"] }),@@ -196,6 +204,11 @@ const deleteLabelRoute = createRoute({request: { params: labelParam },responses: {200: jsonResponse("Label deleted successfully", labelSchema),+ 202: jsonResponse(+ "Deletion has more batches; repeat the same request",+ pendingLabelDeletionSchema,+ ),+ 429: errorResponse("Deletion capacity is busy; retry after Retry-After"),400: errorResponse("Unknown label, or its workspace could not be determined",),@@ -246,7 +259,10 @@ const label = apiRouter().openapi(deleteLabelRoute, async (c) => {const { id } = c.req.valid("param");const userId = c.get("userId");- return c.json(await deleteLabel(id, userId), 200);+ const result = await deleteLabel(id, userId);+ if (result.pendingDeletion)+ return c.json({ ...result, pendingDeletion: true as const }, 202);+ return c.json(result, 200);});export default label;diff --git a/apps/api/src/label/response.ts b/apps/api/src/label/response.tsindex f8c87f1d3..ad85f865a 100644--- a/apps/api/src/label/response.ts+++ b/apps/api/src/label/response.ts@@ -7,9 +7,14 @@ export const labelSchema = zcolor: z.string(),createdAt: responseTimestamp,updatedAt: responseTimestamp,+ deletionStartedAt: responseTimestamp.nullable().optional(),taskId: z.string().nullable(),workspaceId: z.string().nullable(),}).openapi("Label");export const labelListSchema = z.array(labelSchema);++export const pendingLabelDeletionSchema = labelSchema+ .extend({ pendingDeletion: z.literal(true) })+ .openapi("PendingLabelDeletion");diff --git a/apps/api/src/mcp/controllers/oauth-consent.ts b/apps/api/src/mcp/controllers/oauth-consent.tsindex c5f75fd72..3763f7396 100644--- a/apps/api/src/mcp/controllers/oauth-consent.ts+++ b/apps/api/src/mcp/controllers/oauth-consent.ts@@ -117,7 +117,7 @@ export async function decideMcpAuthorizationRequest(params: {const session = await auth.api.getSession({ headers: params.headers });if (!session?.user?.id) throwOAuthError(401, "unauthorized");- const request = await consumeAuthorizationRequest(params.requestId);+ const request = await getAuthorizationRequest(params.requestId);if (!request) throwOAuthError(404, "invalid_or_expired_request");const client = await getClient(request.clientId);@@ -126,15 +126,20 @@ export async function decideMcpAuthorizationRequest(params: {}if (!params.decision.approved) {+ if (!(await consumeAuthorizationRequest(params.requestId)))+ throwOAuthError(404, "invalid_or_expired_request");return buildAuthorizationRedirect(request, { error: "access_denied" });}- const code = await createAuthCode({- clientId: request.clientId,- userId: session.user.id,- codeChallenge: request.codeChallenge,- redirectUri: request.redirectUri,- });+ const code = await createAuthCode(+ {+ clientId: request.clientId,+ userId: session.user.id,+ codeChallenge: request.codeChallenge,+ redirectUri: request.redirectUri,+ },+ params.requestId,+ );await publishEvent("mcp.authorization_code_issued", {clientId: request.clientId,userId: session.user.id,diff --git a/apps/api/src/mcp/index.ts b/apps/api/src/mcp/index.tsindex 359384051..c59beb820 100644--- a/apps/api/src/mcp/index.ts+++ b/apps/api/src/mcp/index.ts@@ -17,6 +17,7 @@ import {} from "./controllers/oauth-consent";import { createModernMcpHandler } from "./modern";import { exchangeCode } from "./oauth";+import { oauthRequestBounds } from "./request-bounds";import {authorizationDecisionResponseSchema,authorizationDecisionSchema,@@ -72,6 +73,14 @@ async function validateBearerToken(}const mcp = apiRouter();+for (const path of [+ "/mcp/register",+ "/mcp/authorize",+ "/mcp/authorize/request/*",+ "/mcp/token",+]) {+ mcp.use(path, oauthRequestBounds);+}const jsonError = (description: string) =>jsonResponse(description, oauthErrorSchema);@@ -289,13 +298,19 @@ mcp.all("/mcp", async (c) => {mcp.post("/mcp/token", async (c) => {const contentType = c.req.header("content-type") || "";- let params: Record<string, string>;-- if (contentType.includes("application/x-www-form-urlencoded")) {- const body = await c.req.text();- params = Object.fromEntries(new URLSearchParams(body));- } else {- params = await c.req.json();+ let params: Record<string, unknown>;++ try {+ if (contentType.includes("application/x-www-form-urlencoded")) {+ params = Object.fromEntries(new URLSearchParams(await c.req.text()));+ } else {+ const input: unknown = await c.req.json();+ if (!input || typeof input !== "object" || Array.isArray(input))+ return c.json({ error: "invalid_request" }, 400);+ params = input as Record<string, unknown>;+ }+ } catch {+ return c.json({ error: "invalid_request" }, 400);}const { grant_type, code, client_id, code_verifier, redirect_uri } = params;@@ -303,7 +318,20 @@ mcp.post("/mcp/token", async (c) => {if (grant_type !== "authorization_code") {return c.json({ error: "unsupported_grant_type" }, 400);}- if (!code || !client_id || !code_verifier || !redirect_uri) {+ if (+ typeof code !== "string" ||+ !code ||+ code.length > 128 ||+ typeof client_id !== "string" ||+ !client_id ||+ client_id.length > 128 ||+ typeof code_verifier !== "string" ||+ !code_verifier ||+ code_verifier.length > 128 ||+ typeof redirect_uri !== "string" ||+ !redirect_uri ||+ redirect_uri.length > 2048+ ) {return c.json({ error: "invalid_request" }, 400);}diff --git a/apps/api/src/mcp/oauth-store.ts b/apps/api/src/mcp/oauth-store.tsindex 46b2a1435..2be165b6d 100644--- a/apps/api/src/mcp/oauth-store.ts+++ b/apps/api/src/mcp/oauth-store.ts@@ -1,16 +1,162 @@-import { and, count, desc, eq, lt, notInArray } from "drizzle-orm";+import { and, count, eq, gt, sql } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";import db from "../database";import { mcpOauthStateTable } from "../database/schema";export type OauthStateKind = "client" | "code" | "request";+export const OAUTH_STATE_LIMITS = {+ client: { rows: 1_000, perMinute: 60, perClient: 0, lock: 1 },+ request: { rows: 10_000, perMinute: 300, perClient: 20, lock: 2 },+ code: { rows: 10_000, perMinute: 300, perClient: 20, lock: 3 },+} as const;+export const OAUTH_PAYLOAD_BYTES = 32 * 1024;+export const EXPIRED_STATE_BATCH = 100;+type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++async function sweepExpired(dbOrTx: typeof db | Transaction) {+ // Never issue an unbounded delete or evict a live consent request. Fixed+ // rate-counter rows are reused rather than accumulated per time window.+ await dbOrTx.execute(sql`+ DELETE FROM ${mcpOauthStateTable} WHERE id IN (+ SELECT id FROM ${mcpOauthStateTable}+ WHERE kind <> 'rate' AND expires_at <= now()+ ORDER BY expires_at LIMIT ${EXPIRED_STATE_BATCH}+ FOR UPDATE SKIP LOCKED+ )+ `);+}export async function putState(kind: OauthStateKind,key: string,payload: unknown,expiresAt: Date,+ consumeRequestId?: string,): Promise<void> {- await db.insert(mcpOauthStateTable).values({ kind, key, payload, expiresAt });+ const serialized = JSON.stringify(payload);+ if (+ typeof serialized !== "string" ||+ Buffer.byteLength(serialized) > OAUTH_PAYLOAD_BYTES ||+ key.length > 128+ ) {+ throw new HTTPException(413, { message: "OAuth state is too large" });+ }+ const clientId =+ payload && typeof payload === "object" && "clientId" in payload+ ? payload.clientId+ : undefined;+ const limits = OAUTH_STATE_LIMITS[kind];+ const denial = await db.transaction(async (tx) => {+ // Separate fixed locks keep a registration flood from occupying the code+ // issuance lock. Try-lock bounds the queue during concurrent floods.+ const lock = await tx.execute<{ acquired: boolean; nowMs: number }>(+ sql`SELECT pg_try_advisory_xact_lock(773621, ${limits.lock}) AS acquired, (extract(epoch FROM now()) * 1000)::double precision AS "nowMs"`,+ );+ if (!lock.rows[0]?.acquired) return "busy";+ const now = new Date(Number(lock.rows[0].nowMs));+ await sweepExpired(tx);+ const [rate] = await tx+ .select()+ .from(mcpOauthStateTable)+ .where(+ and(+ eq(mcpOauthStateTable.kind, "rate"),+ eq(mcpOauthStateTable.key, kind),+ ),+ )+ .limit(1);+ const used =+ rate && rate.expiresAt > now+ ? Number((rate.payload as { count?: number }).count ?? 0)+ : 0;+ if (!Number.isSafeInteger(used) || used < 0 || used >= limits.perMinute)+ return "rate";+ const [total] = await tx+ .select({ total: count() })+ .from(+ tx+ .select({ id: mcpOauthStateTable.id })+ .from(mcpOauthStateTable)+ .where(eq(mcpOauthStateTable.kind, kind))+ .limit(limits.rows)+ .as("bounded_states"),+ );+ if ((total?.total ?? limits.rows) >= limits.rows) return "capacity";+ if (limits.perClient && typeof clientId === "string") {+ const [clientTotal] = await tx.select({ total: count() }).from(+ tx+ .select({ id: mcpOauthStateTable.id })+ .from(mcpOauthStateTable)+ .where(+ and(+ eq(mcpOauthStateTable.kind, kind),+ sql`${mcpOauthStateTable.payload}->>'clientId' = ${clientId}`,+ ),+ )+ .limit(limits.perClient)+ .as("bounded_client_states"),+ );+ if ((clientTotal?.total ?? limits.perClient) >= limits.perClient)+ return "client";+ }+ if (consumeRequestId) {+ const consumed = await tx+ .delete(mcpOauthStateTable)+ .where(+ and(+ eq(mcpOauthStateTable.kind, "request"),+ eq(mcpOauthStateTable.key, consumeRequestId),+ gt(mcpOauthStateTable.expiresAt, now),+ ),+ )+ .returning({ id: mcpOauthStateTable.id });+ if (!consumed.length) return "missing-request";+ }+ await tx+ .insert(mcpOauthStateTable)+ .values({ kind, key, payload, expiresAt });+ const rateExpires = new Date(+ (Math.floor(now.getTime() / 60_000) + 1) * 60_000,+ );+ await tx+ .insert(mcpOauthStateTable)+ .values({+ kind: "rate",+ key: kind,+ payload: { count: used + 1 },+ expiresAt: rateExpires,+ })+ .onConflictDoUpdate({+ target: [mcpOauthStateTable.kind, mcpOauthStateTable.key],+ set: { payload: { count: used + 1 }, expiresAt: rateExpires },+ });+ return null;+ });+ // Return denials outside the transaction: expired-row cleanup must commit+ // even when a legacy over-cap table refuses this insert.+ if (denial === "missing-request")+ throw new HTTPException(404, {+ res: Response.json(+ { error: "invalid_or_expired_request" },+ { status: 404 },+ ),+ });+ if (denial)+ throw new HTTPException(429, {+ res: Response.json(+ {+ error: "temporarily_unavailable",+ error_description: "OAuth capacity reached; retry later",+ },+ {+ status: 429,+ headers: {+ "Retry-After": denial === "busy" ? "1" : "60",+ "Cache-Control": "no-store",+ },+ },+ ),+ });}export async function getState<T>(@@ -26,7 +172,7 @@ export async function getState<T>(.limit(1);if (!row) return null;- if (row.expiresAt.getTime() < Date.now()) return null;+ if (row.expiresAt.getTime() <= Date.now()) return null;return row.payload as T;}@@ -43,41 +189,10 @@ export async function consumeState<T>(.returning();if (!row) return null;- if (row.expiresAt.getTime() < Date.now()) return null;+ if (row.expiresAt.getTime() <= Date.now()) return null;return row.payload as T;}export async function deleteExpiredStates(): Promise<void> {- await db- .delete(mcpOauthStateTable)- .where(lt(mcpOauthStateTable.expiresAt, new Date()));-}--// Evicts oldest-expiring rows so an insert after this call stays within maxRows.-export async function enforceStateCap(- kind: OauthStateKind,- maxRows: number,-): Promise<void> {- const [countRow] = await db- .select({ pending: count() })- .from(mcpOauthStateTable)- .where(eq(mcpOauthStateTable.kind, kind));-- if ((countRow?.pending ?? 0) < maxRows) return;-- const newest = db- .select({ key: mcpOauthStateTable.key })- .from(mcpOauthStateTable)- .where(eq(mcpOauthStateTable.kind, kind))- .orderBy(desc(mcpOauthStateTable.expiresAt))- .limit(maxRows - 1);-- await db- .delete(mcpOauthStateTable)- .where(- and(- eq(mcpOauthStateTable.kind, kind),- notInArray(mcpOauthStateTable.key, newest),- ),- );+ await sweepExpired(db);}diff --git a/apps/api/src/mcp/oauth.ts b/apps/api/src/mcp/oauth.tsindex 5d4b2491e..b5f36c4d5 100644--- a/apps/api/src/mcp/oauth.ts+++ b/apps/api/src/mcp/oauth.ts@@ -2,13 +2,7 @@ import { createHash, randomUUID } from "node:crypto";import { createId } from "@paralleldrive/cuid2";import db from "../database";import { sessionTable } from "../database/schema";-import {- consumeState,- deleteExpiredStates,- enforceStateCap,- getState,- putState,-} from "./oauth-store";+import { consumeState, getState, putState } from "./oauth-store";type RegisteredClient = {clientId: string;@@ -35,8 +29,6 @@ export type AuthorizationRequest = {const clientTtlMs = 30 * 24 * 60 * 60 * 1000;const codeTtlMs = 5 * 60 * 1000;const requestTtlMs = 10 * 60 * 1000;-// Same bound the in-memory store enforced; authorize is reachable without a session.-const maxAuthorizationRequests = 10_000;export async function getClient(clientId: string,@@ -64,17 +56,24 @@ export async function registerClient(params: {return client;}-export async function createAuthCode(params: AuthCode): Promise<string> {+export async function createAuthCode(+ params: AuthCode,+ requestId?: string,+): Promise<string> {const code = randomUUID();- await putState("code", code, params, new Date(Date.now() + codeTtlMs));+ await putState(+ "code",+ code,+ params,+ new Date(Date.now() + codeTtlMs),+ requestId,+ );return code;}export async function createAuthorizationRequest(params: AuthorizationRequest,): Promise<string> {- await deleteExpiredStates();- await enforceStateCap("request", maxAuthorizationRequests);const requestId = randomUUID();await putState("request",diff --git a/apps/api/src/mcp/request-bounds.ts b/apps/api/src/mcp/request-bounds.tsnew file mode 100644index 000000000..e9703fea3--- /dev/null+++ b/apps/api/src/mcp/request-bounds.ts@@ -0,0 +1,39 @@+import type { MiddlewareHandler } from "hono";+import { HTTPException } from "hono/http-exception";++import { boundedRequestBody } from "../utils/bounded-request-body";++export const OAUTH_BODY_BYTES = 32 * 1024;+export const OAUTH_URL_BYTES = 8 * 1024;+const checkBody = boundedRequestBody(OAUTH_BODY_BYTES);++const checkRequestBounds: MiddlewareHandler = async (c, next) => {+ if (Buffer.byteLength(c.req.url) > OAUTH_URL_BYTES) {+ throw new HTTPException(414, { message: "OAuth URL is too long" });+ }+ return checkBody(c, next);+};++export const OAUTH_MAX_IN_FLIGHT = 16;+const activeRequests = { registration: 0, authorization: 0, token: 0 };++export const oauthRequestBounds: MiddlewareHandler = async (c, next) => {+ const group = c.req.path.endsWith("/register")+ ? "registration"+ : c.req.path.endsWith("/token")+ ? "token"+ : "authorization";+ if (activeRequests[group] >= OAUTH_MAX_IN_FLIGHT) {+ void c.req.raw.body?.cancel().catch(() => {});+ return c.json({ error: "temporarily_unavailable" }, 429, {+ "Retry-After": "1",+ "Cache-Control": "no-store",+ });+ }+ activeRequests[group]++;+ try {+ return await checkRequestBounds(c, next);+ } finally {+ activeRequests[group]--;+ }+};diff --git a/apps/api/src/mcp/schemas.ts b/apps/api/src/mcp/schemas.tsindex 8257c9d9f..41a5020a2 100644--- a/apps/api/src/mcp/schemas.ts+++ b/apps/api/src/mcp/schemas.ts@@ -30,32 +30,36 @@ const redirectUriSchema = z// Clients such as Claude also ask for refresh_token. The server never issues// one, so the grant is accepted here and omitted from the registration response.export const clientRegistrationSchema = z.object({- redirect_uris: z.array(redirectUriSchema).min(1),+ redirect_uris: z.array(redirectUriSchema).min(1).max(10),client_name: z.string().max(100).optional(),token_endpoint_auth_method: z.literal("none").optional(),grant_types: z.array(z.enum(["authorization_code", "refresh_token"]))+ .max(2).refine((types) => types.includes("authorization_code"),"grant_types must include authorization_code",).optional(),- response_types: z.array(z.literal("code")).min(1).optional(),+ response_types: z.array(z.literal("code")).min(1).max(1).optional(),});export const authorizationQuerySchema = z.object({response_type: z.literal("code"),- client_id: z.string(),+ client_id: z.string().min(1).max(128),redirect_uri: redirectUriSchema,- code_challenge: z.string().min(1).openapi({- description: "PKCE challenge; only S256 is accepted.",- }),+ code_challenge: z+ .string()+ .regex(/^[A-Za-z0-9_-]{43}$/)+ .openapi({+ description: "PKCE challenge; only S256 is accepted.",+ }),code_challenge_method: z.literal("S256"),- state: z.string().optional(),+ state: z.string().max(1024).optional(),});export const authorizationRequestParamSchema = z.object({- requestId: z.string(),+ requestId: z.string().min(1).max(128),});export const authorizationDecisionSchema = z.object({diff --git a/apps/api/src/mcp/tools.ts b/apps/api/src/mcp/tools.tsindex 8f91fec97..6fd6889b5 100644--- a/apps/api/src/mcp/tools.ts+++ b/apps/api/src/mcp/tools.ts@@ -364,14 +364,16 @@ export function registerMcpTools(registerTool("list_tasks",{- description: "List tasks for a project (optionally filtered/sorted).",+ description:+ "List a bounded page of tasks for a project (50 by default, maximum 100). Use pagination.totalPages and page to retrieve the rest; filters and sorting apply before pagination. For every task page, also follow relatedPage through pagination.relatedTotalPages for complete labels, links and column metadata.",inputSchema: z.object({projectId: nonEmptyString,status: optionalNonEmptyString,priority: prioritySchema.optional(),assigneeId: optionalNonEmptyString,- page: z.number().int().positive().optional(),- limit: z.number().int().positive().optional(),+ page: z.number().int().min(1).max(1_000_000).optional(),+ relatedPage: z.number().int().min(1).max(1_000_000).optional(),+ limit: z.number().int().min(1).max(100).optional(),sortBy: z.enum(["createdAt",diff --git a/apps/api/src/notification-preferences/delivery.ts b/apps/api/src/notification-preferences/delivery.tsindex dff4d18cb..89f3d7502 100644--- a/apps/api/src/notification-preferences/delivery.ts+++ b/apps/api/src/notification-preferences/delivery.ts@@ -11,26 +11,13 @@ import {userTable,workspaceTable,} from "../database/schema";-import { assertPublicWebhookDestination } from "../plugins/generic-webhook/config";+import { canReceiveResourceNotification } from "../notification/resource-access";+import {+ safeOutboundError,+ sendOutboundRequest,+} from "../utils/outbound-request";import { decryptSecret } from "./secrets";-const DEFAULT_OUTBOUND_FETCH_TIMEOUT_MS = 15_000;--async function fetchWithTimeout(- url: string,- init: RequestInit & { timeoutMs?: number },-): Promise<Response> {- const timeoutMs = init.timeoutMs ?? DEFAULT_OUTBOUND_FETCH_TIMEOUT_MS;- const { timeoutMs: _timeout, ...rest } = init;- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), timeoutMs);- try {- return await fetch(url, { ...rest, signal: controller.signal });- } finally {- clearTimeout(timer);- }-}-type ResolvedNotificationContext = {workspaceId: string;workspaceName: string;@@ -282,12 +269,9 @@ async function sendNtfyNotification(input: {body: string;clickUrl?: string | null;}) {- await assertPublicWebhookDestination(input.serverUrl);-- const response = await fetchWithTimeout(+ await sendOutboundRequest(`${input.serverUrl.replace(/\/+$/, "")}/${encodeURIComponent(input.topic)}`,{- method: "POST",headers: {...(input.token ? { Authorization: `Bearer ${input.token}` } : {}),...(input.clickUrl ? { Click: input.clickUrl } : {}),@@ -295,13 +279,8 @@ async function sendNtfyNotification(input: {},body: input.body,},+ { publicDestination: true, timeoutMs: 15_000 },);-- if (!response.ok) {- throw new Error(- `ntfy delivery failed (${response.status}): ${await response.text()}`,- );- }}async function sendGotifyNotification(input: {@@ -311,15 +290,12 @@ async function sendGotifyNotification(input: {body: string;clickUrl?: string | null;}) {- await assertPublicWebhookDestination(input.serverUrl);-// Gotify expects the app token in the query string; that can surface in logs, proxies, and browser history, so factor this into Gotify placement and log handling.- const response = await fetchWithTimeout(+ await sendOutboundRequest(`${input.serverUrl.replace(/\/+$/, "")}/message?token=${encodeURIComponent(input.token,)}`,{- method: "POST",headers: {"Content-Type": "application/json",},@@ -341,13 +317,8 @@ async function sendGotifyNotification(input: {: undefined,}),},+ { publicDestination: true, timeoutMs: 15_000 },);-- if (!response.ok) {- throw new Error(- `Gotify delivery failed (${response.status}): ${await response.text()}`,- );- }}async function sendWebhookNotification(input: {@@ -355,8 +326,6 @@ async function sendWebhookNotification(input: {secret?: string | null;payload: Record<string, unknown>;}) {- await assertPublicWebhookDestination(input.webhookUrl);-const body = JSON.stringify(input.payload);const headers: Record<string, string> = {"Content-Type": "application/json",@@ -368,17 +337,11 @@ async function sendWebhookNotification(input: {.digest("hex");}- const response = await fetchWithTimeout(input.webhookUrl, {- method: "POST",- headers,- body,- });-- if (!response.ok) {- throw new Error(- `Webhook delivery failed (${response.status}): ${await response.text()}`,- );- }+ await sendOutboundRequest(+ input.webhookUrl,+ { headers, body },+ { publicDestination: true, timeoutMs: 15_000 },+ );}export async function deliverNotification(@@ -388,7 +351,14 @@ export async function deliverNotification(where: eq(notificationTable.id, notificationId),});- if (!notification) {+ if (+ !notification ||+ !(await canReceiveResourceNotification(+ notification.userId,+ notification.resourceId,+ notification.resourceType,+ ))+ ) {return;}@@ -571,7 +541,7 @@ export async function deliverNotification(if (result.status === "rejected") {console.error("Notification delivery failed", {notificationId,- error: result.reason,+ error: safeOutboundError(result.reason),});}}diff --git a/apps/api/src/notification/controllers/create-notification.ts b/apps/api/src/notification/controllers/create-notification.tsindex 91e25a19e..2ba7681a1 100644--- a/apps/api/src/notification/controllers/create-notification.ts+++ b/apps/api/src/notification/controllers/create-notification.ts@@ -4,6 +4,9 @@ import { notificationTable } from "../../database/schema";import { publishEvent } from "../../events";import { deliverNotification } from "../../notification-preferences/delivery";+import { safeOutboundError } from "../../utils/outbound-request";+import { canReceiveResourceNotification } from "../resource-access";+async function createNotification({userId,title,@@ -21,6 +24,12 @@ async function createNotification({resourceId?: string;resourceType?: string;}) {+ if (+ !(await canReceiveResourceNotification(userId, resourceId, resourceType))+ ) {+ return null;+ }+const preferenceKey =type === "task_assignee_changed" || type === "task_created"? "taskAssignmentEnabled"@@ -66,7 +75,7 @@ async function createNotification({void deliverNotification(notification.id).catch((error) => {console.error("Failed to deliver notification", {notificationId: notification.id,- error,+ error: safeOutboundError(error),});});}diff --git a/apps/api/src/notification/controllers/get-notifications.ts b/apps/api/src/notification/controllers/get-notifications.tsindex e79159d7a..98567317f 100644--- a/apps/api/src/notification/controllers/get-notifications.ts+++ b/apps/api/src/notification/controllers/get-notifications.ts@@ -7,6 +7,8 @@ import {workspaceTable,} from "../../database/schema";+import { notificationResourceAccess } from "../resource-access";+async function getNotifications(userId: string) {const rows = await db.select({@@ -24,7 +26,16 @@ async function getNotifications(userId: string) {).leftJoin(projectTable, eq(taskTable.projectId, projectTable.id)).leftJoin(workspaceTable, eq(projectTable.workspaceId, workspaceTable.id))- .where(eq(notificationTable.userId, userId))+ .where(+ and(+ eq(notificationTable.userId, userId),+ notificationResourceAccess(+ userId,+ notificationTable.resourceId,+ notificationTable.resourceType,+ ),+ ),+ ).orderBy(desc(notificationTable.createdAt)).limit(50);diff --git a/apps/api/src/notification/controllers/mark-notification-as-read.ts b/apps/api/src/notification/controllers/mark-notification-as-read.tsindex bb1c9c9b5..ec02d1cd1 100644--- a/apps/api/src/notification/controllers/mark-notification-as-read.ts+++ b/apps/api/src/notification/controllers/mark-notification-as-read.ts@@ -3,12 +3,22 @@ import { HTTPException } from "hono/http-exception";import db from "../../database";import { notificationTable } from "../../database/schema";+import { notificationResourceAccess } from "../resource-access";+async function markNotificationAsRead(id: string, userId: string) {const [notification] = await db.update(notificationTable).set({ isRead: true }).where(- and(eq(notificationTable.id, id), eq(notificationTable.userId, userId)),+ and(+ eq(notificationTable.id, id),+ eq(notificationTable.userId, userId),+ notificationResourceAccess(+ userId,+ notificationTable.resourceId,+ notificationTable.resourceType,+ ),+ ),).returning();diff --git a/apps/api/src/notification/resource-access.ts b/apps/api/src/notification/resource-access.tsnew file mode 100644index 000000000..482efaf02--- /dev/null+++ b/apps/api/src/notification/resource-access.ts@@ -0,0 +1,48 @@+import { and, eq, type SQLWrapper, sql } from "drizzle-orm";+import db from "../database";+import { userTable } from "../database/schema";++// Membership, rather than public visibility or global admin privileges, defines+// who may be subscribed to private task activity. Use the same predicate when+// creating, reading and delivering notifications, including historical rows.+export function notificationResourceAccess(+ userId: string,+ resourceId: string | null | SQLWrapper,+ resourceType: string | null | SQLWrapper,+) {+ return sql<boolean>`(+ (${resourceId}::text IS NULL AND ${resourceType}::text IS NULL)+ OR (${resourceType}::text = 'task' AND EXISTS (+ SELECT 1 FROM task AS notification_task+ JOIN project AS notification_project ON notification_project.id = notification_task.project_id+ JOIN workspace_member AS notification_member ON notification_member.workspace_id = notification_project.workspace_id+ WHERE notification_task.id = ${resourceId} AND notification_member.user_id = ${userId}+ ))+ OR (${resourceType}::text = 'workspace' AND EXISTS (+ SELECT 1 FROM workspace_member AS notification_member+ WHERE notification_member.workspace_id = ${resourceId} AND notification_member.user_id = ${userId}+ ))+ )`;+}++export async function canReceiveResourceNotification(+ userId: string,+ resourceId?: string | null,+ resourceType?: string | null,+) {+ const [user] = await db+ .select({ id: userTable.id })+ .from(userTable)+ .where(+ and(+ eq(userTable.id, userId),+ notificationResourceAccess(+ userId,+ resourceId ?? null,+ resourceType ?? null,+ ),+ ),+ )+ .limit(1);+ return Boolean(user);+}diff --git a/apps/api/src/oauth/index.ts b/apps/api/src/oauth/index.tsindex 66bda2b4d..414cf89dc 100644--- a/apps/api/src/oauth/index.ts+++ b/apps/api/src/oauth/index.ts@@ -1,8 +1,10 @@import { apiRouter, createRoute, jsonResponse } from "../openapi";+import { requireUserSession } from "../utils/require-user-session";import getIdToken from "./controllers/get-id-token";import { idTokenSchema } from "./response";const getIdTokenRoute = createRoute({+ middleware: [requireUserSession] as const,method: "get",operationId: "getOAuthIdToken",path: "/id-token",diff --git a/apps/api/src/plugins/generic-webhook/client.ts b/apps/api/src/plugins/generic-webhook/client.tsindex 109192aeb..e58e310be 100644--- a/apps/api/src/plugins/generic-webhook/client.ts+++ b/apps/api/src/plugins/generic-webhook/client.ts@@ -1,20 +1,19 @@import { createHmac } from "node:crypto";import * as Sentry from "@sentry/node";-import { assertPublicWebhookDestination } from "./config";+import { sendOutboundRequest } from "../../utils/outbound-request";type GenericWebhookPayload = Record<string, unknown>;-const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);--const GENERIC_WEBHOOK_TIMEOUT_MS = 10_000;-export async function postToGenericWebhook(webhookUrl: string,payload: GenericWebhookPayload,secret?: string,): Promise<void> {- await assertPublicWebhookDestination(webhookUrl);-+ Sentry.addBreadcrumb({+ category: "integration",+ level: "info",+ data: { integration: "generic-webhook" },+ });const body = JSON.stringify(payload);const headers: Record<string, string> = {"Content-Type": "application/json",@@ -26,48 +25,9 @@ export async function postToGenericWebhook(.digest("hex");}- const controller = new AbortController();- const timeoutId = setTimeout(- () => controller.abort(),- GENERIC_WEBHOOK_TIMEOUT_MS,+ await sendOutboundRequest(+ webhookUrl,+ { headers, body },+ { publicDestination: true },);-- try {- Sentry.addBreadcrumb({- category: "integration",- level: "info",- data: { integration: "generic-webhook" },- });- const response = await fetch(webhookUrl, {- method: "POST",- headers,- body,- signal: controller.signal,- redirect: "manual",- });-- if (REDIRECT_STATUSES.has(response.status)) {- await response.body?.cancel();- throw new Error(- `Generic webhook request was redirected (${response.status}); redirects are not followed`,- );- }-- if (!response.ok) {- const errorText = await response.text();- throw new Error(- `Generic webhook request failed (${response.status}): ${errorText}`,- );- }- } catch (error) {- if (error instanceof Error && error.name === "AbortError") {- throw new Error(- `Generic webhook request timed out after ${GENERIC_WEBHOOK_TIMEOUT_MS}ms`,- );- }-- throw error;- } finally {- clearTimeout(timeoutId);- }}diff --git a/apps/api/src/plugins/generic-webhook/events.ts b/apps/api/src/plugins/generic-webhook/events.tsindex b8392debc..f26228081 100644--- a/apps/api/src/plugins/generic-webhook/events.ts+++ b/apps/api/src/plugins/generic-webhook/events.ts@@ -8,6 +8,7 @@ import {userTable,workspaceTable,} from "../../database/schema";+import { safeOutboundError } from "../../utils/outbound-request";import type {PluginContext,TaskAssigneeChangedEvent,@@ -139,9 +140,9 @@ async function persistWebhookHealth(updatedAt: new Date(),}).where(eq(integrationTable.id, integration.id));- } catch (error) {+ } catch {console.error("persistWebhookHealth failed", {- error,+ error: "Webhook health update failed",projectId,});}@@ -158,7 +159,7 @@ async function deliverWebhookEvent(eventName,taskId,projectId,- webhookUrl: config.webhookUrl,+ webhookUrl: "configured destination",};try {@@ -175,8 +176,7 @@ async function deliverWebhookEvent(}));return true;} catch (error) {- const message =- error instanceof Error ? (error.stack ?? error.message) : String(error);+ const message = safeOutboundError(error);void persistWebhookHealth(projectId, (currentConfig) => ({...currentConfig,@@ -190,11 +190,11 @@ async function deliverWebhookEvent(}));console.error("postToGenericWebhook failed", {- error,+ error: message,eventName,taskId,projectId,- webhookUrl: config.webhookUrl,+ webhookUrl: "configured destination",});return false;}diff --git a/apps/api/src/plugins/github/config.ts b/apps/api/src/plugins/github/config.tsindex bbf32756b..476f0b30b 100644--- a/apps/api/src/plugins/github/config.ts+++ b/apps/api/src/plugins/github/config.ts@@ -17,6 +17,9 @@ export const githubConfigSchema = v.object({repositoryOwner: v.string(),repositoryName: v.string(),installationId: v.nullable(v.number()),+ repositoryId: v.optional(v.number()),+ verifiedGithubAccountId: v.optional(v.string()),+ verifiedByUserId: v.optional(v.string()),branchPattern: v.optional(v.string()),customBranchRegex: v.optional(v.string()),commentTaskLinkOnGitHubIssue: v.optional(v.boolean()),@@ -73,3 +76,17 @@ export function getDefaultConfig(...defaultGitHubConfig,};}++/** Legacy integrations require explicit re-verification by a repository administrator. */+export function hasVerifiedGitHubBinding(config: GitHubConfig): boolean {+ return (+ Number.isSafeInteger(config.installationId) &&+ (config.installationId ?? 0) > 0 &&+ Number.isSafeInteger(config.repositoryId) &&+ (config.repositoryId ?? 0) > 0 &&+ typeof config.verifiedGithubAccountId === "string" &&+ /^[1-9][0-9]*$/.test(config.verifiedGithubAccountId) &&+ typeof config.verifiedByUserId === "string" &&+ config.verifiedByUserId.length > 0+ );+}diff --git a/apps/api/src/plugins/github/events/task-comment-created.ts b/apps/api/src/plugins/github/events/task-comment-created.tsindex 6c51e55c6..e5f38bc0e 100644--- a/apps/api/src/plugins/github/events/task-comment-created.ts+++ b/apps/api/src/plugins/github/events/task-comment-created.ts@@ -1,7 +1,10 @@import type { PluginContext, TaskCommentCreatedEvent } from "../../types";-import type { GitHubConfig } from "../config";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import { findExternalLinkByTaskAndType } from "../services/link-manager";-import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import {+ getGithubApp,+ getVerifiedInstallationOctokit,+} from "../utils/github-app";export async function handleTaskCommentCreated(event: TaskCommentCreatedEvent,@@ -13,6 +16,7 @@ export async function handleTaskCommentCreated(}const config = context.config as GitHubConfig;+ if (!hasVerifiedGitHubBinding(config)) return;const { repositoryOwner, repositoryName } = config;const existingLink = await findExternalLinkByTaskAndType(@@ -26,15 +30,7 @@ export async function handleTaskCommentCreated(}try {- let installationId = config.installationId;- if (!installationId) {- installationId = await getInstallationIdForRepo(- repositoryOwner,- repositoryName,- );- }-- const octokit = await githubApp.getInstallationOctokit(installationId);+ const octokit = await getVerifiedInstallationOctokit(config);const issueNumber = Number.parseInt(existingLink.externalId, 10);diff --git a/apps/api/src/plugins/github/events/task-created.ts b/apps/api/src/plugins/github/events/task-created.tsindex b4e8a3631..86149a961 100644--- a/apps/api/src/plugins/github/events/task-created.ts+++ b/apps/api/src/plugins/github/events/task-created.ts@@ -2,7 +2,7 @@ import { eq } from "drizzle-orm";import db from "../../../database";import { projectTable } from "../../../database/schema";import type { PluginContext, TaskCreatedEvent } from "../../types";-import type { GitHubConfig } from "../config";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import {createExternalLink,findExternalLinkByTaskAndType,@@ -12,7 +12,10 @@ import {formatIssueTitle,getLabelsForIssue,} from "../utils/format";-import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import {+ getGithubApp,+ getVerifiedInstallationOctokit,+} from "../utils/github-app";import { addLabelsToIssue } from "../utils/labels";export async function handleTaskCreated(@@ -25,6 +28,7 @@ export async function handleTaskCreated(}const config = context.config as GitHubConfig;+ if (!hasVerifiedGitHubBinding(config)) return;const { repositoryOwner, repositoryName } = config;const existingLink = await findExternalLinkByTaskAndType(@@ -38,15 +42,7 @@ export async function handleTaskCreated(}try {- let installationId = config.installationId;- if (!installationId) {- installationId = await getInstallationIdForRepo(- repositoryOwner,- repositoryName,- );- }-- const octokit = await githubApp.getInstallationOctokit(installationId);+ const octokit = await getVerifiedInstallationOctokit(config);const createdIssue = await octokit.rest.issues.create({owner: repositoryOwner,diff --git a/apps/api/src/plugins/github/events/task-description-changed.ts b/apps/api/src/plugins/github/events/task-description-changed.tsindex d50d2e103..efe559293 100644--- a/apps/api/src/plugins/github/events/task-description-changed.ts+++ b/apps/api/src/plugins/github/events/task-description-changed.ts@@ -1,11 +1,14 @@import type { PluginContext, TaskDescriptionChangedEvent } from "../../types";-import type { GitHubConfig } from "../config";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import {findExternalLinksByTask,updateExternalLink,} from "../services/link-manager";import { formatIssueBody } from "../utils/format";-import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import {+ getGithubApp,+ getVerifiedInstallationOctokit,+} from "../utils/github-app";export async function handleTaskDescriptionChanged(event: TaskDescriptionChangedEvent,@@ -17,6 +20,7 @@ export async function handleTaskDescriptionChanged(}const config = context.config as GitHubConfig;+ if (!hasVerifiedGitHubBinding(config)) return;const { repositoryOwner, repositoryName } = config;try {@@ -58,15 +62,7 @@ export async function handleTaskDescriptionChanged(}}- let installationId = config.installationId;- if (!installationId) {- installationId = await getInstallationIdForRepo(- repositoryOwner,- repositoryName,- );- }-- const octokit = await githubApp.getInstallationOctokit(installationId);+ const octokit = await getVerifiedInstallationOctokit(config);const issueNumber = Number.parseInt(issueLink.externalId, 10);// Format description with task ID footerdiff --git a/apps/api/src/plugins/github/events/task-priority-changed.ts b/apps/api/src/plugins/github/events/task-priority-changed.tsindex 8f27676bf..444080233 100644--- a/apps/api/src/plugins/github/events/task-priority-changed.ts+++ b/apps/api/src/plugins/github/events/task-priority-changed.ts@@ -1,7 +1,10 @@import type { PluginContext, TaskPriorityChangedEvent } from "../../types";-import type { GitHubConfig } from "../config";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import { findExternalLinksByTask } from "../services/link-manager";-import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import {+ getGithubApp,+ getVerifiedInstallationOctokit,+} from "../utils/github-app";import { addLabelsToIssue, removeLabel } from "../utils/labels";export async function handleTaskPriorityChanged(@@ -14,6 +17,7 @@ export async function handleTaskPriorityChanged(}const config = context.config as GitHubConfig;+ if (!hasVerifiedGitHubBinding(config)) return;const { repositoryOwner, repositoryName } = config;try {@@ -28,15 +32,7 @@ export async function handleTaskPriorityChanged(return;}- let installationId = config.installationId;- if (!installationId) {- installationId = await getInstallationIdForRepo(- repositoryOwner,- repositoryName,- );- }-- const octokit = await githubApp.getInstallationOctokit(installationId);+ const octokit = await getVerifiedInstallationOctokit(config);const issueNumber = Number.parseInt(issueLink.externalId, 10);if (event.oldPriority && event.oldPriority !== "no-priority") {diff --git a/apps/api/src/plugins/github/events/task-status-changed.ts b/apps/api/src/plugins/github/events/task-status-changed.tsindex 8650f3264..ef8125b1c 100644--- a/apps/api/src/plugins/github/events/task-status-changed.ts+++ b/apps/api/src/plugins/github/events/task-status-changed.ts@@ -1,10 +1,13 @@import type { PluginContext, TaskStatusChangedEvent } from "../../types";-import type { GitHubConfig } from "../config";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import {findExternalLinksByTask,updateExternalLink,} from "../services/link-manager";-import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import {+ getGithubApp,+ getVerifiedInstallationOctokit,+} from "../utils/github-app";import { addLabelsToIssue, removeLabel } from "../utils/labels";export async function handleTaskStatusChanged(@@ -17,6 +20,7 @@ export async function handleTaskStatusChanged(}const config = context.config as GitHubConfig;+ if (!hasVerifiedGitHubBinding(config)) return;const { repositoryOwner, repositoryName } = config;try {@@ -31,15 +35,7 @@ export async function handleTaskStatusChanged(return;}- let installationId = config.installationId;- if (!installationId) {- installationId = await getInstallationIdForRepo(- repositoryOwner,- repositoryName,- );- }-- const octokit = await githubApp.getInstallationOctokit(installationId);+ const octokit = await getVerifiedInstallationOctokit(config);const issueNumber = Number.parseInt(issueLink.externalId, 10);await removeLabel(diff --git a/apps/api/src/plugins/github/events/task-title-changed.ts b/apps/api/src/plugins/github/events/task-title-changed.tsindex 13f36ac6f..d0e18c8df 100644--- a/apps/api/src/plugins/github/events/task-title-changed.ts+++ b/apps/api/src/plugins/github/events/task-title-changed.ts@@ -1,10 +1,13 @@import type { PluginContext, TaskTitleChangedEvent } from "../../types";-import type { GitHubConfig } from "../config";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";import {findExternalLinksByTask,updateExternalLink,} from "../services/link-manager";-import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import {+ getGithubApp,+ getVerifiedInstallationOctokit,+} from "../utils/github-app";export async function handleTaskTitleChanged(event: TaskTitleChangedEvent,@@ -16,6 +19,7 @@ export async function handleTaskTitleChanged(}const config = context.config as GitHubConfig;+ if (!hasVerifiedGitHubBinding(config)) return;const { repositoryOwner, repositoryName } = config;try {@@ -55,15 +59,7 @@ export async function handleTaskTitleChanged(}}- let installationId = config.installationId;- if (!installationId) {- installationId = await getInstallationIdForRepo(- repositoryOwner,- repositoryName,- );- }-- const octokit = await githubApp.getInstallationOctokit(installationId);+ const octokit = await getVerifiedInstallationOctokit(config);const issueNumber = Number.parseInt(issueLink.externalId, 10);await octokit.rest.issues.update({diff --git a/apps/api/src/plugins/github/services/link-manager.ts b/apps/api/src/plugins/github/services/link-manager.tsindex 56bb13bea..abf8ba1b7 100644--- a/apps/api/src/plugins/github/services/link-manager.ts+++ b/apps/api/src/plugins/github/services/link-manager.ts@@ -2,6 +2,8 @@ import { and, eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";+type DbOrTx = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];+export type CreateExternalLinkParams = {taskId: string;integrationId: string;@@ -20,8 +22,9 @@ export type UpdateExternalLinkParams = {export async function createExternalLink(params: CreateExternalLinkParams,+ database: DbOrTx = db,): Promise<{ id: string }> {- const result = await db+ const result = await database.insert(externalLinkTable).values({taskId: params.taskId,@@ -46,8 +49,9 @@ export async function findExternalLink(integrationId: string,resourceType: string,externalId: string,+ database: DbOrTx = db,) {- return db.query.externalLinkTable.findFirst({+ return database.query.externalLinkTable.findFirst({where: and(eq(externalLinkTable.integrationId, integrationId),eq(externalLinkTable.resourceType, resourceType),diff --git a/apps/api/src/plugins/github/services/task-service.ts b/apps/api/src/plugins/github/services/task-service.tsindex 603ca9f95..ac0a2d591 100644--- a/apps/api/src/plugins/github/services/task-service.ts+++ b/apps/api/src/plugins/github/services/task-service.ts@@ -6,6 +6,7 @@ import {integrationTable,taskTable,} from "../../../database/schema";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";export type TaskRow = InferSelectModel<typeof taskTable>;@@ -117,26 +118,34 @@ export async function getIntegrationWithProject(integrationId: string) {});}-export async function findIntegrationByRepo(owner: string, repo: string) {- const integrations = await findAllIntegrationsByRepo(owner, repo);- return integrations[0] || null;-}--export async function findAllIntegrationsByRepo(owner: string, repo: string) {+export type GitHubWebhookSource = {+ installation?: { id: number };+ repository: { id: number };+};++export async function findAllIntegrationsByRepo(source: GitHubWebhookSource) {+ const installationId = source.installation?.id;+ const repositoryId = source.repository.id;+ if (+ !Number.isSafeInteger(installationId) ||+ !Number.isSafeInteger(repositoryId)+ )+ return [];const integrations = await db.query.integrationTable.findMany({where: and(eq(integrationTable.type, "github"),eq(integrationTable.isActive, true),),- with: {- project: true,- },+ with: { project: true },});-return integrations.filter((integration) => {try {- const config = JSON.parse(integration.config);- return config.repositoryOwner === owner && config.repositoryName === repo;+ const config = JSON.parse(integration.config) as GitHubConfig;+ return (+ hasVerifiedGitHubBinding(config) &&+ config.installationId === installationId &&+ config.repositoryId === repositoryId+ );} catch {return false;}diff --git a/apps/api/src/plugins/github/utils/format.ts b/apps/api/src/plugins/github/utils/format.tsindex a3f8aa329..96da2fb2d 100644--- a/apps/api/src/plugins/github/utils/format.ts+++ b/apps/api/src/plugins/github/utils/format.ts@@ -39,6 +39,14 @@ export function getLabelsForIssue(export function formatTaskDescriptionFromIssue(issueBody: string | null,+ taskId?: string,): string {- return issueBody || "";+ const body = issueBody || "";+ // Only remove our exact trailing footer for the already-linked task.+ // New imports and arbitrary Task mentions remain untouched.+ if (!taskId) return body;+ const footer = `<sub>Task: ${taskId}</sub>`;+ if (body === footer) return "";+ const suffix = `\n\n---\n${footer}`;+ return body.endsWith(suffix) ? body.slice(0, -suffix.length) : body;}diff --git a/apps/api/src/plugins/github/utils/github-app.ts b/apps/api/src/plugins/github/utils/github-app.tsindex 4c7e2165f..9fe8be794 100644--- a/apps/api/src/plugins/github/utils/github-app.ts+++ b/apps/api/src/plugins/github/utils/github-app.ts@@ -1,10 +1,13 @@import * as Sentry from "@sentry/node";import { config } from "dotenv-mono";-import { App } from "octokit";+import { App, Octokit } from "octokit";+import { boundedGithubFetch } from "../../../utils/bounded-github-fetch";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";config();let githubAppInstance: App | null = null;+let githubImportAppInstance: App | null = null;// Resolve the GitHub App private key from env in whichever form the host// can carry. Orchestrators like Portainer's form-based stack editor strip@@ -28,9 +31,10 @@ export function resolveGithubPrivateKey(): string {return raw;}-export function getGithubApp(): App | null {- if (githubAppInstance) {- return githubAppInstance;+export function getGithubApp(boundedImport = false): App | null {+ const existing = boundedImport ? githubImportAppInstance : githubAppInstance;+ if (existing) {+ return existing;}const privateKey = resolveGithubPrivateKey();@@ -42,7 +46,16 @@ export function getGithubApp(): App | null {return null;}- githubAppInstance = new App({+ const app = new App({+ ...(boundedImport+ ? {+ Octokit: Octokit.defaults({+ throttle: { enabled: false },+ retry: { enabled: false },+ request: { fetch: boundedGithubFetch, timeout: 10_000 },+ }),+ }+ : {}),appId: process.env.GITHUB_APP_ID ?? "",privateKey,webhooks: {@@ -50,11 +63,16 @@ export function getGithubApp(): App | null {},});- return githubAppInstance;+ if (boundedImport) githubImportAppInstance = app;+ else githubAppInstance = app;+ return app;}-export async function getInstallationOctokit(installationId: number) {- const app = getGithubApp();+export async function getInstallationOctokit(+ installationId: number,+ boundedImport = false,+) {+ const app = getGithubApp(boundedImport);if (!app) {throw new Error("GitHub App not configured");}@@ -92,3 +110,28 @@ export async function getInstallationIdForRepo(return installation.id;}++/** Prevent name reuse or transfer from redirecting writes to a different repository. */+export async function getVerifiedInstallationOctokit(+ config: GitHubConfig,+ boundedImport = false,+) {+ if (!hasVerifiedGitHubBinding(config) || !config.installationId) {+ throw new Error("GitHub integration requires verification");+ }+ const octokit = await getInstallationOctokit(+ config.installationId,+ boundedImport,+ );+ const { data: repository } = await octokit.rest.repos.get({+ owner: config.repositoryOwner,+ repo: config.repositoryName,+ request: { timeout: 10_000 },+ });+ if (repository.id !== config.repositoryId) {+ throw new Error(+ "GitHub repository identity changed; reconnect the integration",+ );+ }+ return octokit;+}diff --git a/apps/api/src/plugins/github/utils/resolve-column.ts b/apps/api/src/plugins/github/utils/resolve-column.tsindex 72948c243..136f547d3 100644--- a/apps/api/src/plugins/github/utils/resolve-column.ts+++ b/apps/api/src/plugins/github/utils/resolve-column.ts@@ -6,8 +6,11 @@ export async function resolveTargetStatus(projectId: string,eventType: string,fallbackStatus: string,+ database:+ | typeof db+ | Parameters<Parameters<typeof db.transaction>[0]>[0] = db,): Promise<string> {- const projectColumns = await db+ const projectColumns = await database.select({id: columnTable.id,slug: columnTable.slug,@@ -20,7 +23,7 @@ export async function resolveTargetStatus(return fallbackStatus;}- const rule = await db.query.workflowRuleTable.findFirst({+ const rule = await database.query.workflowRuleTable.findFirst({where: and(eq(workflowRuleTable.projectId, projectId),eq(workflowRuleTable.integrationType, "github"),diff --git a/apps/api/src/plugins/github/utils/sync-label-to-github.ts b/apps/api/src/plugins/github/utils/sync-label-to-github.tsindex 60bb12f08..90734f3f7 100644--- a/apps/api/src/plugins/github/utils/sync-label-to-github.ts+++ b/apps/api/src/plugins/github/utils/sync-label-to-github.ts@@ -1,7 +1,8 @@import { eq } from "drizzle-orm";import db from "../../../database";import { externalLinkTable } from "../../../database/schema";-import { getInstallationOctokit } from "./github-app";+import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";+import { getVerifiedInstallationOctokit } from "./github-app";const namedColorToHex: Record<string, string> = {red: "EF4444",@@ -56,27 +57,25 @@ async function getGitHubContext(taskId: string) {}const integration = externalLink.integration;- if (integration?.type !== "github") {+ if (integration?.type !== "github" || !integration.isActive) {return null;}- let config: {- repositoryOwner: string;- repositoryName: string;- installationId?: number;- };+ let config: GitHubConfig;try {config = JSON.parse(integration.config);} catch {return null;}- if (!config.installationId) {+ if (!hasVerifiedGitHubBinding(config) || !config.installationId) {return null;}- const octokit = await getInstallationOctokit(config.installationId);- if (!octokit) {+ let octokit: Awaited<ReturnType<typeof getVerifiedInstallationOctokit>>;+ try {+ octokit = await getVerifiedInstallationOctokit(config);+ } catch {return null;}diff --git a/apps/api/src/plugins/github/webhooks/issue-closed.ts b/apps/api/src/plugins/github/webhooks/issue-closed.tsindex 9f490825b..9a8933b9a 100644--- a/apps/api/src/plugins/github/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/github/webhooks/issue-closed.ts@@ -18,7 +18,9 @@ type IssueClosedPayload = {html_url: string;state: string;};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;full_name: string;@@ -26,12 +28,9 @@ type IssueClosedPayload = {};export async function handleIssueClosed(payload: IssueClosedPayload) {- const { issue, repository } = payload;+ const { issue } = payload;- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);for (const integration of integrations) {const externalLink = await db.query.externalLinkTable.findFirst({diff --git a/apps/api/src/plugins/github/webhooks/issue-comment-created.ts b/apps/api/src/plugins/github/webhooks/issue-comment-created.tsindex e5efecf3f..ff88fa658 100644--- a/apps/api/src/plugins/github/webhooks/issue-comment-created.ts+++ b/apps/api/src/plugins/github/webhooks/issue-comment-created.ts@@ -18,7 +18,9 @@ type IssueCommentCreatedPayload = {} | null;created_at: string;};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;};@@ -27,7 +29,7 @@ type IssueCommentCreatedPayload = {export async function handleIssueCommentCreated(payload: IssueCommentCreatedPayload,) {- const { issue, comment, repository } = payload;+ const { issue, comment } = payload;if (payload.action !== "created") {return;@@ -38,10 +40,7 @@ export async function handleIssueCommentCreated(return;}- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);for (const integration of integrations) {const existingLink = await findExternalLink(diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.tsindex eaafa9e32..8847206bc 100644--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts@@ -37,7 +37,9 @@ type IssueEditedPayload = {from: string;};};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;full_name: string;@@ -45,7 +47,7 @@ type IssueEditedPayload = {};export async function handleIssueEdited(payload: IssueEditedPayload) {- const { issue, repository, changes } = payload;+ const { issue, changes } = payload;if (!changes?.title && !changes?.body) {console.log(@@ -54,10 +56,7 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {return;}- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);for (const integration of integrations) {const externalLink = await findExternalLink(@@ -133,7 +132,10 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {if (changes.body) {const lastDescSync = metadata.lastSync?.description;- const formattedDescription = formatTaskDescriptionFromIssue(issue.body);+ const formattedDescription = formatTaskDescriptionFromIssue(+ issue.body,+ task.id,+ );let shouldUpdateDescription = true;diff --git a/apps/api/src/plugins/github/webhooks/issue-labeled.ts b/apps/api/src/plugins/github/webhooks/issue-labeled.tsindex 877e2966c..63252bec6 100644--- a/apps/api/src/plugins/github/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/github/webhooks/issue-labeled.ts@@ -22,19 +22,18 @@ type IssueLabeledPayload = {name: string;color: string;};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;};};export async function handleIssueLabeled(payload: IssueLabeledPayload) {- const { issue, repository, label: addedLabel } = payload;+ const { issue, label: addedLabel } = payload;- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);for (const integration of integrations) {const existingLink = await findExternalLink(diff --git a/apps/api/src/plugins/github/webhooks/issue-opened.ts b/apps/api/src/plugins/github/webhooks/issue-opened.tsindex 85b06056e..02029446d 100644--- a/apps/api/src/plugins/github/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-opened.ts@@ -1,6 +1,11 @@import { and, eq } from "drizzle-orm";import db from "../../../database";-import { columnTable, projectTable, taskTable } from "../../../database/schema";+import {+ columnTable,+ integrationTable,+ projectTable,+ taskTable,+} from "../../../database/schema";import { claimTaskNumber } from "../../../task/controllers/claim-task-numbers";import type { GitHubConfig } from "../config";import { createExternalLink, findExternalLink } from "../services/link-manager";@@ -24,7 +29,9 @@ type IssueOpenedPayload = {labels?: Array<string | { name?: string }>;user: { login: string } | null;};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;full_name: string;@@ -47,10 +54,7 @@ export async function handleIssueOpened(payload: IssueOpenedPayload) {return;}- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);if (integrations.length === 0) {return;@@ -63,69 +67,69 @@ export async function handleIssueOpened(payload: IssueOpenedPayload) {const priority = extractIssuePriority(issue.labels);const status = extractIssueStatus(issue.labels);- const existingLink = await findExternalLink(- integration.id,- "issue",- issue.number.toString(),- );-- if (existingLink) {- console.log(- `Issue #${issue.number} already linked to task ${existingLink.taskId} in project ${projectId}, skipping`,+ const createdTask = await db.transaction(async (tx) => {+ // Use the same integration lock as resumable imports before checking the+ // link. The task and link must either both commit or both roll back.+ const [current] = await tx+ .select()+ .from(integrationTable)+ .where(eq(integrationTable.id, integration.id))+ .for("update");+ if (!current?.isActive || current.config !== integration.config)+ return null;+ const existingLink = await findExternalLink(+ integration.id,+ "issue",+ String(issue.number),+ tx,);- continue;- }-- const nextTaskNumber = await claimTaskNumber(projectId);-- const resolvedStatus = await resolveTargetStatus(- projectId,- "issue_opened",- status || "to-do",- );-- const targetStatus = resolvedStatus;- const targetColumn = await db.query.columnTable.findFirst({- where: and(- eq(columnTable.projectId, projectId),- eq(columnTable.slug, targetStatus),- ),- });-- const taskValues: typeof taskTable.$inferInsert = {- projectId,- userId: null,- title: issue.title,- description: formatTaskDescriptionFromIssue(issue.body),- status: targetStatus,- columnId: targetColumn?.id ?? null,- priority: priority ?? "low",- number: nextTaskNumber,- };-- const [createdTask] = await db- .insert(taskTable)- .values(taskValues)- .returning();-- if (!createdTask) {- console.error("Failed to create task from GitHub issue");- continue;- }-- await createExternalLink({- taskId: createdTask.id,- integrationId: integration.id,- resourceType: "issue",- externalId: issue.number.toString(),- url: issue.html_url,- title: issue.title,- metadata: {- state: "open",- createdFrom: "github",- author: issue.user?.login,- },+ if (existingLink) return null;+ const targetStatus = await resolveTargetStatus(+ projectId,+ "issue_opened",+ status || "to-do",+ tx,+ );+ const targetColumn = await tx.query.columnTable.findFirst({+ where: and(+ eq(columnTable.projectId, projectId),+ eq(columnTable.slug, targetStatus),+ ),+ });+ const number = await claimTaskNumber(projectId, tx);+ const [task] = await tx+ .insert(taskTable)+ .values({+ projectId,+ userId: null,+ title: issue.title,+ description: formatTaskDescriptionFromIssue(issue.body),+ status: targetStatus,+ columnId: targetColumn?.id ?? null,+ priority: priority ?? "low",+ number,+ })+ .returning();+ if (!task) throw new Error("Failed to create task from GitHub issue");+ await createExternalLink(+ {+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: String(issue.number),+ url: issue.html_url,+ title: issue.title,+ metadata: {+ state: "open",+ createdFrom: "github",+ author: issue.user?.login,+ },+ },+ tx,+ );+ return task;});+ if (!createdTask) continue;const project = await db.query.projectTable.findFirst({where: eq(projectTable.id, projectId),diff --git a/apps/api/src/plugins/github/webhooks/issue-reopened.ts b/apps/api/src/plugins/github/webhooks/issue-reopened.tsindex 7f838deda..e2fb54779 100644--- a/apps/api/src/plugins/github/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-reopened.ts@@ -7,6 +7,7 @@ import {findAllIntegrationsByRepo,updateTaskStatus,} from "../services/task-service";+import { parseLinkMetadata } from "../utils/parse-link-metadata";import { resolveTargetStatus } from "../utils/resolve-column";type IssueReopenedPayload = {@@ -17,7 +18,9 @@ type IssueReopenedPayload = {html_url: string;state: string;};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;full_name: string;@@ -25,12 +28,9 @@ type IssueReopenedPayload = {};export async function handleIssueReopened(payload: IssueReopenedPayload) {- const { issue, repository } = payload;+ const { issue } = payload;- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);for (const integration of integrations) {const externalLink = await db.query.externalLinkTable.findFirst({@@ -53,21 +53,10 @@ export async function handleIssueReopened(payload: IssueReopenedPayload) {continue;}- let existingMetadata: Record<string, unknown> = {};- if (externalLink.metadata) {- try {- existingMetadata = JSON.parse(externalLink.metadata) as Record<- string,- unknown- >;- } catch (error) {- console.warn("Failed to parse GitHub issue metadata for reopen sync", {- externalLinkId: externalLink.id,- metadata: externalLink.metadata,- error,- });- }- }+ const existingMetadata = parseLinkMetadata(externalLink.metadata, {+ externalLinkId: externalLink.id,+ source: "issue_reopened",+ });if (existingMetadata.createdFrom === "kaneo") {continue;diff --git a/apps/api/src/plugins/github/webhooks/label-created.ts b/apps/api/src/plugins/github/webhooks/label-created.tsindex bef816c19..5f29b6056 100644--- a/apps/api/src/plugins/github/webhooks/label-created.ts+++ b/apps/api/src/plugins/github/webhooks/label-created.ts@@ -10,19 +10,18 @@ type LabelCreatedPayload = {color: string;description?: string | null;};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;};};export async function handleLabelCreated(payload: LabelCreatedPayload) {- const { repository, label } = payload;+ const { label } = payload;- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);for (const integration of integrations) {if (!integration.project) {diff --git a/apps/api/src/plugins/github/webhooks/pull-request-closed.ts b/apps/api/src/plugins/github/webhooks/pull-request-closed.tsindex a4a7bbbfd..99affb901 100644--- a/apps/api/src/plugins/github/webhooks/pull-request-closed.ts+++ b/apps/api/src/plugins/github/webhooks/pull-request-closed.ts@@ -25,19 +25,18 @@ type PRClosedPayload = {ref: string;};};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;};};export async function handlePullRequestClosed(payload: PRClosedPayload) {- const { pull_request, repository } = payload;+ const { pull_request } = payload;- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);for (const integration of integrations) {const config = JSON.parse(integration.config) as GitHubConfig;diff --git a/apps/api/src/plugins/github/webhooks/pull-request-opened.ts b/apps/api/src/plugins/github/webhooks/pull-request-opened.tsindex 6918c1137..ebfcd2052 100644--- a/apps/api/src/plugins/github/webhooks/pull-request-opened.ts+++ b/apps/api/src/plugins/github/webhooks/pull-request-opened.ts@@ -25,19 +25,18 @@ type PROpenedPayload = {};user: { login: string } | null;};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;};};export async function handlePullRequestOpened(payload: PROpenedPayload) {- const { pull_request, repository } = payload;+ const { pull_request } = payload;- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);for (const integration of integrations) {if (!integration.project) {diff --git a/apps/api/src/plugins/github/webhooks/push.ts b/apps/api/src/plugins/github/webhooks/push.tsindex a6c0e6e11..f3e41d3b1 100644--- a/apps/api/src/plugins/github/webhooks/push.ts+++ b/apps/api/src/plugins/github/webhooks/push.ts@@ -18,7 +18,9 @@ type PushPayload = {author?: { name: string };timestamp: string;};+ installation?: { id: number };repository: {+ id: number;owner: { login: string };name: string;html_url: string;@@ -44,10 +46,7 @@ export async function handlePush(payload: PushPayload) {return;}- const integrations = await findAllIntegrationsByRepo(- repository.owner.login,- repository.name,- );+ const integrations = await findAllIntegrationsByRepo(payload);if (integrations.length === 0) {console.log(diff --git a/apps/api/src/plugins/telegram/client.ts b/apps/api/src/plugins/telegram/client.tsindex 411fca839..54e69dc2a 100644--- a/apps/api/src/plugins/telegram/client.ts+++ b/apps/api/src/plugins/telegram/client.ts@@ -1,4 +1,8 @@import * as Sentry from "@sentry/node";+import {+ OutboundRequestError,+ sendOutboundRequest,+} from "../../utils/outbound-request";type TelegramMessage = {chat_id: string;@@ -8,57 +12,29 @@ type TelegramMessage = {message_thread_id?: number;};-const TELEGRAM_TIMEOUT_MS = 10_000;-export async function postToTelegram(botToken: string,message: TelegramMessage,): Promise<void> {- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), TELEGRAM_TIMEOUT_MS);-- try {- Sentry.addBreadcrumb({- category: "integration",- level: "info",- data: { integration: "telegram" },- });- const response = await fetch(- `https://api.telegram.org/bot${botToken}/sendMessage`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(message),- signal: controller.signal,- },- );-- if (!response.ok) {- const errorText = await response.text();- throw new Error(- `Telegram request failed (${response.status}): ${errorText}`,- );- }-- const result = (await response.json()) as {- ok?: boolean;- description?: string;- };-- if (!result.ok) {- throw new Error(result.description || "Telegram API request failed");- }- } catch (error) {- if (error instanceof Error && error.name === "AbortError") {- throw new Error(- `Telegram request timed out after ${TELEGRAM_TIMEOUT_MS}ms`,- );- }-- throw error;- } finally {- clearTimeout(timeoutId);+ Sentry.addBreadcrumb({+ category: "integration",+ level: "info",+ data: { integration: "telegram" },+ });+ const result = await sendOutboundRequest(+ `https://api.telegram.org/bot${botToken}/sendMessage`,+ {+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(message),+ },+ { readJson: true },+ );+ if (+ !result ||+ typeof result !== "object" ||+ !("ok" in result) ||+ result.ok !== true+ ) {+ throw new OutboundRequestError("response");}}diff --git a/apps/api/src/plugins/telegram/events.ts b/apps/api/src/plugins/telegram/events.tsindex 38d0ba802..f3dd14886 100644--- a/apps/api/src/plugins/telegram/events.ts+++ b/apps/api/src/plugins/telegram/events.ts@@ -7,6 +7,7 @@ import {userTable,workspaceTable,} from "../../database/schema";+import { safeOutboundError } from "../../utils/outbound-request";import type {PluginContext,TaskCommentCreatedEvent,@@ -56,17 +57,6 @@ function escapeHtml(value: string): string {.replace(/>/g, ">");}-function redactBotToken(botToken: string): string {- const [prefix, suffix = ""] = botToken.split(":", 2);- if (!suffix) {- return "redacted";- }-- return `${prefix}:${- suffix.length > 8 ? `${suffix.slice(0, 4)}…${suffix.slice(-4)}` : "••••"- }`;-}-function getSafeTelegramTargetIdentifier(config: TelegramConfig): string {const hash = createHash("sha256").update(`${config.chatId}:${config.threadId ?? "none"}`)@@ -183,8 +173,7 @@ async function sendTelegramMessage(});} catch (error) {console.error("sendTelegramMessage postToTelegram failed", {- error,- botToken: redactBotToken(config.botToken),+ error: safeOutboundError(error),telegramTarget: getSafeTelegramTargetIdentifier(config),taskUrl: data.taskUrl,});@@ -209,8 +198,7 @@ async function runTelegramHandler(const validation = validateTelegramConfig(context.config);if (!validation.valid) {console.error("Invalid Telegram plugin config; skipping event dispatch", {- errors: validation.errors,- config: context.config,+ reason: "Invalid configuration",featureKey,projectId: event.projectId,taskId: event.taskId,diff --git a/apps/api/src/project/controllers/get-public-project.ts b/apps/api/src/project/controllers/get-public-project.tsindex d7a9dafd5..63b2d6637 100644--- a/apps/api/src/project/controllers/get-public-project.ts+++ b/apps/api/src/project/controllers/get-public-project.ts@@ -2,9 +2,14 @@ import { eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { projectTable } from "../../database/schema";-import getTasks from "../../task/controllers/get-tasks";+import getTasks, {+ type GetTasksOptions,+} from "../../task/controllers/get-tasks";-export async function getPublicProject(id: string) {+export async function getPublicProject(+ id: string,+ options: GetTasksOptions = {},+) {const [project] = await db.select({ isPublic: projectTable.isPublic }).from(projectTable)@@ -23,7 +28,7 @@ export async function getPublicProject(id: string) {});}- const result = await getTasks(id);+ const result = await getTasks(id, options);if (!result.data) {throw new HTTPException(404, {@@ -37,5 +42,5 @@ export async function getPublicProject(id: string) {});}- return result.data;+ return { ...result.data, pagination: result.pagination };}diff --git a/apps/api/src/scheduler/due-date-reminders.ts b/apps/api/src/scheduler/due-date-reminders.tsindex 4874ba8c7..f50f6e99b 100644--- a/apps/api/src/scheduler/due-date-reminders.ts+++ b/apps/api/src/scheduler/due-date-reminders.ts@@ -2,9 +2,11 @@ import { and, between, eq, isNotNull, isNull, ne, or, sql } from "drizzle-orm";import db from "../database";import {columnTable,+ projectTable,taskReminderSentTable,taskTable,userNotificationPreferenceTable,+ workspaceUserTable,} from "../database/schema";import createNotification from "../notification/controllers/create-notification";import { REMINDER_WINDOW_MINUTES } from "./reminder-timing";@@ -48,6 +50,14 @@ async function getTasksNeedingReminder(userNotificationPreferenceTable.dueDateReminderLeadTimeMinutes,}).from(taskTable)+ .innerJoin(projectTable, eq(projectTable.id, taskTable.projectId))+ .innerJoin(+ workspaceUserTable,+ and(+ eq(workspaceUserTable.workspaceId, projectTable.workspaceId),+ eq(workspaceUserTable.userId, taskTable.userId),+ ),+ ).leftJoin(columnTable, eq(taskTable.columnId, columnTable.id)).leftJoin(userNotificationPreferenceTable,diff --git a/apps/api/src/scheduler/trial-reminders.ts b/apps/api/src/scheduler/trial-reminders.tsindex 84b633966..18323d85d 100644--- a/apps/api/src/scheduler/trial-reminders.ts+++ b/apps/api/src/scheduler/trial-reminders.ts@@ -53,7 +53,11 @@ function clientUrl() {);}-async function getWorkspacesNeedingReminder(type: ReminderType, now: Date) {+async function getWorkspacesNeedingReminder(+ type: ReminderType,+ now: Date,+ limit: number,+) {const windowStart =type === "trial_ending" ? new Date(now.getTime() + 2 * DAY_MS) : null;const windowEnd =@@ -115,11 +119,7 @@ async function getWorkspacesNeedingReminder(type: ReminderType, now: Date) {).as("owners");- return db- .select()- .from(owners)- .orderBy(asc(owners.trialEndsAt))- .limit(maxPerRun());+ return db.select().from(owners).orderBy(asc(owners.trialEndsAt)).limit(limit);}export async function checkTrialReminders(): Promise<{ degraded: boolean }> {@@ -128,13 +128,19 @@ export async function checkTrialReminders(): Promise<{ degraded: boolean }> {}const now = new Date();+ const limit = maxPerRun();let sent = 0;let degraded = false;for (const reminder of REMINDERS) {+ if (sent >= limit) break;let rows: Awaited<ReturnType<typeof getWorkspacesNeedingReminder>>;try {- rows = await getWorkspacesNeedingReminder(reminder.type, now);+ rows = await getWorkspacesNeedingReminder(+ reminder.type,+ now,+ limit - sent,+ );} catch (error) {console.error(`Failed to query ${reminder.type} reminders`, error);degraded = true;diff --git a/apps/api/src/search/controllers/global-search.ts b/apps/api/src/search/controllers/global-search.tsindex c9d770cf1..a6ce0e2a3 100644--- a/apps/api/src/search/controllers/global-search.ts+++ b/apps/api/src/search/controllers/global-search.ts@@ -153,14 +153,20 @@ async function globalSearch(params: SearchParams): Promise<{// or a decomposed "ПА-23" would never reach the stored composed form.const shortIdMatch = query.normalize("NFKC").match(TASK_SHORT_ID_PATTERN);+ const shortIdNumber = Number(shortIdMatch?.[2]);+if (type === "all" || type === "tasks") {const seenTaskIds = new Set<string>();// If query matches short-id pattern, look up by project slug + task number first- if (shortIdMatch?.[1] && shortIdMatch[2]) {+ if (+ shortIdMatch?.[1] &&+ Number.isSafeInteger(shortIdNumber) &&+ shortIdNumber > 0 &&+ shortIdNumber <= 2_147_483_647+ ) {const slug = shortIdMatch[1];- const numberStr = shortIdMatch[2];- const taskNumber = Number.parseInt(numberStr, 10);+ const taskNumber = shortIdNumber;const shortIdTasks = await db.select({diff --git a/apps/api/src/search/schema.ts b/apps/api/src/search/schema.tsindex 34da835b0..079bce909 100644--- a/apps/api/src/search/schema.ts+++ b/apps/api/src/search/schema.ts@@ -1,7 +1,10 @@import { z } from "../openapi";export const searchQuery = z.object({- q: z.string().min(1, "Query must be at least 1 character"),+ q: z+ .string()+ .min(1, "Query must be at least 1 character")+ .max(512, "Query must not exceed 512 characters"),type: z.enum(["all", "tasks", "projects", "workspaces", "comments", "activities"]).optional()diff --git a/apps/api/src/storage/s3.ts b/apps/api/src/storage/s3.tsindex 7858dc425..fc33e61ec 100644--- a/apps/api/src/storage/s3.ts+++ b/apps/api/src/storage/s3.ts@@ -2,6 +2,8 @@ import { Readable } from "node:stream";import {DeleteObjectCommand,GetObjectCommand,+ HeadObjectCommand,+ type HeadObjectCommandOutput,PutObjectCommand,S3Client,type S3ClientConfig,@@ -275,8 +277,8 @@ export function validateTaskAssetUploadInput(throw new Error("A valid content type is required.");}- if (size <= 0) {- throw new Error("Upload size must be greater than zero.");+ if (!Number.isSafeInteger(size) || size <= 0) {+ throw new Error("Upload size must be a positive safe integer.");}if (size > maxImageUploadBytes) {@@ -287,8 +289,9 @@ export function validateTaskAssetUploadInput(}export async function createTaskImageUploadUrl(- context: TaskImageUploadContext,+ context: TaskImageUploadContext & { size: number },): Promise<TaskImageUploadUrl> {+ validateTaskAssetUploadInput(context.contentType, context.size);const config = getStorageConfig();const client = getClient(config);const rawKey = buildObjectKey(context);@@ -298,21 +301,86 @@ export async function createTaskImageUploadUrl(Bucket: config.bucket,Key: key,ContentType: context.contentType,+ ContentLength: context.size,});const uploadUrl = await getSignedUrl(client, command, {expiresIn: config.presignTtlSeconds,+ signableHeaders: new Set(["content-length", "content-type"]),});return {key,uploadUrl,headers: {+ // The browser supplies Content-Length from the File body. It is signed,+ // but must not be set by JS because it is a forbidden request header."Content-Type": context.contentType,},};}+export class InvalidUploadedAssetError extends Error {}++/** Call only after checking the object's task/workspace key prefix. */+export async function verifyTaskAssetUpload(+ key: string,+ expected: { size: number; contentType: string },+) {+ const config = getStorageConfig();+ const client = getClient(config);+ const abortSignal = AbortSignal.timeout(10_000);+ let object: HeadObjectCommandOutput;+ try {+ object = await client.send(+ new HeadObjectCommand({ Bucket: config.bucket, Key: key }),+ { abortSignal },+ );+ } catch (error) {+ if (+ error instanceof Error &&+ (error.name === "NotFound" ||+ error.name === "NoSuchKey" ||+ ("$metadata" in error &&+ (error.$metadata as { httpStatusCode?: number }).httpStatusCode ===+ 404))+ ) {+ throw new InvalidUploadedAssetError("Uploaded object was not found.");+ }+ // Provider errors may include endpoints, signed URLs or other secrets.+ throw new Error("Unable to verify uploaded object.");+ }++ const size = object.ContentLength;+ if (typeof size === "number" && size > config.maxImageUploadBytes) {+ // Also remove oversized objects made with a still-valid older upload URL.+ // Invalid client size claims never cause deletion of an in-limit object.+ try {+ await client.send(+ new DeleteObjectCommand({ Bucket: config.bucket, Key: key }),+ { abortSignal },+ );+ } catch {+ throw new Error("Unable to remove oversized uploaded object.");+ }+ throw new InvalidUploadedAssetError(+ "Uploaded object exceeds the maximum upload size.",+ );+ }+ if (+ !Number.isSafeInteger(size) ||+ !size ||+ size !== expected.size ||+ !object.ContentType ||+ object.ContentType.toLowerCase() !== expected.contentType.toLowerCase()+ ) {+ throw new InvalidUploadedAssetError(+ "Uploaded object does not match the declared size and content type.",+ );+ }+ return { size, contentType: object.ContentType };+}+export function assertStorageConfigured() {return getStorageConfig();}diff --git a/apps/api/src/task-relation/controllers/delete-task-relation.ts b/apps/api/src/task-relation/controllers/delete-task-relation.tsindex 82174fb57..cfe93ecca 100644--- a/apps/api/src/task-relation/controllers/delete-task-relation.ts+++ b/apps/api/src/task-relation/controllers/delete-task-relation.ts@@ -1,34 +1,35 @@-import { eq } from "drizzle-orm";+import { and, eq, inArray } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { taskRelationTable, taskTable } from "../../database/schema";+import {+ projectTable,+ taskRelationTable,+ taskTable,+} from "../../database/schema";import { publishEvent } from "../../events";-async function deleteTaskRelation(id: string, userId: string) {- const [rel] = await db- .select({- sourceTaskId: taskRelationTable.sourceTaskId,- targetTaskId: taskRelationTable.targetTaskId,- })- .from(taskRelationTable)- .where(eq(taskRelationTable.id, id))- .limit(1);-- if (!rel) {- throw new HTTPException(404, {- message: "Task relation not found",- });- }-- const [task] = await db- .select({ projectId: taskTable.projectId })+async function deleteTaskRelation(+ id: string,+ userId: string,+ workspaceId: string,+) {+ const workspaceTasks = db+ .select({ id: taskTable.id }).from(taskTable)- .where(eq(taskTable.id, rel.sourceTaskId))- .limit(1);+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(eq(projectTable.workspaceId, workspaceId));+ // Check both endpoints in the delete statement itself. Legacy cross-tenant+ // rows must not bypass the same boundary enforced on creation and reads.const [relation] = await db.delete(taskRelationTable)- .where(eq(taskRelationTable.id, id))+ .where(+ and(+ eq(taskRelationTable.id, id),+ inArray(taskRelationTable.sourceTaskId, workspaceTasks),+ inArray(taskRelationTable.targetTaskId, workspaceTasks),+ ),+ ).returning();if (!relation) {@@ -37,12 +38,22 @@ async function deleteTaskRelation(id: string, userId: string) {});}+ const [task] = await db+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(+ and(+ eq(taskTable.id, relation.sourceTaskId),+ eq(projectTable.workspaceId, workspaceId),+ ),+ )+ .limit(1);+if (task) {await publishEvent("task-relation.deleted", {...relation,- taskId: rel.sourceTaskId,- sourceTaskId: rel.sourceTaskId,- targetTaskId: rel.targetTaskId,+ taskId: relation.sourceTaskId,projectId: task.projectId,userId,});diff --git a/apps/api/src/task-relation/index.ts b/apps/api/src/task-relation/index.tsindex d90abcdd1..9700498ed 100644--- a/apps/api/src/task-relation/index.ts+++ b/apps/api/src/task-relation/index.ts@@ -185,7 +185,11 @@ const taskRelation = apiRouter<BaseVariables & { workspaceId: string }>()}).openapi(deleteTaskRelationRoute, async (c) =>c.json(- await deleteTaskRelation(c.req.valid("param").id, c.get("userId")),+ await deleteTaskRelation(+ c.req.valid("param").id,+ c.get("userId"),+ c.get("workspaceId"),+ ),200,),);diff --git a/apps/api/src/task/bounded-read.ts b/apps/api/src/task/bounded-read.tsnew file mode 100644index 000000000..dc58db995--- /dev/null+++ b/apps/api/src/task/bounded-read.ts@@ -0,0 +1,32 @@+import { sql } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../database";++export type TaskReadDatabase = Parameters<+ Parameters<typeof db.transaction>[0]+>[0];++export async function boundedTaskRead<T>(+ read: (tx: TaskReadDatabase) => Promise<T>,+ message = "Description request took too long; retry later",+) {+ try {+ return await db.transaction(+ async (tx) => {+ await tx.execute(sql`set local statement_timeout = '3s'`);+ return read(tx);+ },+ { isolationLevel: "repeatable read", accessMode: "read only" },+ );+ } catch (error) {+ const cause = error instanceof Error ? (error.cause ?? error) : error;+ if (+ cause &&+ typeof cause === "object" &&+ "code" in cause &&+ cause.code === "57014"+ )+ throw new HTTPException(503, { message });+ throw error;+ }+}diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.tsindex f25c41f88..e12b27342 100644--- a/apps/api/src/task/controllers/bulk-update-tasks.ts+++ b/apps/api/src/task/controllers/bulk-update-tasks.ts@@ -42,6 +42,8 @@ async function bulkUpdateTasks({.select({id: taskTable.id,title: taskTable.title,+ status: taskTable.status,+ priority: taskTable.priority,projectId: taskTable.projectId,userId: taskTable.userId,dueDate: taskTable.dueDate,@@ -110,9 +112,10 @@ async function bulkUpdateTasks({),});- const projectTaskIds = tasks- .filter((t) => t.projectId === projectId)- .map((t) => t.id);+ const projectTasks = tasks.filter(+ (task) => task.projectId === projectId,+ );+ const projectTaskIds = projectTasks.map((task) => task.id);const result = await db.update(taskTable)@@ -121,12 +124,15 @@ async function bulkUpdateTasks({updatedCount += result.rowCount ?? projectTaskIds.length;- for (const taskId of projectTaskIds) {+ for (const task of projectTasks) {await publishEvent("task.status_changed", {- taskId,+ taskId: task.id,projectId,userId,+ oldStatus: task.status,newStatus: value,+ title: task.title,+ assigneeId: task.userId,type: "status_changed",});}@@ -157,7 +163,9 @@ async function bulkUpdateTasks({taskId: task.id,projectId: task.projectId,userId,+ oldPriority: task.priority,newPriority: value,+ title: task.title,type: "priority_changed",});}diff --git a/apps/api/src/task/controllers/create-task.ts b/apps/api/src/task/controllers/create-task.tsindex 1bb287d41..7aaa66a2e 100644--- a/apps/api/src/task/controllers/create-task.ts+++ b/apps/api/src/task/controllers/create-task.ts@@ -1,4 +1,4 @@-import { and, eq, max } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import {@@ -18,6 +18,7 @@ import {assertValidTaskStatus,} from "../validate-task-fields";import { claimTaskNumber } from "./claim-task-numbers";+import { nextTaskPosition } from "./next-task-position";type CustomFieldInput = {fieldId: string;@@ -116,22 +117,14 @@ async function createTask({),});- const [maxPositionResult] = await db- .select({ maxPosition: max(taskTable.position) })- .from(taskTable)- .where(- and(- eq(taskTable.projectId, projectId),- column?.id- ? eq(taskTable.columnId, column.id)- : eq(taskTable.status, resolvedStatus),- ),- );-- const nextPosition = (maxPositionResult?.maxPosition ?? 0) + 1;-const createdTask = await db.transaction(async (tx) => {const taskNumber = await claimTaskNumber(projectId, tx);+ const nextPosition = await nextTaskPosition(+ tx,+ projectId,+ resolvedStatus,+ column?.id ?? null,+ );const [task] = await tx.insert(taskTable)diff --git a/apps/api/src/task/controllers/get-tasks.ts b/apps/api/src/task/controllers/get-tasks.tsindex 7f46bebf6..4a876fbb3 100644--- a/apps/api/src/task/controllers/get-tasks.ts+++ b/apps/api/src/task/controllers/get-tasks.ts@@ -3,6 +3,7 @@ import {asc,desc,eq,+ getTableColumns,gte,inArray,lte,@@ -10,7 +11,6 @@ import {sql,} from "drizzle-orm";import { HTTPException } from "hono/http-exception";-import db from "../../database";import {columnTable,externalLinkTable,@@ -20,12 +20,21 @@ import {userTable,} from "../../database/schema";-type GetTasksOptions = {+import { boundedTaskRead, type TaskReadDatabase } from "../bounded-read";+import {+ boardDescription,+ boardProjectDescription,+ descriptionDeferred,+ projectDescriptionDeferred,+} from "../description-pages";++export type GetTasksOptions = {assigneeId?: string;dueAfter?: string;dueBefore?: string;limit?: number;page?: number;+ relatedPage?: number;priority?: string;sortBy?:| "createdAt"@@ -68,10 +77,20 @@ function buildOrderBy(}}-async function getTasks(projectId: string, options: GetTasksOptions = {}) {- const project = await db.query.projectTable.findFirst({- where: eq(projectTable.id, projectId),- });+async function getTasksPage(+ db: TaskReadDatabase,+ projectId: string,+ options: GetTasksOptions,+) {+ const [project] = await db+ .select({+ ...getTableColumns(projectTable),+ description: boardProjectDescription,+ descriptionDeferred: projectDescriptionDeferred,+ })+ .from(projectTable)+ .where(eq(projectTable.id, projectId))+ .limit(1);if (!project) {throw new HTTPException(404, {@@ -102,11 +121,13 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {}const whereClause = and(...conditions);- const usePagination = options.page != null || options.limit != null;const page = options.page && options.page > 0 ? options.page : 1;const pageSize =options.limit && options.limit > 0 ? Math.min(options.limit, 100) : 50;const offset = (page - 1) * pageSize;+ const relatedPage = options.relatedPage ?? 1;+ const relatedPageSize = 100;+ const relatedOffset = (relatedPage - 1) * relatedPageSize;const orderByClause = buildOrderBy(options.sortBy ?? "position",@@ -124,7 +145,8 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {id: taskTable.id,title: taskTable.title,number: taskTable.number,- description: taskTable.description,+ description: boardDescription,+ descriptionDeferred,status: taskTable.status,priority: taskTable.priority,startDate: taskTable.startDate,@@ -144,11 +166,9 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {.leftJoin(userTable, eq(taskTable.userId, userTable.id)).leftJoin(projectTable, eq(taskTable.projectId, projectTable.id)).where(whereClause)- .orderBy(orderByClause);+ .orderBy(orderByClause, asc(taskTable.id));- const paginatedTasks = usePagination- ? await query.limit(pageSize).offset(offset)- : await query;+ const paginatedTasks = await query.limit(pageSize).offset(offset);const taskIds = paginatedTasks.map((task) => task.id);@@ -163,6 +183,9 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {}).from(labelTable).where(inArray(labelTable.taskId, taskIds))+ .orderBy(asc(labelTable.id))+ .limit(relatedPageSize)+ .offset(relatedOffset): [];const externalLinksData =@@ -171,6 +194,9 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {.select().from(externalLinkTable).where(inArray(externalLinkTable.taskId, taskIds))+ .orderBy(asc(externalLinkTable.id))+ .limit(relatedPageSize)+ .offset(relatedOffset): [];const taskLabelsMap = new Map<@@ -201,6 +227,8 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {url: string;title: string | null;metadata: Record<string, unknown> | null;+ createdAt: Date;+ updatedAt: Date;}>>();for (const externalLink of externalLinksData) {@@ -209,9 +237,7 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {}taskExternalLinksMap.get(externalLink.taskId)?.push({...externalLink,- metadata: externalLink.metadata- ? JSON.parse(externalLink.metadata)- : null,+ metadata: parseMetadata(externalLink.metadata),});}@@ -219,12 +245,62 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {.select().from(columnTable).where(eq(columnTable.projectId, projectId))- .orderBy(asc(columnTable.position));+ .orderBy(asc(columnTable.position), asc(columnTable.id))+ .limit(relatedPageSize)+ .offset(relatedOffset);++ // Keep every selected task representable even when its column falls on a+ // later metadata page. At most 100 distinct task statuses can be present.+ const missingStatuses = Array.from(+ new Set(paginatedTasks.map((task) => task.status)),+ ).filter(+ (status) =>+ status !== "planned" &&+ status !== "archived" &&+ !projectColumns.some((column) => column.slug === status),+ );+ if (missingStatuses.length) {+ const taskColumns = await db+ .selectDistinctOn([columnTable.slug])+ .from(columnTable)+ .where(+ and(+ eq(columnTable.projectId, projectId),+ inArray(columnTable.slug, missingStatuses),+ ),+ )+ .orderBy(+ asc(columnTable.slug),+ asc(columnTable.position),+ asc(columnTable.id),+ )+ .limit(100);+ projectColumns.push(...taskColumns);+ }+ const [columnCount] = await db+ .select({ count: sql<number>`count(*)` })+ .from(columnTable)+ .where(eq(columnTable.projectId, projectId));+ let labelCount = 0;+ let linkCount = 0;+ if (taskIds.length) {+ const [labels] = await db+ .select({ count: sql<number>`count(*)` })+ .from(labelTable)+ .where(inArray(labelTable.taskId, taskIds));+ const [links] = await db+ .select({ count: sql<number>`count(*)` })+ .from(externalLinkTable)+ .where(inArray(externalLinkTable.taskId, taskIds));+ labelCount = Number(labels?.count ?? 0);+ linkCount = Number(links?.count ?? 0);+ }const columns = projectColumns.map((column) => ({id: column.slug,slug: column.slug,name: column.name,+ position: column.position,icon: column.icon,isFinal: column.isFinal,tasks: paginatedTasks@@ -259,26 +335,49 @@ async function getTasks(projectId: string, options: GetTasksOptions = {}) {slug: project.slug,icon: project.icon,description: project.description,+ descriptionDeferred: project.descriptionDeferred,isPublic: project.isPublic,workspaceId: project.workspaceId,columns,archivedTasks,plannedTasks,},- pagination: usePagination- ? {- total,- page,- pageSize,- totalPages: Math.max(1, Math.ceil(total / pageSize)),- }- : {- total,- page: 1,- pageSize: total,- totalPages: 1,- },+ pagination: {+ total,+ page,+ pageSize,+ totalPages: Math.max(1, Math.ceil(total / pageSize)),+ relatedPage,+ relatedPageSize,+ relatedTotalPages: Math.max(+ 1,+ Math.ceil(+ Math.max(Number(columnCount?.count ?? 0), labelCount, linkCount) /+ relatedPageSize,+ ),+ ),+ },};}-export default getTasks;+function parseMetadata(raw: string | null): Record<string, unknown> | null {+ if (!raw) return null;+ try {+ const value: unknown = JSON.parse(raw);+ return value !== null && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+ } catch {+ return null;+ }+}++export default function getTasks(+ projectId: string,+ options: GetTasksOptions = {},+) {+ return boundedTaskRead(+ (db) => getTasksPage(db, projectId, options),+ "Task list request took too long; retry later",+ );+}diff --git a/apps/api/src/task/controllers/move-task.ts b/apps/api/src/task/controllers/move-task.tsindex 52ada6f10..f45ff1f27 100644--- a/apps/api/src/task/controllers/move-task.ts+++ b/apps/api/src/task/controllers/move-task.ts@@ -1,4 +1,4 @@-import { and, asc, eq, max } from "drizzle-orm";+import { and, asc, eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import {@@ -9,8 +9,7 @@ import {} from "../../database/schema";import { publishEvent } from "../../events";import { claimTaskNumber } from "./claim-task-numbers";--type DbOrTx = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];+import { nextTaskPosition } from "./next-task-position";function isSameProjectMove(sourceProjectId: string,@@ -59,26 +58,6 @@ async function resolveDestinationStatus(return requestedColumn ?? matchingCurrentColumn ?? firstColumn;}-async function getNextTaskPosition(- dbOrTx: DbOrTx,- projectId: string,- status: string,- columnId: string,-) {- const [maxPositionResult] = await dbOrTx- .select({ maxPosition: max(taskTable.position) })- .from(taskTable)- .where(- and(- eq(taskTable.projectId, projectId),- eq(taskTable.status, status),- eq(taskTable.columnId, columnId),- ),- );-- return (maxPositionResult?.maxPosition ?? 0) + 1;-}-async function moveTask({taskId,destinationProjectId,@@ -106,24 +85,24 @@ async function moveTask({});}- const [sourceProject, destinationProject] = await Promise.all([- db.query.projectTable.findFirst({- where: eq(projectTable.id, existingTask.projectId),- }),- db.query.projectTable.findFirst({- where: eq(projectTable.id, destinationProjectId),- }),- ]);-- if (!sourceProject || !destinationProject) {+ const sourceProject = await db.query.projectTable.findFirst({+ where: eq(projectTable.id, existingTask.projectId),+ });+ if (!sourceProject) {throw new HTTPException(404, {message: "Project not found",});}- if (sourceProject.workspaceId !== destinationProject.workspaceId) {- throw new HTTPException(400, {- message: "Tasks can only be moved within the same workspace",+ const destinationProject = await db.query.projectTable.findFirst({+ where: and(+ eq(projectTable.id, destinationProjectId),+ eq(projectTable.workspaceId, sourceProject.workspaceId),+ ),+ });+ if (!destinationProject) {+ throw new HTTPException(404, {+ message: "Project not found",});}@@ -134,15 +113,13 @@ async function moveTask({);const movedTask = await db.transaction(async (tx) => {- const [nextTaskNumber, nextPosition] = await Promise.all([- claimTaskNumber(destinationProjectId, tx),- getNextTaskPosition(- tx,- destinationProjectId,- resolvedColumn.slug,- resolvedColumn.id,- ),- ]);+ const nextTaskNumber = await claimTaskNumber(destinationProjectId, tx);+ const nextPosition = await nextTaskPosition(+ tx,+ destinationProjectId,+ resolvedColumn.slug,+ resolvedColumn.id,+ );const [updatedTask] = await tx.update(taskTable)diff --git a/apps/api/src/task/controllers/next-task-position.ts b/apps/api/src/task/controllers/next-task-position.tsnew file mode 100644index 000000000..7ad064a51--- /dev/null+++ b/apps/api/src/task/controllers/next-task-position.ts@@ -0,0 +1,59 @@+import { and, count, eq, max, sql } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import type db from "../../database";+import { taskTable } from "../../database/schema";++export const MAX_TASK_POSITION = 2_147_483_646;+type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];++export function assertTaskPosition(position: number) {+ if (+ !Number.isInteger(position) ||+ position < 0 ||+ position > MAX_TASK_POSITION+ ) {+ throw new HTTPException(400, {+ message: `Position must be an integer between 0 and ${MAX_TASK_POSITION}`,+ });+ }+}++// Call after claimTaskNumber has locked the destination project in this same+// transaction, so concurrent creates/moves cannot allocate the same position.+export async function nextTaskPosition(+ tx: Transaction,+ projectId: string,+ status: string,+ columnId: string | null,+) {+ const scope = and(+ eq(taskTable.projectId, projectId),+ columnId ? eq(taskTable.columnId, columnId) : eq(taskTable.status, status),+ );+ const [range] = await tx+ .select({ maximum: max(taskTable.position), total: count() })+ .from(taskTable)+ .where(scope);+ const maximum = Math.max(0, range?.maximum ?? 0);+ if (maximum < MAX_TASK_POSITION) return maximum + 1;++ // Repair legacy poisoned positions in SQL, preserving relative order. Merely+ // rejecting future bad values would leave existing projects unable to append.+ const total = range?.total ?? 0;+ if (total >= MAX_TASK_POSITION) {+ throw new HTTPException(409, {+ message: "Task column has reached its capacity",+ });+ }+ await tx.execute(sql`+ WITH ranked AS (+ SELECT ${taskTable.id} AS id,+ row_number() OVER (ORDER BY ${taskTable.position}, ${taskTable.createdAt}, ${taskTable.id}) AS position+ FROM ${taskTable}+ WHERE ${scope}+ )+ UPDATE ${taskTable} SET position = ranked.position::integer+ FROM ranked WHERE ${taskTable.id} = ranked.id+ `);+ return total + 1;+}diff --git a/apps/api/src/task/controllers/update-task.ts b/apps/api/src/task/controllers/update-task.tsindex c6b81cbb3..5920a2717 100644--- a/apps/api/src/task/controllers/update-task.ts+++ b/apps/api/src/task/controllers/update-task.ts@@ -1,4 +1,4 @@-import { and, eq } from "drizzle-orm";+import { and, eq, getTableColumns, sql } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import { columnTable, taskTable } from "../../database/schema";@@ -8,7 +8,9 @@ import {assertAssignableUser,getProjectWorkspaceId,} from "../../utils/assert-assignable-user";+import { boardDescription, descriptionDeferred } from "../description-pages";import { assertValidTaskStatus } from "../validate-task-fields";+import { assertTaskPosition } from "./next-task-position";async function updateTask(id: string,@@ -17,16 +19,19 @@ async function updateTask(startDate: Date | undefined,dueDate: Date | undefined,projectId: string,- description: string,+ description: string | undefined,priority: string,position: number,userId?: string,currentUserId?: string,) {+ assertTaskPosition(position);+const [existingTask] = await db.select({id: taskTable.id,- description: taskTable.description,+ description:+ description === undefined ? sql<null>`null` : taskTable.description,status: taskTable.status,projectId: taskTable.projectId,})@@ -79,7 +84,11 @@ async function updateTask(userId: normalizedUserId ?? null,}).where(eq(taskTable.id, id))- .returning();+ .returning({+ ...getTableColumns(taskTable),+ description: boardDescription,+ descriptionDeferred,+ });if (!updatedTask) {throw new HTTPException(500, {@@ -113,7 +122,7 @@ async function updateTask(userId: currentUserId,});- if (existingTask.description !== description) {+ if (description !== undefined && existingTask.description !== description) {deleteOrphanedAssets(existingTask.description, description, {taskId: id,}).catch(() => {});diff --git a/apps/api/src/task/description-pages.ts b/apps/api/src/task/description-pages.tsnew file mode 100644index 000000000..859528832--- /dev/null+++ b/apps/api/src/task/description-pages.ts@@ -0,0 +1,124 @@+import { and, asc, eq, gt, sql } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import { projectTable, taskTable } from "../database/schema";+import { boundedTaskRead } from "./bounded-read";++export const BOARD_DESCRIPTION_MAX_BYTES = 64 * 1024;+export const DESCRIPTION_CHUNK_CHARACTERS = 32 * 1024;+export const DESCRIPTION_MATCH_PAGE_SIZE = 100;+export const projectDescriptionDeferred = sql<boolean>`coalesce(octet_length(${projectTable.description}) > ${BOARD_DESCRIPTION_MAX_BYTES}, false)`;+export const boardProjectDescription = sql<+ string | null+>`case when ${projectDescriptionDeferred} then null else ${projectTable.description} end`;+export const descriptionDeferred = sql<boolean>`coalesce(octet_length(${taskTable.description}) > ${BOARD_DESCRIPTION_MAX_BYTES}, false)`;+export const boardDescription = sql<+ string | null+>`case when ${descriptionDeferred} then null else ${taskTable.description} end`;++export async function getDescriptionPage(+ taskId: string,+ options: { offset: number; version?: string; publicProjectId?: string },+) {+ return boundedTaskRead(async (tx) => {+ const conditions = [eq(taskTable.id, taskId)];+ if (options.publicProjectId)+ conditions.push(+ eq(taskTable.projectId, options.publicProjectId),+ eq(projectTable.isPublic, true),+ );+ if (options.version)+ conditions.push(sql`${taskTable}.xmin::text = ${options.version}`);+ const [row] = await tx+ .select({+ content: sql<string>`coalesce(substring(${taskTable.description} from ${options.offset + 1}::integer for ${DESCRIPTION_CHUNK_CHARACTERS + 1}::integer), '')`,+ version: sql<string>`${taskTable}.xmin::text`,+ })+ .from(taskTable)+ .innerJoin(projectTable, eq(projectTable.id, taskTable.projectId))+ .where(and(...conditions))+ .limit(1);+ if (!row)+ throw new HTTPException(options.version ? 409 : 404, {+ message:+ "Description changed or is unavailable; refresh before loading it again",+ });+ // PostgreSQL offsets count Unicode characters, not JavaScript UTF-16 units.+ const characters = Array.from(row.content);+ return {+ content: characters.slice(0, DESCRIPTION_CHUNK_CHARACTERS).join(""),+ version: row.version,+ nextOffset:+ characters.length > DESCRIPTION_CHUNK_CHARACTERS+ ? options.offset + DESCRIPTION_CHUNK_CHARACTERS+ : null,+ };+ });+}++export async function getDeferredDescriptionMatches(+ projectId: string,+ query: string,+ after?: string,+) {+ return boundedTaskRead(async (tx) => {+ const rows = await tx+ .select({ id: taskTable.id })+ .from(taskTable)+ .where(+ and(+ eq(taskTable.projectId, projectId),+ descriptionDeferred,+ sql`strpos(lower(${taskTable.description}), lower(${query})) > 0`,+ after ? gt(taskTable.id, after) : undefined,+ ),+ )+ .orderBy(asc(taskTable.id))+ .limit(DESCRIPTION_MATCH_PAGE_SIZE + 1);+ const matches = rows.slice(0, DESCRIPTION_MATCH_PAGE_SIZE);+ return {+ ids: matches.map((row) => row.id),+ nextCursor:+ rows.length > DESCRIPTION_MATCH_PAGE_SIZE+ ? (matches.at(-1)?.id ?? null)+ : null,+ };+ });+}++export async function getPublicProjectDescriptionPage(+ projectId: string,+ options: { offset: number; version?: string },+) {+ return boundedTaskRead(async (tx) => {+ const [row] = await tx+ .select({+ content: sql<string>`coalesce(substring(${projectTable.description} from ${options.offset + 1}::integer for ${DESCRIPTION_CHUNK_CHARACTERS + 1}::integer), '')`,+ version: sql<string>`${projectTable}.xmin::text`,+ })+ .from(projectTable)+ .where(+ and(+ eq(projectTable.id, projectId),+ eq(projectTable.isPublic, true),+ options.version+ ? sql`${projectTable}.xmin::text = ${options.version}`+ : undefined,+ ),+ )+ .limit(1);+ if (!row)+ throw new HTTPException(options.version ? 409 : 404, {+ message:+ "Description changed or is unavailable; refresh before loading it again",+ });+ const characters = Array.from(row.content);+ return {+ content: characters.slice(0, DESCRIPTION_CHUNK_CHARACTERS).join(""),+ version: row.version,+ nextOffset:+ characters.length > DESCRIPTION_CHUNK_CHARACTERS+ ? options.offset + DESCRIPTION_CHUNK_CHARACTERS+ : null,+ };+ });+}diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.tsindex 919d49e35..29f89ec08 100644--- a/apps/api/src/task/index.ts+++ b/apps/api/src/task/index.ts@@ -18,8 +18,10 @@ import {import {assertTaskImageKeyMatchesContext,createTaskImageUploadUrl,+ InvalidUploadedAssetError,isImageContentType,validateTaskAssetUploadInput,+ verifyTaskAssetUpload,} from "../storage/s3";import { normalizeApiServerUrl } from "../utils/openapi-spec";import { requireWorkspacePermission } from "../utils/require-workspace-permission";@@ -48,9 +50,15 @@ import updateTaskDueDate from "./controllers/update-task-due-date";import updateTaskPriority from "./controllers/update-task-priority";import updateTaskStatus from "./controllers/update-task-status";import updateTaskTitle from "./controllers/update-task-title";+import {+ getDeferredDescriptionMatches,+ getDescriptionPage,+} from "./description-pages";import {boardSchema,bulkResultSchema,+ descriptionMatchesSchema,+ descriptionPageSchema,finalizedAssetSchema,imageUploadSchema,moveTaskResultSchema,@@ -62,6 +70,8 @@ import {import {bulkUpdateBody,createTaskBody,+ descriptionMatchesQuery,+ descriptionPageQuery,finalizeImageUploadBody,imageUploadBody,importTasksBody,@@ -85,11 +95,12 @@ const listTasksRoute = createRoute({tags: ["Tasks"],summary: "List tasks",description:- "Get a project's board: its columns, each with the tasks in it, plus the archived and planned buckets. Filter and paginate with the query parameters.",+ "Get a project's board: its columns, each with the tasks in it, plus the archived and planned buckets. Responses always contain at most 100 tasks (50 by default). Continue through pagination.totalPages for the whole board, and for each task page follow relatedPage through pagination.relatedTotalPages for all labels, links and column metadata. Filters and sorting apply before pagination. Descriptions larger than 64 KiB are omitted with descriptionDeferred=true; read the task detail or description pages for full text.",middleware: [workspaceAccess.fromProject("projectId")] as const,request: { params: projectIdParam, query: listTasksQuery },responses: {200: jsonResponse("The project board", boardSchema),+ 503: errorResponse("Task list request timed out"),400: errorResponse("Unknown project, or its workspace could not be determined",),@@ -543,7 +554,57 @@ const updateTaskDescriptionRoute = createRoute({},});+const descriptionPageRoute = createRoute({+ method: "get",+ operationId: "getTaskDescriptionPage",+ path: "/{id}/description",+ tags: ["Tasks"],+ summary: "Read a description page",+ middleware: [workspaceAccess.fromTaskId("id")] as const,+ request: { params: taskParam, query: descriptionPageQuery },+ responses: {+ 200: jsonResponse("Description page", descriptionPageSchema),+ 400: errorResponse("Invalid offset or version"),+ 403: errorResponse("No workspace access"),+ 404: errorResponse("Task not found"),+ 409: errorResponse("Description changed; reload from offset zero"),+ 503: errorResponse("Description request timed out"),+ },+});+const descriptionMatchesRoute = createRoute({+ method: "get",+ operationId: "findDeferredTaskDescriptions",+ path: "/description-matches/{projectId}",+ tags: ["Tasks"],+ summary: "Search descriptions omitted from task lists",+ middleware: [workspaceAccess.fromProject("projectId")] as const,+ request: { params: projectIdParam, query: descriptionMatchesQuery },+ responses: {+ 200: jsonResponse("Matching task IDs", descriptionMatchesSchema),+ 400: errorResponse("Invalid search query or cursor"),+ 403: errorResponse("No workspace access"),+ 503: errorResponse("Description search timed out"),+ },+});+const task = apiRouter<BaseVariables & { workspaceId: string }>()+ .openapi(descriptionPageRoute, async (c) =>+ c.json(+ await getDescriptionPage(c.req.valid("param").id, c.req.valid("query")),+ 200,+ ),+ )+ .openapi(descriptionMatchesRoute, async (c) => {+ const { query, after } = c.req.valid("query");+ return c.json(+ await getDeferredDescriptionMatches(+ c.req.valid("param").projectId,+ query,+ after,+ ),+ 200,+ );+ }).openapi(listTasksRoute, async (c) => {const { projectId } = c.req.valid("param");const filters = c.req.valid("query") || {};@@ -797,6 +858,7 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()surface,filename,contentType,+ size,});return c.json(upload, 200);@@ -858,6 +920,24 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()});}+ let uploaded: Awaited<ReturnType<typeof verifyTaskAssetUpload>>;+ try {+ uploaded = await verifyTaskAssetUpload(normalizedKey, {+ size,+ contentType,+ });+ } catch (error) {+ throw new HTTPException(+ error instanceof InvalidUploadedAssetError ? 400 : 503,+ {+ message:+ error instanceof InvalidUploadedAssetError+ ? error.message+ : "Unable to verify uploaded object.",+ },+ );+ }+const [existingAsset] = await db.select({ id: assetTable.id }).from(assetTable)@@ -872,9 +952,11 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()projectId: taskContext.projectId,taskId: taskContext.taskId,filename,- mimeType: contentType,- size,- kind: isImageContentType(contentType) ? "image" : "attachment",+ mimeType: uploaded.contentType,+ size: uploaded.size,+ kind: isImageContentType(uploaded.contentType)+ ? "image"+ : "attachment",surface,createdBy: userId || null,})@@ -890,9 +972,11 @@ const task = apiRouter<BaseVariables & { workspaceId: string }>()taskId: taskContext.taskId,objectKey: normalizedKey,filename,- mimeType: contentType,- size,- kind: isImageContentType(contentType) ? "image" : "attachment",+ mimeType: uploaded.contentType,+ size: uploaded.size,+ kind: isImageContentType(uploaded.contentType)+ ? "image"+ : "attachment",surface,createdBy: userId || null,})diff --git a/apps/api/src/task/response.ts b/apps/api/src/task/response.tsindex dd5f7f56b..03f8b1d48 100644--- a/apps/api/src/task/response.ts+++ b/apps/api/src/task/response.ts@@ -18,6 +18,10 @@ export const taskSchema = z.openapi({ description: "The assignee, if any." }),title: z.string(),description: z.string().nullable(),+ descriptionDeferred: z.boolean().optional().openapi({+ description:+ "True when the list omits a large description; load the task detail or description pages to read it. Do not replace stored text with this null summary.",+ }),status: z.string().openapi({description: "The slug of the column the task sits in.",}),@@ -66,6 +70,10 @@ export const boardTaskSchema = ztitle: z.string(),number: z.number().nullable(),description: z.string().nullable(),+ descriptionDeferred: z.boolean().optional().openapi({+ description:+ "True when the list omits a large description; load the task detail or description pages to read it. Do not replace stored text with this null summary.",+ }),status: z.string(),priority: z.string().openapi({ description: priorityDescription }),startDate: nullableResponseTimestamp,@@ -89,6 +97,7 @@ export const boardColumnSchema = zname: z.string(),icon: z.string().nullable(),isFinal: z.boolean(),+ position: z.number().optional(),tasks: z.array(boardTaskSchema),}).openapi("BoardColumn");@@ -102,6 +111,10 @@ export const boardSchema = zslug: z.string(),icon: z.string().nullable(),description: z.string().nullable(),+ descriptionDeferred: z.boolean().optional().openapi({+ description:+ "True when a project description above 64 KiB is omitted; use project detail or public project description pages for full text.",+ }),isPublic: z.boolean().nullable(),workspaceId: z.string(),columns: z.array(boardColumnSchema),@@ -115,10 +128,13 @@ export const boardSchema = zpage: z.number(),pageSize: z.number(),totalPages: z.number(),+ relatedPage: z.number(),+ relatedPageSize: z.number(),+ relatedTotalPages: z.number(),}).openapi({description:- "When no page/limit is given, everything is returned on a single page.",+ "Always paginated: 50 tasks by default, at most 100 per page. Continue through totalPages to retrieve all tasks. For each task page, follow relatedPage through relatedTotalPages to retrieve all labels, external links and columns (100 related rows per kind per request, plus up to 100 columns needed to represent the tasks).",}).openapi("BoardPagination"),})@@ -209,3 +225,14 @@ export const finalizedAssetSchema = z}),}).openapi("TaskImageAsset");++export const descriptionPageSchema = z+ .object({+ content: z.string(),+ version: z.string(),+ nextOffset: z.number().nullable(),+ })+ .openapi("TaskDescriptionPage");+export const descriptionMatchesSchema = z+ .object({ ids: z.array(z.string()), nextCursor: z.string().nullable() })+ .openapi("TaskDescriptionMatches");diff --git a/apps/api/src/task/schema.ts b/apps/api/src/task/schema.tsindex 88ffc9f5b..5d290e58a 100644--- a/apps/api/src/task/schema.ts+++ b/apps/api/src/task/schema.ts@@ -1,4 +1,5 @@import { z } from "../openapi";+import { MAX_TASK_POSITION } from "./controllers/next-task-position";import { VALID_PRIORITIES } from "./validate-task-fields";const pagingNumber = (min: number, max: number) =>@@ -21,7 +22,8 @@ export const listTasksQuery = z.object({assigneeId: z.string().optional(),// Number("abc") is NaN, which used to reach the limit/offset clause unchecked.page: pagingNumber(1, 1_000_000).optional(),- limit: pagingNumber(1, 200).optional(),+ relatedPage: pagingNumber(1, 1_000_000).optional(),+ limit: pagingNumber(1, 100).optional(),sortBy: z.enum(["createdAt", "priority", "dueDate", "position", "title", "number"]).optional(),@@ -62,13 +64,16 @@ export const createTaskBody = z.object({export const updateTaskBody = z.object({title: z.string(),- description: z.string(),+ description: z.string().optional().openapi({+ description:+ "Omit to preserve the existing description when updating a list summary.",+ }),startDate: z.string().optional(),dueDate: z.string().optional(),priority,status: z.string(),projectId: z.string(),- position: z.number(),+ position: z.number().int().min(0).max(MAX_TASK_POSITION),userId: z.string().optional(),});@@ -122,3 +127,15 @@ export const finalizeImageUploadBody = z.object({size: z.number(),surface,});++export const descriptionPageQuery = z.object({+ offset: pagingNumber(0, 2_000_000_000).default(0),+ version: z+ .string()+ .regex(/^[0-9]{1,10}$/)+ .optional(),+});+export const descriptionMatchesQuery = z.object({+ query: z.string().trim().min(1).max(256),+ after: z.string().min(1).max(128).optional(),+});diff --git a/apps/api/src/task/validate-assignee.ts b/apps/api/src/task/validate-assignee.tsnew file mode 100644index 000000000..5e6d6e7e2--- /dev/null+++ b/apps/api/src/task/validate-assignee.ts@@ -0,0 +1,26 @@+import { and, eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../database";+import { projectTable, workspaceUserTable } from "../database/schema";++export async function assertProjectAssignee(projectId: string, userId: string) {+ const [member] = await db+ .select({ id: workspaceUserTable.id })+ .from(workspaceUserTable)+ .innerJoin(+ projectTable,+ eq(projectTable.workspaceId, workspaceUserTable.workspaceId),+ )+ .where(+ and(+ eq(projectTable.id, projectId),+ eq(workspaceUserTable.userId, userId),+ ),+ )+ .limit(1);+ if (!member) {+ throw new HTTPException(400, {+ message: "Assignee must be a current workspace member",+ });+ }+}diff --git a/apps/api/src/user/avatar.ts b/apps/api/src/user/avatar.tsindex 7a2eed713..cf3c54696 100644--- a/apps/api/src/user/avatar.ts+++ b/apps/api/src/user/avatar.ts@@ -1,4 +1,14 @@export const MAX_AVATAR_BYTES = 512 * 1024;+export const MAX_AVATAR_BASE64_CHARS = Math.ceil(MAX_AVATAR_BYTES / 3) * 4;+// Permit the data URL prefix and modest whitespace without unbounded cleanup.+export const MAX_AVATAR_INPUT_CHARS = MAX_AVATAR_BASE64_CHARS + 1024;+export const MAX_AVATAR_REQUEST_BYTES = 768 * 1024;++function avatarSizeError() {+ return new Error(+ `Image exceeds the maximum avatar size of ${MAX_AVATAR_BYTES / 1024}KB.`,+ );+}const AVATAR_MIME_TYPES = ["image/png", "image/jpeg", "image/webp"] as const;@@ -49,6 +59,7 @@ export function decodeAvatarUpload(input: {contentType: string;data: string;}): { mimeType: AvatarMimeType; bytes: Buffer } {+ if (input.data.length > MAX_AVATAR_INPUT_CHARS) throw avatarSizeError();const mimeType = normalizeAvatarMimeType(input.contentType);if (!isAvatarMimeType(mimeType)) {@@ -59,10 +70,15 @@ export function decodeAvatarUpload(input: {const payload = stripDataUrlPrefix(input.data).replace(/\s+/g, "");+ if (payload.length > MAX_AVATAR_BASE64_CHARS) throw avatarSizeError();+if (!payload || !BASE64_PATTERN.test(payload) || payload.length % 4 !== 0) {throw new Error("Image data must be base64 encoded.");}+ const padding = payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0;+ if ((payload.length / 4) * 3 - padding > MAX_AVATAR_BYTES)+ throw avatarSizeError();const bytes = Buffer.from(payload, "base64");if (bytes.length === 0) {diff --git a/apps/api/src/user/index.ts b/apps/api/src/user/index.tsindex 0b8e8ef55..29df3d077 100644--- a/apps/api/src/user/index.ts+++ b/apps/api/src/user/index.ts@@ -5,7 +5,8 @@ import {errorResponse,jsonResponse,} from "../openapi";-import { MAX_AVATAR_BYTES } from "./avatar";+import { boundedRequestBody } from "../utils/bounded-request-body";+import { MAX_AVATAR_BYTES, MAX_AVATAR_REQUEST_BYTES } from "./avatar";import deleteAvatar from "./controllers/delete-avatar";import saveAvatar from "./controllers/save-avatar";import { avatarDeletedSchema, avatarSchema } from "./response";@@ -20,6 +21,7 @@ const uploadAvatarRoute = createRoute({description: `Store a base64 encoded avatar (PNG, JPEG, or WebP, up to ${Math.floor(MAX_AVATAR_BYTES / 1024,)}KB) for the current user and return its public URL. Replaces any existing avatar.`,+ middleware: [boundedRequestBody(MAX_AVATAR_REQUEST_BYTES)] as const,request: {body: {required: true,@@ -28,6 +30,8 @@ const uploadAvatarRoute = createRoute({},responses: {200: jsonResponse("Avatar stored", avatarSchema),+ 408: errorResponse("Request body timed out"),+ 413: errorResponse("Request body exceeds the upload limit"),400: errorResponse("Unsupported content type, malformed base64, or too large",),diff --git a/apps/api/src/user/schema.ts b/apps/api/src/user/schema.tsindex 96bfed60c..9057a6d02 100644--- a/apps/api/src/user/schema.ts+++ b/apps/api/src/user/schema.ts@@ -1,9 +1,13 @@import { z } from "../openapi";+import { MAX_AVATAR_INPUT_CHARS } from "./avatar";export const uploadAvatarBody = z.object({- contentType: z.string().openapi({+ contentType: z.string().max(64).openapi({description: "One of image/png, image/jpeg, or image/webp.",example: "image/png",}),- data: z.string().openapi({ description: "Base64 encoded image bytes." }),+ data: z+ .string()+ .max(MAX_AVATAR_INPUT_CHARS)+ .openapi({ description: "Base64 encoded image bytes." }),});diff --git a/apps/api/src/utils/authorize-asset-access.ts b/apps/api/src/utils/authorize-asset-access.tsindex a61d60bd7..3686d7de4 100644--- a/apps/api/src/utils/authorize-asset-access.ts+++ b/apps/api/src/utils/authorize-asset-access.ts@@ -5,22 +5,19 @@ import { validateWorkspaceAccess } from "./validate-workspace-access";type AssetAccessTarget = {workspaceId: string;isPublic: boolean | null;+ surface: string;};-/**- * Authorizes a request for a stored asset.- *- * Assets that belong to a public project are readable by anyone, so the- * credential check must be skipped entirely for them:- * `resolveAssetBearerOrCookie` throws a 401 for anonymous callers rather than- * returning an empty user, so calling it first makes the public case- * unreachable.- */+/** Only description assets belong to the public project representation. */+export function isPublicAsset(asset: AssetAccessTarget): boolean {+ return asset.isPublic === true && asset.surface === "description";+}+export async function authorizeAssetAccess(c: Context,asset: AssetAccessTarget,): Promise<void> {- if (asset.isPublic) {+ if (isPublicAsset(asset)) {return;}diff --git a/apps/api/src/utils/bounded-github-fetch.ts b/apps/api/src/utils/bounded-github-fetch.tsnew file mode 100644index 000000000..9e1bd35f4--- /dev/null+++ b/apps/api/src/utils/bounded-github-fetch.ts@@ -0,0 +1,63 @@+// Import pages have bounded counts, but cap the decoded HTTP body as well.+export const MAX_GITHUB_IMPORT_RESPONSE_BYTES = 16 * 1024 * 1024;+export const GITHUB_IMPORT_REQUEST_TIMEOUT_MS = 10_000;++export const boundedGithubFetch: typeof fetch = async (input, init) => {+ const controller = new AbortController();+ let timer: ReturnType<typeof setTimeout> | undefined;+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;+ const deadline = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ controller.abort();+ reject(new Error("GitHub import request timed out"));+ }, GITHUB_IMPORT_REQUEST_TIMEOUT_MS);+ });+ try {+ return await Promise.race([+ deadline,+ (async () => {+ const response = await fetch(input, {+ ...init,+ redirect: "error",+ signal: init?.signal+ ? AbortSignal.any([init.signal, controller.signal])+ : controller.signal,+ });+ if (controller.signal.aborted) {+ void response.body?.cancel().catch(() => {});+ throw new Error("GitHub import request timed out");+ }+ reader = response.body?.getReader();+ // Fixed storage also bounds overhead when a stream uses tiny chunks.+ const bytes = new Uint8Array(MAX_GITHUB_IMPORT_RESPONSE_BYTES);+ let size = 0;+ if (reader) {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > MAX_GITHUB_IMPORT_RESPONSE_BYTES)+ throw new Error("GitHub import response is too large");+ bytes.set(value, size - value.byteLength);+ }+ }+ return new Response(+ response.status === 204 || response.status === 304+ ? null+ : bytes.subarray(0, size),+ {+ status: response.status,+ statusText: response.statusText,+ headers: response.headers,+ },+ );+ })(),+ ]);+ } finally {+ clearTimeout(timer);+ controller.abort();+ if (reader) {+ void reader.cancel().catch(() => {});+ }+ }+};diff --git a/apps/api/src/utils/bounded-request-body.ts b/apps/api/src/utils/bounded-request-body.tsnew file mode 100644index 000000000..d10856ffd--- /dev/null+++ b/apps/api/src/utils/bounded-request-body.ts@@ -0,0 +1,61 @@+import type { MiddlewareHandler } from "hono";+import { HTTPException } from "hono/http-exception";++/** Bound actual bytes before any JSON/form parser, even for misleading headers. */+export function boundedRequestBody(+ maxBytes: number,+ timeoutMs = 5_000,+): MiddlewareHandler {+ return async (c, next) => {+ const body = c.req.raw.body;+ if (!body) return next();+ const declared = Number(c.req.header("content-length"));+ if (declared > maxBytes) {+ void body.cancel().catch(() => {});+ throw new HTTPException(413, { message: "Request body is too large" });+ }+ // Always count actual bytes, including chunked bodies and misleading length+ // headers. Do not parse JSON/form data until this bounded read completes.+ const reader = body.getReader();+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ const read = async () => {+ // A fixed buffer also bounds memory for adversarial one-byte chunks.+ const bytes = new Uint8Array(maxBytes);+ let size = 0;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ if (size + value.byteLength > maxBytes) {+ void reader.cancel().catch(() => {});+ throw new HTTPException(413, {+ message: "Request body is too large",+ });+ }+ bytes.set(value, size);+ size += value.byteLength;+ }+ return bytes.subarray(0, size);+ };+ const bytes = await Promise.race([+ read(),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(() => {+ reject(+ new HTTPException(408, { message: "Request body timed out" }),+ );+ void reader.cancel().catch(() => {});+ }, timeoutMs);+ }),+ ]);+ const headers = new Headers(c.req.raw.headers);+ headers.set("content-length", String(bytes.byteLength));+ headers.delete("transfer-encoding");+ c.req.raw = new Request(c.req.raw, { headers, body: bytes });+ } finally {+ clearTimeout(timeout);+ reader.releaseLock();+ }+ return next();+ };+}diff --git a/apps/api/src/utils/check-registration-allowed.ts b/apps/api/src/utils/check-registration-allowed.tsindex b40aef210..50ce13b0c 100644--- a/apps/api/src/utils/check-registration-allowed.ts+++ b/apps/api/src/utils/check-registration-allowed.ts@@ -19,7 +19,7 @@ type RegistrationCheckResult = {export async function checkRegistrationAllowed(email?: string,invitationId?: string,- options?: { allowInvitationByEmail?: boolean },+ options?: { allowInvitationByEmail?: boolean; emailVerified?: boolean },): Promise<RegistrationCheckResult> {const isRegistrationDisabled = process.env.DISABLE_REGISTRATION === "true";@@ -30,7 +30,9 @@ export async function checkRegistrationAllowed(};}- const canMatchByEmail = Boolean(options?.allowInvitationByEmail && email);+ const canMatchByEmail = Boolean(+ options?.allowInvitationByEmail && options.emailVerified === true && email,+ );if (!invitationId && !canMatchByEmail) {return {diff --git a/apps/api/src/utils/client-ip.ts b/apps/api/src/utils/client-ip.tsnew file mode 100644index 000000000..0bd5a1a8e--- /dev/null+++ b/apps/api/src/utils/client-ip.ts@@ -0,0 +1,75 @@+import { BlockList, isIP } from "node:net";+import { getConnInfo } from "@hono/node-server/conninfo";+import type { MiddlewareHandler } from "hono";++const CLIENT_IP_HEADER = "x-kaneo-client-ip";+const DEFAULT_TRUSTED_PROXIES = "127.0.0.0/8,::1/128";++export function createClientIpResolver(config = process.env.TRUSTED_PROXIES) {+ const trusted = new BlockList();+ const raw = config?.trim() || DEFAULT_TRUSTED_PROXIES;+ for (const entry of raw === "none" ? [] : raw.split(",")) {+ const parts = entry.trim().split("/");+ const [address = "", prefix] = parts;+ const family = isIP(address);+ const bits = family === 4 ? 32 : 128;+ if (+ !family ||+ parts.length > 2 ||+ (prefix !== undefined && (!/^\d+$/.test(prefix) || Number(prefix) > bits))+ ) {+ throw new Error(+ "TRUSTED_PROXIES must contain valid IP addresses or CIDR ranges, or 'none'",+ );+ }+ if (prefix === undefined)+ trusted.addAddress(address, family === 4 ? "ipv4" : "ipv6");+ else+ trusted.addSubnet(+ address,+ Number(prefix),+ family === 4 ? "ipv4" : "ipv6",+ );+ }+ const isTrusted = (address: string) =>+ trusted.check(address, isIP(address) === 4 ? "ipv4" : "ipv6");++ return (+ peer: string | undefined,+ forwarded: string | undefined,+ ): string | null => {+ if (!peer || !isIP(peer)) return null;+ if (!isTrusted(peer) || !forwarded || forwarded.length > 8192) return peer;+ const hops = forwarded.split(",");+ if (hops.length > 64) return peer;+ let current = peer;+ for (let i = hops.length - 1; i >= 0; i--) {+ if (!isTrusted(current)) break;+ const candidate = hops[i]?.trim() ?? "";+ // A malformed chain has no reliable client identity; keep the transport peer.+ if (!isIP(candidate)) return peer;+ current = candidate;+ }+ return current;+ };+}++export function clientIpMiddleware(config?: string): MiddlewareHandler {+ const resolve = createClientIpResolver(config);+ return async (c, next) => {+ let peer: string | undefined;+ // app.request() and non-Node adapters have no socket. Do not trust headers+ // in that case: Better Auth uses its shared fallback rate-limit bucket.+ try {+ peer = getConnInfo(c).remote.address;+ } catch {+ /* no transport peer */+ }+ const ip = resolve(peer, c.req.header("x-forwarded-for"));+ const headers = new Headers(c.req.raw.headers);+ headers.delete(CLIENT_IP_HEADER);+ if (ip) headers.set(CLIENT_IP_HEADER, ip);+ c.req.raw = new Request(c.req.raw, { headers });+ await next();+ };+}diff --git a/apps/api/src/utils/get-settings.ts b/apps/api/src/utils/get-settings.tsindex fe13b68ff..0d01ff15d 100644--- a/apps/api/src/utils/get-settings.ts+++ b/apps/api/src/utils/get-settings.ts@@ -24,7 +24,12 @@ function getSettings() {hasCustomOAuth:Boolean(process.env.CUSTOM_OAUTH_CLIENT_ID) &&Boolean(process.env.CUSTOM_OAUTH_CLIENT_SECRET),- hasGuestAccess: process.env.DISABLE_GUEST_ACCESS !== "true",+ hasGuestAccess: [+ "DISABLE_GUEST_ACCESS",+ "DISABLE_REGISTRATION",+ "DISABLE_PASSWORD_REGISTRATION",+ "DISABLE_LOGIN_FORM",+ ].every((key) => process.env[key] !== "true"),disableLoginForm: process.env.DISABLE_LOGIN_FORM === "true",customOAuthAutoLogin: process.env.CUSTOM_OAUTH_AUTO_LOGIN === "true",customOAuthLogoutUrl: process.env.CUSTOM_OAUTH_LOGOUT_URL || null,diff --git a/apps/api/src/utils/instance-bootstrap.ts b/apps/api/src/utils/instance-bootstrap.tsnew file mode 100644index 000000000..512f5cfcc--- /dev/null+++ b/apps/api/src/utils/instance-bootstrap.ts@@ -0,0 +1,42 @@+import { and, asc, count, eq, sql } from "drizzle-orm";+import db, { schema } from "../database";++export const nonAnonymousUser = sql`${schema.userTable.isAnonymous} IS NOT TRUE`;++export async function hasRegisteredUsers(): Promise<boolean> {+ const [row] = await db+ .select({ value: count() })+ .from(schema.userTable)+ .where(nonAnonymousUser);+ return (row?.value ?? 0) > 0;+}++export async function promoteInitialAdministrator(+ userId: string,+): Promise<void> {+ await db.transaction(async (tx) => {+ await tx.execute(sql`SELECT pg_advisory_xact_lock(2026)`);+ const [admin] = await tx+ .select({ id: schema.userTable.id })+ .from(schema.userTable)+ .where(and(nonAnonymousUser, eq(schema.userTable.role, "admin")))+ .limit(1);+ if (admin) return;++ // Elect the earliest registered user, not the only row: concurrent first+ // signups may both be inserted before either after-hook gets this lock.+ // Existing non-admin accounts remain ineligible for promotion by a later+ // signup. Anonymous rows never consume the initial-admin slot.+ const [first] = await tx+ .select({ id: schema.userTable.id })+ .from(schema.userTable)+ .where(nonAnonymousUser)+ .orderBy(asc(schema.userTable.createdAt), asc(schema.userTable.id))+ .limit(1);+ if (first?.id !== userId) return;+ await tx+ .update(schema.userTable)+ .set({ role: "admin" })+ .where(eq(schema.userTable.id, userId));+ });+}diff --git a/apps/api/src/utils/outbound-request.ts b/apps/api/src/utils/outbound-request.tsnew file mode 100644index 000000000..4cbd55349--- /dev/null+++ b/apps/api/src/utils/outbound-request.ts@@ -0,0 +1,107 @@+import { assertPublicDestination } from "./assert-public-destination";+import { withoutOutboundTelemetry } from "./sensitive-outbound";++type Failure = "timeout" | "http" | "network" | "response" | "destination";++// Never attach the original error/cause: it can include credential-bearing+// URLs, authorization headers or untrusted response bodies.+export class OutboundRequestError extends Error {+ constructor(+ readonly reason: Failure,+ readonly status?: number,+ ) {+ super(+ `Outbound request failed: ${reason}${status ? ` (HTTP ${status})` : ""}`,+ );+ }+}++export function safeOutboundError(error: unknown): string {+ return error instanceof OutboundRequestError+ ? error.message+ : "Outbound request failed";+}++async function readSmallJson(response: Response): Promise<unknown> {+ const reader = response.body?.getReader();+ if (!reader) throw new OutboundRequestError("response");+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > 16_384) throw new OutboundRequestError("response");+ chunks.push(value);+ }+ const bytes = new Uint8Array(size);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }+ try {+ return JSON.parse(new TextDecoder().decode(bytes));+ } catch {+ throw new OutboundRequestError("response");+ }+ } finally {+ // Cancellation need not wait for the remote peer to close its stream.+ void reader.cancel().catch(() => {});+ reader.releaseLock();+ }+}++export async function sendOutboundRequest(+ url: string,+ init: Pick<RequestInit, "headers" | "body">,+ options: {+ readJson?: boolean;+ publicDestination?: boolean;+ timeoutMs?: number;+ } = {},+): Promise<unknown> {+ const controller = new AbortController();+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ controller.abort();+ reject(new OutboundRequestError("timeout"));+ }, options.timeoutMs ?? 10_000);+ });+ const request = async () => {+ if (options.publicDestination) {+ try {+ await assertPublicDestination(url, "Notification");+ } catch {+ throw new OutboundRequestError("destination");+ }+ }+ // DNS validation may finish after the deadline. Never start a late request.+ controller.signal.throwIfAborted();+ const response = await withoutOutboundTelemetry(() =>+ fetch(url, {+ ...init,+ method: "POST",+ redirect: "error",+ signal: controller.signal,+ }),+ );+ if (!response.ok || !options.readJson) {+ void response.body?.cancel().catch(() => {});+ if (!response.ok) throw new OutboundRequestError("http", response.status);+ return undefined;+ }+ return readSmallJson(response);+ };+ try {+ return await Promise.race([request(), deadline]);+ } catch (error) {+ if (controller.signal.aborted) throw new OutboundRequestError("timeout");+ if (error instanceof OutboundRequestError) throw error;+ throw new OutboundRequestError("network");+ } finally {+ clearTimeout(timer);+ }+}diff --git a/apps/api/src/utils/registration-policy.ts b/apps/api/src/utils/registration-policy.tsnew file mode 100644index 000000000..6da121f13--- /dev/null+++ b/apps/api/src/utils/registration-policy.ts@@ -0,0 +1,68 @@+import { APIError } from "better-auth/api";+import { checkRegistrationAllowed } from "./check-registration-allowed";+import { hasRegisteredUsers } from "./instance-bootstrap";++export function normalizeInvitationId(value: unknown): string | undefined {+ if (typeof value !== "string") return undefined;+ const normalized = value.trim();+ return /^[a-z0-9_-]{1,128}$/i.test(normalized) ? normalized : undefined;+}++export function isOAuthCallbackPath(path: unknown): boolean {+ return (+ typeof path === "string" &&+ (path.startsWith("/callback/") || path.startsWith("/oauth2/callback/"))+ );+}++export async function assertGuestRegistrationAllowed(): Promise<void> {+ if (+ process.env.DISABLE_GUEST_ACCESS === "true" ||+ process.env.DISABLE_REGISTRATION === "true" ||+ process.env.DISABLE_PASSWORD_REGISTRATION === "true" ||+ process.env.DISABLE_LOGIN_FORM === "true" ||+ !(await hasRegisteredUsers())+ ) {+ throw new APIError("FORBIDDEN", {+ message: "Guest access is unavailable on this instance.",+ });+ }+}++export async function assertUserRegistrationAllowed(+ user: {+ email: string;+ emailVerified?: boolean;+ isAnonymous?: boolean | null;+ },+ context?: { path?: string; invitationId?: unknown },+): Promise<void> {+ if (user.isAnonymous) {+ await assertGuestRegistrationAllowed();+ return;+ }+ if (!(await hasRegisteredUsers())) return;+ if (+ process.env.DISABLE_PASSWORD_REGISTRATION === "true" &&+ !isOAuthCallbackPath(context?.path)+ ) {+ throw new APIError("FORBIDDEN", {+ message:+ "Local account registration is disabled. Please use a configured social or OIDC sign-in method.",+ });+ }+ const verifiedEmailFlow =+ isOAuthCallbackPath(context?.path) ||+ context?.path === "/sign-in/email-otp" ||+ context?.path === "/magic-link/verify";+ const result = await checkRegistrationAllowed(+ user.email,+ normalizeInvitationId(context?.invitationId),+ {+ allowInvitationByEmail: verifiedEmailFlow,+ emailVerified: user.emailVerified === true,+ },+ );+ if (!result.allowed)+ throw new APIError("FORBIDDEN", { message: result.reason });+}diff --git a/apps/api/src/utils/require-user-session.ts b/apps/api/src/utils/require-user-session.tsnew file mode 100644index 000000000..cc6fa88e6--- /dev/null+++ b/apps/api/src/utils/require-user-session.ts@@ -0,0 +1,11 @@+import type { Context, Next } from "hono";+import { HTTPException } from "hono/http-exception";++/** Sensitive account operations cannot inherit the owner's privileges from an API key. */+export async function requireUserSession(c: Context, next: Next) {+ if (c.get("apiKey") || !c.get("session") || !c.get("user")) {+ throw new HTTPException(403, { message: "A user session is required" });+ }+ c.header("Cache-Control", "no-store");+ return next();+}diff --git a/apps/api/src/utils/sensitive-outbound.ts b/apps/api/src/utils/sensitive-outbound.tsnew file mode 100644index 000000000..1a5a87718--- /dev/null+++ b/apps/api/src/utils/sensitive-outbound.ts@@ -0,0 +1,12 @@+import { AsyncLocalStorage } from "node:async_hooks";++// Webhook and bot credentials may live in the URL path, so ordinary query/header+// redaction is insufficient. Scope automatic HTTP telemetry to the individual+// delivery rather than disabling tracing for unrelated concurrent requests.+const sensitiveDelivery = new AsyncLocalStorage<boolean>();+export function isSensitiveOutboundRequest() {+ return sensitiveDelivery.getStore() === true;+}+export function withoutOutboundTelemetry<T>(action: () => T): T {+ return sensitiveDelivery.run(true, action);+}diff --git a/apps/api/src/utils/verify-api-key.ts b/apps/api/src/utils/verify-api-key.tsindex 77a7ffa21..597d413e7 100644--- a/apps/api/src/utils/verify-api-key.ts+++ b/apps/api/src/utils/verify-api-key.ts@@ -1,5 +1,5 @@import { createHash } from "node:crypto";-import { and, eq, gt, isNull, or } from "drizzle-orm";+import { and, eq, exists, gt, isNull, or, sql } from "drizzle-orm";import db, { schema } from "../database";async function hashApiKey(key: string): Promise<string> {@@ -46,6 +46,18 @@ export async function verifyApiKey(key: string) {and(eq(schema.apikeyTable.key, hashedKey),eq(schema.apikeyTable.enabled, true),+ // Fail closed even before legacy databases finish the repair migration.+ exists(+ db+ .select({ id: schema.userTable.id })+ .from(schema.userTable)+ .where(+ eq(+ schema.userTable.id,+ sql`coalesce(${schema.apikeyTable.referenceId}, ${schema.apikeyTable.userId})`,+ ),+ ),+ ),or(isNull(schema.apikeyTable.expiresAt),gt(schema.apikeyTable.expiresAt, new Date()),diff --git a/apps/api/src/utils/verify-turnstile.ts b/apps/api/src/utils/verify-turnstile.tsindex c3f16fbb0..8760c49f4 100644--- a/apps/api/src/utils/verify-turnstile.ts+++ b/apps/api/src/utils/verify-turnstile.ts@@ -1,66 +1,60 @@+import { sendOutboundRequest } from "./outbound-request";+const TURNSTILE_VERIFY_URL ="https://challenges.cloudflare.com/turnstile/v0/siteverify";--const DEFAULT_TIMEOUT_MS = 5000;-export type TurnstileResult = { ok: true } | { ok: false; reason: string };-// Verifies a Cloudflare Turnstile token against the siteverify endpoint.-// Returns { ok: true } when the token is valid OR when no secret is configured-// (self-hosted instances opt out by leaving TURNSTILE_SECRET_KEY unset).+export const authCaptchaPaths = new Set([+ "/sign-up/email",+ "/sign-in/social",+ "/sign-in/oauth2",+ "/sign-in/anonymous",+ "/sign-in/magic-link",+ "/email-otp/send-verification-otp",+]);++// One token is redeemed at initiation, never again at the OAuth callback or+// OTP redemption. Better Auth verifies the corresponding state/code there.export async function verifyTurnstile(- token: string | null | undefined,- remoteIp?: string | null,+ token: unknown,): Promise<TurnstileResult> {const secret = process.env.TURNSTILE_SECRET_KEY;- if (!secret) {- return { ok: true };- }- if (!token) {- return { ok: false, reason: "Captcha token missing." };- }-- const raw = (process.env.TURNSTILE_TIMEOUT_MS ?? "").trim();- const parsed = Number.parseInt(raw, 10);- const timeoutMs =- Number.isSafeInteger(parsed) && parsed > 0 && String(parsed) === raw- ? parsed- : DEFAULT_TIMEOUT_MS;-- const body = new URLSearchParams();- body.set("secret", secret);- body.set("response", token);- if (remoteIp) {- body.set("remoteip", remoteIp);- }+ if (!secret) return { ok: true };+ const failure = {+ ok: false,+ reason: "Captcha verification failed.",+ } as const;+ if (typeof token !== "string" || token.length === 0 || token.length > 2048)+ return failure;try {- const res = await fetch(TURNSTILE_VERIFY_URL, {- method: "POST",- body,- signal: AbortSignal.timeout(timeoutMs),- });- const data = (await res.json()) as {- success?: boolean;- "error-codes"?: string[];- };- if (data.success === true) {- return { ok: true };- }- const errorCodes = data["error-codes"]?.join(",") ?? "unknown";- return {- ok: false,- reason: `Captcha verification failed (${errorCodes}).`,- };- } catch (error) {+ const hostname = new URL(process.env.KANEO_CLIENT_URL || "").hostname;+ if (+ process.env.KANEO_CLOUD === "true" &&+ process.env.NODE_ENV === "production" &&+ ["localhost", "127.0.0.1", "[::1]"].includes(hostname)+ )+ return failure;+ const data = await sendOutboundRequest(+ TURNSTILE_VERIFY_URL,+ {+ body: new URLSearchParams({ secret, response: token }),+ },+ { readJson: true },+ );if (- error instanceof DOMException &&- (error.name === "TimeoutError" || error.name === "AbortError")- ) {- console.error("Turnstile verification timed out", error);- return { ok: false, reason: "Captcha verification timed out." };- }- console.error("Turnstile verification request failed", error);- return { ok: false, reason: "Captcha verification failed." };+ data &&+ typeof data === "object" &&+ "success" in data &&+ data.success === true &&+ "action" in data &&+ data.action === "auth" &&+ "hostname" in data &&+ data.hostname === hostname+ )+ return { ok: true };+ } catch {+ // Fail closed without retaining token, secret or an upstream error body.}+ return failure;}diff --git a/apps/api/src/utils/workspace-access-middleware.ts b/apps/api/src/utils/workspace-access-middleware.tsindex e431cb1a9..9babe25ea 100644--- a/apps/api/src/utils/workspace-access-middleware.ts+++ b/apps/api/src/utils/workspace-access-middleware.ts@@ -170,10 +170,27 @@ async function lookupWorkspaceId(case "label": {const [label] = await db- .select({ workspaceId: schema.labelTable.workspaceId })+ .select({+ workspaceId: schema.labelTable.workspaceId,+ taskId: schema.labelTable.taskId,+ taskWorkspaceId: schema.projectTable.workspaceId,+ }).from(schema.labelTable)+ .leftJoin(+ schema.taskTable,+ eq(schema.labelTable.taskId, schema.taskTable.id),+ )+ .leftJoin(+ schema.projectTable,+ eq(schema.taskTable.projectId, schema.projectTable.id),+ ).where(eq(schema.labelTable.id, id)).limit(1);+ // Older releases allowed inconsistent label/task references. Never use+ // such a row to authorize reads, mutations or external provider sync.+ if (label?.taskId && label.taskWorkspaceId !== label.workspaceId) {+ return null;+ }return label?.workspaceId || null;}diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex a71466979..d9d1ddeea 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -376,6 +376,17 @@ for (const eventName of taskUpdateEvents) {type = "TASK_UPDATED";}+ if (eventName === "task.label_deleted") {+ // Cascade deletion waits for this adapter operation rather than growing+ // the ordinary 100ms broadcast queue behind a slow Redis connection.+ await adapter?.publish({+ projectId,+ message: { type, projectId, taskId },+ excludeInitiatorId: initiatorId,+ });+ return;+ }+broadcastToProject(projectId,{diff --git a/apps/api/src/ws/security.ts b/apps/api/src/ws/security.tsnew file mode 100644index 000000000..94d0e02b7--- /dev/null+++ b/apps/api/src/ws/security.ts@@ -0,0 +1,69 @@+import { HTTPException } from "hono/http-exception";+import type { WSContext } from "hono/ws";++export const MAX_WEBSOCKET_MESSAGE_BYTES = 64;++export function assertWebSocketOrigin(headers: Headers) {+ const origin = headers.get("origin");+ if (origin === null) {+ // Native clients may omit Origin, but must supply explicit credentials.+ // authenticateApiRequest still validates them and rejects invalid tokens;+ // a cookie alone must never bypass the browser-origin boundary.+ if (+ /^Bearer\s+\S+$/i.test(headers.get("authorization") ?? "") ||+ headers.get("x-api-key")?.trim()+ ) {+ return;+ }+ } else {+ const configured = [+ process.env.KANEO_CLIENT_URL,+ process.env.KANEO_API_URL,+ ...(process.env.CORS_ORIGINS ?? "").split(","),+ ];+ if (process.env.NODE_ENV !== "production") {+ if (!process.env.KANEO_CLIENT_URL)+ configured.push("http://localhost:5173");+ if (!process.env.KANEO_API_URL) configured.push("http://localhost:1337");+ }+ for (const value of configured) {+ if (!value?.trim()) continue;+ try {+ const url = new URL(value.trim());+ if (+ (url.protocol === "https:" || url.protocol === "http:") &&+ !url.username &&+ !url.password &&+ url.origin === origin+ ) {+ return;+ }+ } catch {+ // Invalid entries and wildcards do not grant access.+ }+ }+ }+ throw new HTTPException(403, { message: "WebSocket origin is not allowed" });+}++export function handleWebSocketMessage(+ evt: MessageEvent<unknown>,+ ws: WSContext,+) {+ if (typeof evt.data !== "string") {+ ws.close(1003, "Only text keepalives are supported");+ return;+ }+ if (+ evt.data.length > MAX_WEBSOCKET_MESSAGE_BYTES ||+ Buffer.byteLength(evt.data, "utf8") > MAX_WEBSOCKET_MESSAGE_BYTES+ ) {+ ws.close(1009, "Message too large");+ return;+ }+ // Both web clients send this exact keepalive. No arbitrary JSON needs to be+ // parsed, copied or dispatched. Receiving it is enough to keep proxies alive.+ if (evt.data !== '{"type":"ping"}') {+ ws.close(1008, "Unsupported message");+ }+}diff --git a/apps/api/vitest.storage.config.ts b/apps/api/vitest.storage.config.tsnew file mode 100644index 000000000..a25286e9f--- /dev/null+++ b/apps/api/vitest.storage.config.ts@@ -0,0 +1,10 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ environment: "node",+ include: ["../../tests/storage-integration/**/*.test.ts"],+ fileParallelism: false,+ testTimeout: 15_000,+ },+});diff --git a/apps/docs/api-reference/endpoints/github/createGitHubIntegration.mdx b/apps/docs/api-reference/endpoints/github/createGitHubIntegration.mdxindex 94f52e830..0294d18aa 100644--- a/apps/docs/api-reference/endpoints/github/createGitHubIntegration.mdx+++ b/apps/docs/api-reference/endpoints/github/createGitHubIntegration.mdx@@ -3,3 +3,6 @@ title: createGitHubIntegrationdescription: Create a new GitHub integration for a projectopenapi: 'POST /github-integration/project/{projectId}'---+++Connecting a different repository while one is already linked returns **409**. Disconnect the current integration first so its old issue and pull-request numbers cannot be reused against the new repository. Local tasks remain; old external links and saved import progress are removed by disconnecting. Reverification of the same numeric repository preserves existing links and preferences, including when its name or installation changes. Concurrent configuration changes also return409; refresh before retrying.diff --git a/apps/docs/api-reference/endpoints/github/importGitHubIssues.mdx b/apps/docs/api-reference/endpoints/github/importGitHubIssues.mdxindex ac49b01b3..6b44368fa 100644--- a/apps/docs/api-reference/endpoints/github/importGitHubIssues.mdx+++ b/apps/docs/api-reference/endpoints/github/importGitHubIssues.mdx@@ -3,3 +3,12 @@ title: importGitHubIssuesdescription: Import GitHub issues as tasksopenapi: 'POST /github-integration/import-issues'---+++This endpoint processes at most four provider pages per request. It returns **202** while work remains and **200** when the run is complete. Send the returned `runId` with the same `projectId` on each continuation. Retrying a completed `runId` returns its final summary without starting another run.++Without `runId`, the endpoint resumes an unfinished run or starts a new run after the previous one completes. `GET /github-integration/project/{projectId}` exposes the saved `importProgress` summary, including its `runId` and `pending` flag. Provider cursors remain on the server. Workspace access and task creation permission are checked on every request.++**429** means an import is busy; honor `Retry-After`. **502** pauses work on a provider failure; previously committed pages are retained. **409** indicates that the integration or run changed; refresh its configuration before retrying. A successful response includes `imported`, `updated` and `skipped` counts. Do not treat a 202 response as completion.++API and web clients must be upgraded together. Custom clients that previously expected one synchronous 200 response must implement this continuation loop.diff --git a/apps/docs/api-reference/endpoints/labels/deleteLabel.mdx b/apps/docs/api-reference/endpoints/labels/deleteLabel.mdxindex 86e4e5097..d8edbd962 100644--- a/apps/docs/api-reference/endpoints/labels/deleteLabel.mdx+++ b/apps/docs/api-reference/endpoints/labels/deleteLabel.mdx@@ -3,3 +3,18 @@ title: deleteLabeldescription: Delete a label by IDopenapi: 'DELETE /label/{id}'---++Workspace label deletion runs in steps of at most 25 task assignments. After a+`202 Accepted` response with `pendingDeletion: true`, repeat `DELETE /label/{id}`+with the same ID until the server returns `200 OK`. Do not mark the label as+deleted after the first `202` response.++The server stores the deletion start time. Retrying after a connection failure+or API restart resumes the remaining assignments. Assignments created after+that boundary by a concurrent import or webhook are not part of this operation.+During deletion, attempts to edit the workspace label or attach it to another+task return `409 Conflict`.++Concurrent deletion work is limited across API replicas. A `429` response includes+`Retry-After`; retry after that interval. Each request still requires label-delete+permission. Single task-label deletion completes with `200 OK`.diff --git a/apps/docs/api-reference/endpoints/tasks/listTasks.mdx b/apps/docs/api-reference/endpoints/tasks/listTasks.mdxindex 94ba4d892..d70da023f 100644--- a/apps/docs/api-reference/endpoints/tasks/listTasks.mdx+++ b/apps/docs/api-reference/endpoints/tasks/listTasks.mdx@@ -1,5 +1,45 @@---title: listTasks-description: Get all tasks for a specific project+description: Get a bounded page of tasks for a specific projectopenapi: 'GET /task/tasks/{projectId}'---+++Every response is paginated: the default is **50 tasks**, with a maximum `limit` of **100**. Inspect `pagination.totalPages` and request subsequent `page` values to retrieve the entire project. Filters and sorting are applied before pagination. The page includes tasks across regular columns, planned tasks and archived tasks; it is not a separate limit for every column.++The web app fetches these pages sequentially and combines them for its board, list, calendar and Gantt views. Custom clients that previously omitted pagination to receive every task must now follow the pagination metadata. MCP `list_tasks` uses the same paginated contract.++The unauthenticated `GET /public-project/{id}` route also returns bounded pages. Its `pagination` object is alongside the board fields. Public visibility is checked before loading tasks and again for each subsequent request.+++Descriptions larger than 64 KiB are returned as `description: null` with+`descriptionDeferred: true`. This means the text was omitted, not deleted. Load+`GET /api/task/{id}` for the task detail, or follow+`GET /api/task/{id}/description?offset=0` and its `nextOffset` values for bounded+text pages. Send the first page's `version` on subsequent requests; a `409`+requires restarting from offset zero. Omit `description` in generic task updates+when editing a list summary. Sending an explicit empty string clears the text.++The web board searches omitted descriptions through+`GET /api/task/description-matches/{projectId}?query=…`, following `nextCursor`+as `after` until it is null. Searches match literal case-insensitive substrings;+`%` and `_` have no wildcard meaning. This endpoint requires project access.+Public details use `/api/public-project/{id}/task/{taskId}/description`; visibility+and task ownership are checked on every page. A description timeout returns `503`+and can be retried.+++Each task page also has `pagination.relatedTotalPages`. Request `relatedPage=2`,+`3`, and so on for the **same task page and filters**, merging labels and external+links by ID and columns by slug. Each response contains at most 100 labels and+100 external links, a page of 100 columns, and up to 100 additional columns needed+to represent the selected tasks. The web client completes these continuations+before showing a successful refresh. Use returned column `position` to retain+ordering. Both task and related pagination describe a live collection; concurrent+changes are picked up on a later refresh, not an immutable snapshot.++Board-level project descriptions use the same 64 KiB omission flag. Authorized+clients can use the project detail endpoint; public clients can follow+`GET /api/public-project/{id}/description` with `offset` and `version`, just like+public task descriptions. Every database statement in a board read has a+three-second timeout; expensive counts or offsets return a retryable `503`.diff --git a/apps/docs/core/functional/manage-workspace-labels.mdx b/apps/docs/core/functional/manage-workspace-labels.mdxindex 7742323ae..ce2401165 100644--- a/apps/docs/core/functional/manage-workspace-labels.mdx+++ b/apps/docs/core/functional/manage-workspace-labels.mdx@@ -35,11 +35,13 @@ Changes cascade to every task currently using that label, with no manual re-assi1. Click the trash icon next to the label.2. Confirm deletion in the dialog.-Deleting a workspace label removes it from **all** tasks that use it. This cannot be undone.+Deleting a workspace label removes its existing task assignments. This cannot be undone. Large deletions take longer; keep the page open until the success message appears.++If the connection fails or you close the page, return to **Workspace → Labels**. An unfinished label shows **Deletion pending**. Use its trash button, then **Resume deletion**, to finish removing the remaining assignments. A pending label cannot be edited or newly assigned from the label picker.## Permissions-Managing workspace labels requires the **Manage settings** permission. If you don't see the edit or delete controls, ask a workspace admin to update your role.+Creating, editing, and deleting labels require the corresponding **Label** permissions. If you don't see the controls, ask a workspace admin to update your role.## Best practicesdiff --git a/apps/docs/core/index.mdx b/apps/docs/core/index.mdxindex a7edc2dc6..6c913a60f 100644--- a/apps/docs/core/index.mdx+++ b/apps/docs/core/index.mdx@@ -23,8 +23,9 @@ We offer two ways to install Kaneo:For straightforward deployments, use [drim](/core/installation/drim) - a CLI tool that handles everything automatically:+Install drim using the [version-pinned download and checksum verification](/core/installation/drim#installation), then run:+```bash-curl -fsSL https://assets.kaneo.app/install.sh | shdrim setup```diff --git a/apps/docs/core/installation/docker-compose.mdx b/apps/docs/core/installation/docker-compose.mdxindex 63e805ecc..3251574e6 100644--- a/apps/docs/core/installation/docker-compose.mdx+++ b/apps/docs/core/installation/docker-compose.mdx@@ -13,13 +13,14 @@ services:image: postgres:16-alpineenv_file:- .env- ports:- - "5432:5432"+ environment:+ POSTGRES_USER: ${POSTGRES_USER:-kaneo}+ POSTGRES_DB: ${POSTGRES_DB:-kaneo}volumes:- postgres_data:/var/lib/postgresql/datarestart: unless-stoppedhealthcheck:- test: ["CMD-SHELL", "pg_isready -U kaneo -d kaneo"]+ test: ["CMD-SHELL", 'pg_isready -U "$${POSTGRES_USER}" -d "$${POSTGRES_DB}"']interval: 10stimeout: 5sretries: 5@@ -73,7 +74,7 @@ AUTH_SECRET= # generate: openssl rand -hex 32This keeps the browser on one origin while the container proxies `/api` requests to the internal API process.For this Compose setup, the bundled Kaneo container reaches PostgreSQL at the service hostname `postgres`.-If you run the API directly on your host instead, use `localhost` or set `DATABASE_URL` explicitly.+The database is reachable only inside the Compose network. For host-based development, explicitly add a loopback-only mapping (`127.0.0.1:5432:5432`) and configure `DATABASE_URL` accordingly.## Notes on object storagediff --git a/apps/docs/core/installation/drim-migration.mdx b/apps/docs/core/installation/drim-migration.mdxindex d7b4e1074..7a5160001 100644--- a/apps/docs/core/installation/drim-migration.mdx+++ b/apps/docs/core/installation/drim-migration.mdx@@ -105,11 +105,11 @@ Record the names of your existing volumes and your current environment values:docker volume ls | grep -i kaneo```-Stop the current stack, then install drim and run setup in a new directory:+Complete the [verified drim installation](/core/installation/drim#installation)+before stopping the current stack. Then run setup in a new directory:```bashdocker compose down-curl -fsSL https://assets.kaneo.app/install.sh | shmkdir ~/kaneo && cd ~/kaneodrim setup --domain=your-domain.comdrim stopdiff --git a/apps/docs/core/installation/drim.mdx b/apps/docs/core/installation/drim.mdxindex 0ce358662..f2cf49c82 100644--- a/apps/docs/core/installation/drim.mdx+++ b/apps/docs/core/installation/drim.mdx@@ -11,26 +11,52 @@ It suits straightforward deployments. If you need a custom topology, extra servi## Installation-```bash-curl -fsSL https://assets.kaneo.app/install.sh | sh-```--Or download a binary from [releases](https://github.com/usekaneo/drim/releases/latest).--### Install script options--| Option | Description |-| --- | --- |-| `--silent` | Suppress output |-| `--setup` | Run `drim setup` after installing |-| `--domain=DOMAIN` | Deploy on this domain, implies `--setup` |--```bash-# Install, deploy, and configure HTTPS for a domain in one command-curl -fsSL https://assets.kaneo.app/install.sh | sh -s -- --setup --domain=kaneo.example.com+Install Docker and Docker Compose using your operating system's signed packages+before running setup. Then install the fixed [drim v0.1.8 release](https://github.com/usekaneo/drim/releases/tag/v0.1.8)+using the reviewed checksums below. The download is saved to a temporary file and+verified before it is made executable; it does not run an installation script.++```sh+(+ set -eu+ case "$(uname -s)-$(uname -m)" in+ Linux-x86_64)+ drim_asset=drim_Linux_x86_64+ drim_sha256=dbc57af416dac4d6f4302a77cac22c0e1887afcfdf55173c3113ae1f4712bd89 ;;+ Linux-aarch64|Linux-arm64)+ drim_asset=drim_Linux_arm64+ drim_sha256=dd78bea7b40c4e071887605823f6d999829c7500787f27a86ab2166697f0520f ;;+ Darwin-x86_64)+ drim_asset=drim_Darwin_x86_64+ drim_sha256=d2d6f8e1ab3e7725de0a559626a10660b6507cd85955c5bfcd1419de07e8ad29 ;;+ Darwin-arm64)+ drim_asset=drim_Darwin_arm64+ drim_sha256=065d0611b61e83284f3ffa620c9cc12b83ebdab74ce09f402ed70eea795713ea ;;+ *) echo "Unsupported platform; use a supported Linux or macOS system." >&2; exit 1 ;;+ esac+ drim_tmp=$(mktemp -d)+ trap 'rm -rf "$drim_tmp"' EXIT HUP INT TERM+ cd "$drim_tmp"+ curl --fail --show-error --silent --location \+ --proto '=https' --proto-redir '=https' --tlsv1.2 \+ "https://github.com/usekaneo/drim/releases/download/v0.1.8/$drim_asset" \+ --output drim+ if command -v sha256sum >/dev/null 2>&1; then+ printf '%s drim\n' "$drim_sha256" | sha256sum -c -+ else+ printf '%s drim\n' "$drim_sha256" | shasum -a 256 -c -+ fi+ mkdir -p "$HOME/.local/bin"+ install -m 755 drim "$HOME/.local/bin/drim"+)```-The script detects your platform, downloads the matching binary, and installs it to `/usr/local/bin`. It supports Linux and macOS on amd64 and arm64, and Windows through WSL.+Add `~/.local/bin` to your shell's `PATH`, or use `~/.local/bin/drim` in place of+`drim` below. WSL uses the Linux asset matching its architecture. Stop on a+checksum mismatch; do not replace the expected checksum with one supplied by+the failed download. These fixed digests pin the published bytes, not a claim+that the release was independently audited. Upgrading drim requires selecting+and reviewing a new release and updating its expected digest.## Quick start@@ -63,7 +89,6 @@ drim start # Start servicesdrim stop # Stop servicesdrim restart # Restart servicesdrim upgrade # Pull the latest Kaneo images and restart-drim update # Update the drim CLI itselfdrim configure # Edit .env, then apply the changesdrim uninstall # Remove Kaneo```@@ -130,11 +155,9 @@ drim upgradeThis pulls the latest images and restarts the changed services. Your data lives in Docker volumes and is not touched.-To update drim itself:--```bash-drim update-```+To update drim itself, repeat the verified installation procedure with a newly+reviewed release and its fixed checksum. The built-in updater follows the latest+release and is not part of this pinned installation procedure.<Warning>Deployments created before Kaneo moved to a single container still run the older two-image layout, and `drim upgrade` does not rewrite an existing `docker-compose.yml`. See [migrating to drim](/core/installation/drim-migration) to move to the current layout.@@ -145,7 +168,9 @@ Deployments created before Kaneo moved to a single container still run the older```bashgit clone https://github.com/usekaneo/drim.gitcd drim-go build -o drim .+git checkout --detach 2c21e713869c97dda413e4135ffaf89ece8156c8+# Review this fixed source revision and its dependencies before building.+go build -mod=readonly -o drim .````make build-all` cross-compiles for every supported platform.diff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdxindex a7dd9d0f6..a19c93e76 100644--- a/apps/docs/core/installation/environment-variables.mdx+++ b/apps/docs/core/installation/environment-variables.mdx@@ -35,6 +35,14 @@ Name | Description || `KANEO_CLIENT_URL` | The URL of the web application.| `KANEO_API_URL` | The URL of the API.+The web container embeds only `KANEO_API_URL`, `KANEO_CLIENT_URL`, and+`KANEO_TURNSTILE_SITE_KEY` into browser assets at startup. These values are public;+other `KANEO_*` variables are not substituted into frontend files. Values are+encoded as JavaScript strings. The standalone web image serves its generated MCP+discovery documents as JSON files, without modifying the nginx configuration.+Configure actual public service URLs; escaping a value does not make an invalid+URL usable. Recreate the container when changing its environment.+### DatabaseThis section will cover all the variables related to the database.@@ -85,11 +93,18 @@ Name | Description | Default |### Access Control+Browser WebSocket connections require an exact origin matching `KANEO_CLIENT_URL`,+`KANEO_API_URL`, or a comma-separated `CORS_ORIGINS` entry. Wildcards, `null`, and+missing browser origins are rejected. Production deployments must configure their+public URLs. Native clients without an Origin header must provide a valid bearer+token or API key; cookies alone are not sufficient. Both real-time endpoints accept+only the small `{"type":"ping"}` text keepalive, with a 64-byte message limit.+Name | Description | Default |--- | --- | --- |-| `DISABLE_GUEST_ACCESS` | Disable anonymous/guest sign-in. When set to `true`, the guest access button will not be shown on sign-in and sign-up pages. | `false` |-| `DISABLE_REGISTRATION` | Disable public user registration. When set to `true`, the sign-up option will not be shown on the sign-in page and new user creation is blocked (including via SSO). **Note:** Users with valid workspace invitations can still register even when this is enabled. | `false` |-| `DISABLE_PASSWORD_REGISTRATION` | Disable password-based account creation. When set to `true`, email/password sign-up is blocked, but social/OIDC registration remains available unless `DISABLE_REGISTRATION=true`. | `false` |+| `DISABLE_GUEST_ACCESS` | Disable anonymous/guest sign-in. Guests are also blocked before initial instance setup and when registration, local registration, or the local login form is disabled. | `false` |+| `DISABLE_REGISTRATION` | Disable public user registration. When set to `true`, the sign-up option will not be shown on the sign-in page and new user creation is blocked (including via SSO). **Note:** Invited password signups must present the matching invitation link. OAuth, OTP, and magic-link signups may match an invitation by email only after that email has been verified. The first non-guest user can complete initial instance setup. | `false` |+| `DISABLE_PASSWORD_REGISTRATION` | Disable local account creation through password, email OTP, magic link, and guest access. Existing accounts can still use email sign-in unless `DISABLE_LOGIN_FORM=true`. Social/OIDC registration remains available unless `DISABLE_REGISTRATION=true`. The initial administrator can still be created through password signup. | `false` || `DISABLE_EMAIL_OTP_SIGN_IN` | When SMTP is configured, sign-in uses email verification codes by default. Set to `true` to use email/password sign-in instead. Workspace invitation emails still use SMTP. | `false` || `DISABLE_LOGIN_FORM` | Hide the email/password login form on the sign-in page. When set to `true`, only SSO/OAuth buttons are shown. Useful when you want to enforce authentication exclusively through an external identity provider. | `false` || `CUSTOM_OAUTH_AUTO_LOGIN` | Automatically redirect to the custom OAuth/OIDC provider instead of showing the sign-in page. When set to `true`, users are immediately redirected to your identity provider without seeing the login page. Requires a custom OAuth provider to be configured. | `false` |@@ -102,7 +117,7 @@ Name | Description | Default |Name | Description | Default |--- | --- | --- |-| `TRUSTED_PROXIES` | Comma-separated IPs or CIDR ranges of the reverse proxies in front of Kaneo. The forwarded header chain is walked right to left, trusted hops are skipped, and the first untrusted address is taken as the client IP. Only set this if your proxies sit outside the default ranges; the default covers loopback and private networks, which is correct for the standard Docker Compose setup. | `127.0.0.0/8, ::1/128, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16` |+| `TRUSTED_PROXIES` | Comma-separated IPs or CIDR ranges of trusted reverse proxies. Kaneo first checks the actual TCP peer, then walks `X-Forwarded-For` right to left only through trusted hops. Defaults trust the bundled loopback nginx only. For a separate Docker/ingress proxy, explicitly add its IP or dedicated proxy subnet; avoid shared private-network ranges. Use `none` for direct API access without trusted proxies. Invalid entries prevent startup. `CF-Connecting-IP` and client-supplied `X-Kaneo-Client-IP` are never used. | `127.0.0.0/8, ::1/128` |<Warning>Only list addresses you control. Any host in this range can set `X-Forwarded-For` and have it believed, so do not include a range that clients can reach Kaneo from directly. The client IP is used for rate limiting and session records.@@ -205,12 +220,15 @@ Name | Description |--- | --- || `SMTP_HOST` | The SMTP host.| `SMTP_PORT` | The SMTP port.-| `SMTP_SECURE` | Whether to use SSL/TLS.+| `SMTP_SECURE` | Use TLS immediately (default: `true`, typically port 465). Set to `false` for STARTTLS, typically on port 587.| `SMTP_USER` | The SMTP user.| `SMTP_PASSWORD` | The SMTP password.| `SMTP_FROM` | The SMTP from address.-| `SMTP_REQUIRE_TLS` | Whether to explicitly force to use TLS. [See more on](https://nodemailer.com/smtp#tls-options).-| `SMTP_IGNORE_TLS` | Ignore TLS certificate errors. Set to `true` for self-signed or invalid certificates. Default: `false`.+| `SMTP_REQUIRE_TLS` | Require STARTTLS when `SMTP_SECURE=false` (default: `true`). Sending fails if the server cannot upgrade. Only use `false` for an intentionally unencrypted local development relay.+| `SMTP_IGNORE_TLS` | Removed: `true` is rejected. This option disabled STARTTLS; it never bypassed certificate validation.+| `NODE_EXTRA_CA_CERTS` | Path to a trusted CA PEM file for a private SMTP certificate authority. Set before starting the API; certificate expiry and hostname checks remain enabled.++When upgrading, remove `SMTP_IGNORE_TLS=true` and verify delivery with the corrected certificate trust configuration before rollout. Fix invalid certificates instead of disabling validation. [Nodemailer documents the difference between STARTTLS and certificate validation](https://nodemailer.com/smtp#tls-options).## Key points@@ -221,3 +239,11 @@ Name | Description |- If you enable Custom OAuth/OIDC, you need to configure your identity provider with the appropriate redirect URI. See the [Custom OAuth/OIDC guide](/core/social-providers/custom-oauth).- If you have enabled SMTP, sign-in uses email verification codes by default. Set `DISABLE_EMAIL_OTP_SIGN_IN=true` to use email/password sign-in instead.- If you need device authorization for clients beyond the defaults (`kaneo-cli`, `kaneo-mcp` when `DEVICE_AUTH_CLIENT_IDS` is unset), set `DEVICE_AUTH_CLIENT_IDS` to the full comma-separated list of trusted client IDs for your deployment.++## Authentication CAPTCHA++When `TURNSTILE_SECRET_KEY` is configured on the API, deploy the matching `VITE_TURNSTILE_SITE_KEY` with the web app. The API validates the token at password signup, social/OIDC initiation, guest sign-in, OTP sending (including resend), and magic-link initiation. Tokens are single-use; clients must obtain a fresh token for each attempt. OAuth callbacks and OTP redemption validate their own state/code and do not redeem the CAPTCHA token again.++The widget uses the action `auth`. The API requires that action and the exact frontend hostname from `KANEO_CLIENT_URL`, and rejects verification failures, redirects and timeouts. Update the API and web app together when adopting this check. Custom clients must include the token in the `x-turnstile-token` header. Automatic OIDC redirection pauses at the sign-in page when a CAPTCHA widget is configured so the user can complete it.++No secret configured means CAPTCHA is disabled, as on self-hosted instances that opt out. This does not bypass registration or guest-access restrictions.diff --git a/apps/docs/core/installation/index.mdx b/apps/docs/core/installation/index.mdxindex de0c1ae34..2980c0883 100644--- a/apps/docs/core/installation/index.mdx+++ b/apps/docs/core/installation/index.mdx@@ -16,8 +16,9 @@ Kaneo offers two installation methods depending on your needs:- Simple production deployments with a single domain- Automatic HTTPS setup+Install drim using the [version-pinned download and checksum verification](/core/installation/drim#installation), then run:+```bash-curl -fsSL https://assets.kaneo.app/install.sh | shdrim setup```diff --git a/apps/docs/core/installation/migration.mdx b/apps/docs/core/installation/migration.mdxindex 72ca2c72c..edda80c52 100644--- a/apps/docs/core/installation/migration.mdx+++ b/apps/docs/core/installation/migration.mdx@@ -55,7 +55,7 @@ volumes:postgres_data:```-### After+### After (current recommended configuration)```ymlservices:@@ -63,8 +63,9 @@ services:image: postgres:16-alpineenv_file:- .env- ports:- - "5432:5432"+ environment:+ POSTGRES_USER: ${POSTGRES_USER:-kaneo}+ POSTGRES_DB: ${POSTGRES_DB:-kaneo}volumes:- postgres_data:/var/lib/postgresql/datarestart: unless-stopped@@ -89,7 +90,7 @@ volumes:postgres_data:```-Remove the `api` and `web` service blocks and add the `kaneo` service. The `postgres` service is unchanged except for the added healthcheck, which `kaneo` waits for before starting.+Remove the `api` and `web` service blocks and add the `kaneo` service. The current recommended `postgres` configuration adds a healthcheck and keeps the database on the internal Compose network without publishing port 5432. Preserve the actual database name, user and password from your existing installation in `.env`; defaults do not rename an existing database.---diff --git a/apps/docs/core/installation/object-storage-and-image-uploads.mdx b/apps/docs/core/installation/object-storage-and-image-uploads.mdxindex 48cc37fff..c7bb720c6 100644--- a/apps/docs/core/installation/object-storage-and-image-uploads.mdx+++ b/apps/docs/core/installation/object-storage-and-image-uploads.mdx@@ -14,6 +14,23 @@ Uploads use an S3-compatible object storage backend:- Kaneo finalizes uploads into private asset records- Kaneo serves uploaded files back through its own API+Upload URLs bind the declared byte length and content type. The browser supplies+`Content-Length` from the selected file automatically; custom clients must send+that exact length and the returned `Content-Type`. A streaming request without+`Content-Length`, a larger body, or a changed content type is rejected by storage.++Before creating an asset record, Kaneo retrieves object metadata with `HeadObject`+and checks existence, size and content type. Missing or mismatched objects are+not finalized. Oversized objects are removed. The storage credentials therefore+need read (`s3:GetObject`, also used by HEAD), write and delete access. Configure+storage CORS to allow your frontend origin and PUT with `Content-Type`.++After upgrading, check an upload through your actual browser, storage provider+and reverse proxy. The provider must enforce SigV4 signed `Content-Length` and+`Content-Type`; do not work around incompatibility by removing those signed+headers. Previously issued upload URLs retain their old constraints until their+configured expiry, so account for `S3_PRESIGN_TTL_SECONDS` during rollout.+This means Kaneo can work with multiple backends as long as they expose a compatible S3-style API.Current behavior:diff --git a/apps/docs/core/integrations/github/configuration.mdx b/apps/docs/core/integrations/github/configuration.mdxindex 049b4ef38..66fc0b6af 100644--- a/apps/docs/core/integrations/github/configuration.mdx+++ b/apps/docs/core/integrations/github/configuration.mdx@@ -172,6 +172,10 @@ Once connected, new tasks created in this project will automatically generate Gi</Step></Steps>+### Changing the connected repository++Disconnect the existing integration before connecting a different repository. This preserves local tasks but removes their old external links and any unfinished import progress. Reconnecting the same verified repository, including after a rename or reinstall, preserves its links and project preferences. Legacy integrations without a verified numeric identity can be reverified for the same repository name; review their existing links before enabling synchronization.+## Testing the IntegrationAfter connecting a repository, test the integration thoroughly:@@ -290,4 +294,14 @@ If you need to connect repositories from multiple GitHub organizations:----**Having issues?** Check our [troubleshooting guide](/core/integrations/github/troubleshooting) for common problems and solutions.\ No newline at end of file+**Having issues?** Check our [troubleshooting guide](/core/integrations/github/troubleshooting) for common problems and solutions.++## Import existing issues++Select **Import Issues** in the project's GitHub integration settings to import open issues and their labels and comments. Existing linked tasks are updated; matching open pull requests are linked to their tasks. Bot comments are excluded.++Large imports run in small, sequential steps. Keep the page open until the completion message appears. If the connection fails or you close the page, the saved progress remains available: return to these settings and select **Resume import**. The completion message lists created, updated and skipped issues. A skipped issue may have lost its source or linked task during the import, or have a legacy link to another project.++Each run uses its start time as a cutoff for newly created issues, pull requests and comments. Label and comment counts are bounded by the first page observed for each issue, so additions during an import may require a new import after the current run completes. GitHub can change during a run; this is not an exact point-in-time snapshot. Reimporting does not duplicate already linked tasks or comments.++If GitHub is unavailable or rate limits requests, wait before resuming. Reconnect the integration if its repository verification no longer succeeds. Unlinking the integration also removes saved import progress; already imported tasks remain.diff --git a/apps/docs/core/integrations/mcp.mdx b/apps/docs/core/integrations/mcp.mdxindex d5dff821e..1344cb44b 100644--- a/apps/docs/core/integrations/mcp.mdx+++ b/apps/docs/core/integrations/mcp.mdx@@ -32,6 +32,29 @@ stateless and self-contained, while 2025-era clients keep the sessionful`initialize` flow. See [MCP 2026-07-28 stateless compatibility](/core/integrations/mcp-stateless)for the exact contract, tests, Codex configuration, limitations, and rollback.+### OAuth request limits++The HTTP OAuth endpoints accept bodies up to 32 KiB and URLs up to 8 KiB.+Client registration accepts at most 10 redirect URIs. Request bodies must arrive+within five seconds. Each API process allows up to 16 concurrent requests in+each of the registration, authorization, and token endpoint groups.++Instances sharing a database also share OAuth storage and issuance limits:++| State | Stored entries | New entries per minute | Pending entries per client |+| --- | --- | --- | --- |+| Registered clients | 1,000 | 60 | — |+| Authorization requests | 10,000 | 300 | 20 |+| Authorization codes | 10,000 | 300 | 20 |++When capacity is exhausted, the endpoint returns HTTP 429 with `Retry-After`.+Clients should wait before retrying. Existing, unexpired entries are retained;+an approval that cannot issue a code leaves its authorization request available+for retry until it expires. Expired entries are cleaned up in bounded batches+when new state is created, so a previously oversized store may need multiple+attempts before accepting new entries. These limits complement reverse-proxy+connection and request limits for internet-facing installations.+## Stdio packageThe `@kaneo/mcp` package runs a local stdio MCP server and authenticates with Kaneo using device authorization. Use this when your MCP client requires stdio transport.diff --git a/apps/docs/core/social-providers/custom-oauth.mdx b/apps/docs/core/social-providers/custom-oauth.mdxindex 1279acaee..d4940ecdd 100644--- a/apps/docs/core/social-providers/custom-oauth.mdx+++ b/apps/docs/core/social-providers/custom-oauth.mdx@@ -178,9 +178,9 @@ This will automatically discover the authorization, token, and userinfo endpoint## Account linking-When a user signs in with this provider using an email that already belongs to a Kaneo account (for example one created with email and password), Kaneo can link the OIDC identity to that existing account instead of failing with `error=account_not_linked`. GitHub, Google, and Discord are trusted because they verify email ownership. Kaneo also treats the configured custom provider as trusted, but it cannot verify the provider's email claims itself. Only use a custom provider that guarantees ownership of every returned email address; otherwise, an attacker-controlled email claim could be linked to an existing verified account.+When a user signs in with this provider using an email that already belongs to a Kaneo account, Kaneo can link the OIDC identity to that account. The provider must return a verified email claim; being configured does not make an unverified email trusted. Configure your identity provider to return `email_verified: true` only after establishing ownership of the email address. An unverified claim cannot satisfy email-based invitation matching either.-For safety, Kaneo only links to an existing local account if that account's email has already been verified. This prevents someone from pre-registering another person's email with a password account and retaining access after the real owner signs in through OIDC. If your instance allows password registration alongside OIDC, consider setting `DISABLE_PASSWORD_REGISTRATION=true` or requiring email verification for password users to avoid account-linking surprises.+For safety, Kaneo only links to an existing local account if that account's email has already been verified. This prevents someone from pre-registering another person's email with a password account and retaining access after the real owner signs in through OIDC. If your instance allows password registration alongside OIDC, consider setting `DISABLE_PASSWORD_REGISTRATION=true` (which also blocks new OTP, magic-link and guest accounts) or requiring email verification for password users to avoid account-linking surprises.On existing installations, local accounts created before this requirement may still have an unverified email. Those users will receive `error=account_not_linked` until they verify the local account. Before enforcing SSO-only access, keep the login form available so affected users can sign in with an email OTP or magic link, which verifies the email. If users are already locked out, temporarily set `DISABLE_LOGIN_FORM=false` and `CUSTOM_OAUTH_AUTO_LOGIN=false`, restart Kaneo, and have them complete an email sign-in before enabling SSO-only access again.diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex f4f27f221..e97adbd73 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -40,248 +40,63 @@"hasAdmin"]},- "Config": {- "type": "object",- "properties": {- "disableRegistration": {- "type": "boolean"- },- "disablePasswordRegistration": {- "type": "boolean"- },- "disableEmailOtpSignIn": {- "type": "boolean"- },- "disableWorkspaceCreation": {- "type": "boolean"- },- "isDemoMode": {- "type": "boolean"- },- "hasSmtp": {- "type": "boolean"- },- "hasGithubSignIn": {- "type": "boolean"- },- "hasGoogleSignIn": {- "type": "boolean"- },- "hasDiscordSignIn": {- "type": "boolean"- },- "hasCustomOAuth": {- "type": "boolean"- },- "hasGuestAccess": {- "type": "boolean"- },- "disableLoginForm": {- "type": "boolean"- },- "customOAuthAutoLogin": {- "type": "boolean"- },- "customOAuthLogoutUrl": {- "type": [- "string",- "null"- ]- },- "billingEnabled": {- "type": "boolean"- }- },- "required": [- "disableRegistration",- "disablePasswordRegistration",- "disableEmailOtpSignIn",- "disableWorkspaceCreation",- "isDemoMode",- "hasSmtp",- "hasGithubSignIn",- "hasGoogleSignIn",- "hasDiscordSignIn",- "hasCustomOAuth",- "hasGuestAccess",- "disableLoginForm",- "customOAuthAutoLogin",- "customOAuthLogoutUrl",- "billingEnabled"- ]- },- "McpClientRegistration": {- "type": "object",- "properties": {- "client_id": {- "type": "string"- },- "client_id_issued_at": {- "type": "number"- },- "redirect_uris": {- "type": "array",- "items": {- "type": "string"- }- },- "client_name": {- "type": "string"- },- "token_endpoint_auth_method": {- "type": "string",- "enum": [- "none"- ]- },- "grant_types": {- "type": "array",- "items": {- "type": "string",- "enum": [- "authorization_code"- ]- }- },- "response_types": {- "type": "array",- "items": {- "type": "string",- "enum": [- "code"- ]- }- }- },- "required": [- "client_id",- "client_id_issued_at",- "redirect_uris",- "token_endpoint_auth_method",- "grant_types",- "response_types"- ]- },- "OAuthError": {- "type": "object",- "properties": {- "error": {- "type": "string"- },- "error_description": {- "type": "string"- }- },- "required": [- "error"- ]- },- "McpAuthorizationRequest": {- "type": "object",- "properties": {- "client_name": {- "type": "string"- },- "redirect_uri": {- "type": "string"- }- },- "required": [- "client_name",- "redirect_uri"- ]- },- "McpAuthorizationDecision": {- "type": "object",- "properties": {- "redirect": {- "type": "string",- "description": "Where to send the browser next: back to the client with a code on approval, or with an error on denial."- }- },- "required": [- "redirect"- ]- },- "OAuthIdToken": {- "type": "object",- "properties": {- "idToken": {- "type": [- "string",- "null"- ],- "description": "The stored id_token for the user's `custom` OAuth account, or null when they have no such account."- }- },- "required": [- "idToken"- ]- },- "ProjectListItem": {+ "PublicBoardPage": {"allOf": [{- "$ref": "#/components/schemas/Project"+ "$ref": "#/components/schemas/Board"},{"type": "object","properties": {- "statistics": {- "$ref": "#/components/schemas/ProjectStatistics"- },- "archivedTasks": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BoardTask"- },- "description": "Always empty."- },- "plannedTasks": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BoardTask"- },- "description": "Always empty."- },- "columns": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BoardColumn"- },- "description": "Always empty."+ "pagination": {+ "$ref": "#/components/schemas/BoardPagination"}},"required": [- "statistics",- "archivedTasks",- "plannedTasks",- "columns"+ "pagination"]}]},- "ProjectStatistics": {+ "BoardColumn": {"type": "object","properties": {- "completionPercentage": {- "type": "number"+ "id": {+ "type": "string",+ "description": "The column slug, same as `slug`."},- "totalTasks": {- "type": "number"+ "slug": {+ "type": "string"},- "dueDate": {+ "name": {+ "type": "string"+ },+ "icon": {"type": ["string","null"- ],- "format": "date-time",- "description": "The soonest due date among the project's open tasks."+ ]+ },+ "isFinal": {+ "type": "boolean"+ },+ "position": {+ "type": "number"+ },+ "tasks": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BoardTask"+ }}},"required": [- "completionPercentage",- "totalTasks",- "dueDate"+ "id",+ "slug",+ "name",+ "icon",+ "isFinal",+ "tasks"]},"BoardTask": {@@ -305,6 +120,10 @@"null"]},+ "descriptionDeferred": {+ "type": "boolean",+ "description": "True when the list omits a large description; load the task detail or description pages to read it. Do not replace stored text with this null summary."+ },"status": {"type": "string"},@@ -472,128 +291,41 @@"updatedAt"]},- "BoardColumn": {+ "BoardPagination": {"type": "object","properties": {- "id": {- "type": "string",- "description": "The column slug, same as `slug`."- },- "slug": {- "type": "string"- },- "name": {- "type": "string"- },- "icon": {- "type": [- "string",- "null"- ]- },- "isFinal": {- "type": "boolean"- },- "tasks": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BoardTask"- }- }- },- "required": [- "id",- "slug",- "name",- "icon",- "isFinal",- "tasks"- ]- },- "Project": {- "type": "object",- "properties": {- "id": {- "type": "string"- },- "workspaceId": {- "type": "string"- },- "slug": {- "type": "string",- "description": "Short prefix used in task identifiers, e.g. KAN-12."- },- "icon": {- "type": [- "string",- "null"- ]- },- "name": {- "type": "string"- },- "description": {- "type": [- "string",- "null"- ]+ "total": {+ "type": "number"},- "createdAt": {- "type": "string",- "format": "date-time"+ "page": {+ "type": "number"},- "isPublic": {- "type": [- "boolean",- "null"- ],- "description": "When true the project's board is readable without signing in, via /api/public-project/{id}."+ "pageSize": {+ "type": "number"},- "archivedAt": {- "type": [- "string",- "null"- ],- "format": "date-time",- "description": "Non-null once archived; archived projects are hidden by default."+ "totalPages": {+ "type": "number"},- "position": {- "type": "number",- "description": "Sidebar order, ascending."+ "relatedPage": {+ "type": "number"},- "lastTaskNumber": {- "type": "number",- "description": "Highest task number issued in this project; the next task gets this plus one."- }- },- "required": [- "id",- "workspaceId",- "slug",- "icon",- "name",- "description",- "createdAt",- "isPublic",- "archivedAt",- "position",- "lastTaskNumber"- ]- },- "BoardResponse": {- "type": "object",- "properties": {- "data": {- "$ref": "#/components/schemas/Board"+ "relatedPageSize": {+ "type": "number"},- "pagination": {- "$ref": "#/components/schemas/BoardPagination"+ "relatedTotalPages": {+ "type": "number"}},"required": [- "data",- "pagination"- ]+ "total",+ "page",+ "pageSize",+ "totalPages",+ "relatedPage",+ "relatedPageSize",+ "relatedTotalPages"+ ],+ "description": "Always paginated: 50 tasks by default, at most 100 per page. Continue through totalPages to retrieve all tasks. For each task page, follow relatedPage through relatedTotalPages to retrieve all labels, external links and columns (100 related rows per kind per request, plus up to 100 columns needed to represent the tasks)."},"Board": {"type": "object",@@ -619,6 +351,10 @@"null"]},+ "descriptionDeferred": {+ "type": "boolean",+ "description": "True when a project description above 64 KiB is omitted; use project detail or public project description pages for full text."+ },"isPublic": {"type": ["boolean",@@ -660,401 +396,284 @@"plannedTasks"]},- "BoardPagination": {+ "TaskDescriptionPage": {"type": "object","properties": {- "total": {- "type": "number"- },- "page": {- "type": "number"+ "content": {+ "type": "string"},- "pageSize": {- "type": "number"+ "version": {+ "type": "string"},- "totalPages": {- "type": "number"+ "nextOffset": {+ "type": [+ "number",+ "null"+ ]}},"required": [- "total",- "page",- "pageSize",- "totalPages"- ],- "description": "When no page/limit is given, everything is returned on a single page."+ "content",+ "version",+ "nextOffset"+ ]},- "BulkTaskResult": {+ "Config": {"type": "object","properties": {- "success": {+ "disableRegistration": {"type": "boolean"},- "updatedCount": {- "type": "number"- }- },- "required": [- "success",- "updatedCount"- ]- },- "Task": {- "type": "object",- "properties": {- "id": {- "type": "string"+ "disablePasswordRegistration": {+ "type": "boolean"},- "projectId": {- "type": "string"+ "disableEmailOtpSignIn": {+ "type": "boolean"},- "position": {- "type": [- "number",- "null"- ],- "description": "Order within its column, ascending."+ "disableWorkspaceCreation": {+ "type": "boolean"},- "number": {- "type": [- "number",- "null"- ],- "description": "Per-project counter shown as {projectSlug}-{number}."+ "isDemoMode": {+ "type": "boolean"},- "userId": {- "type": [- "string",- "null"- ],- "description": "The assignee, if any."+ "hasSmtp": {+ "type": "boolean"},- "title": {- "type": "string"+ "hasGithubSignIn": {+ "type": "boolean"},- "description": {- "type": [- "string",- "null"- ]+ "hasGoogleSignIn": {+ "type": "boolean"},- "status": {- "type": "string",- "description": "The slug of the column the task sits in."+ "hasDiscordSignIn": {+ "type": "boolean"},- "priority": {- "type": "string",- "description": "One of: no-priority, low, medium, high, urgent."+ "hasCustomOAuth": {+ "type": "boolean"},- "startDate": {- "type": [- "string",- "null"- ],- "format": "date-time"+ "hasGuestAccess": {+ "type": "boolean"},- "dueDate": {+ "disableLoginForm": {+ "type": "boolean"+ },+ "customOAuthAutoLogin": {+ "type": "boolean"+ },+ "customOAuthLogoutUrl": {"type": ["string","null"- ],- "format": "date-time"- },- "createdAt": {- "type": "string",- "format": "date-time"+ ]},- "customFields": {- "type": "array",- "items": {- "type": "object",- "properties": {- "fieldId": {- "type": "string"- },- "value": {- "type": "string"- }- },- "required": [- "fieldId",- "value"- ]- }+ "billingEnabled": {+ "type": "boolean"}},"required": [- "id",- "projectId",- "position",- "number",- "userId",- "title",- "description",- "status",- "priority",- "startDate",- "dueDate",- "createdAt"- ]- },- "TaskWithAssignee": {- "allOf": [- {- "$ref": "#/components/schemas/Task"- },- {- "type": "object",- "properties": {- "assigneeName": {- "type": [- "string",- "null"- ]- },- "assigneeId": {- "type": [- "string",- "null"- ]- }- },- "required": [- "assigneeName",- "assigneeId"- ]- }+ "disableRegistration",+ "disablePasswordRegistration",+ "disableEmailOtpSignIn",+ "disableWorkspaceCreation",+ "isDemoMode",+ "hasSmtp",+ "hasGithubSignIn",+ "hasGoogleSignIn",+ "hasDiscordSignIn",+ "hasCustomOAuth",+ "hasGuestAccess",+ "disableLoginForm",+ "customOAuthAutoLogin",+ "customOAuthLogoutUrl",+ "billingEnabled"]},- "MoveTaskResult": {+ "McpClientRegistration": {"type": "object","properties": {- "task": {- "$ref": "#/components/schemas/Task"- },- "sourceProjectId": {+ "client_id": {"type": "string"},- "destinationProjectId": {- "type": "string"- }- },- "required": [- "task",- "sourceProjectId",- "destinationProjectId"- ]- },- "TaskExport": {- "type": "object",- "properties": {- "project": {- "$ref": "#/components/schemas/TaskExportProject"+ "client_id_issued_at": {+ "type": "number"},- "tasks": {+ "redirect_uris": {"type": "array","items": {- "$ref": "#/components/schemas/ExportedTask"+ "type": "string"}- }- },- "required": [- "project",- "tasks"- ]- },- "TaskExportProject": {- "type": "object",- "properties": {- "name": {- "type": "string"},- "slug": {+ "client_name": {"type": "string"},- "description": {- "type": [- "string",- "null"+ "token_endpoint_auth_method": {+ "type": "string",+ "enum": [+ "none"]},- "exportedAt": {- "type": "string",- "format": "date-time"+ "grant_types": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "authorization_code"+ ]+ }+ },+ "response_types": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "code"+ ]+ }}},"required": [- "name",- "slug",- "description",- "exportedAt"+ "client_id",+ "client_id_issued_at",+ "redirect_uris",+ "token_endpoint_auth_method",+ "grant_types",+ "response_types"]},- "ExportedTask": {+ "OAuthError": {"type": "object","properties": {- "title": {- "type": "string"- },- "description": {- "type": "string"- },- "status": {+ "error": {"type": "string"},- "priority": {+ "error_description": {"type": "string"- },- "dueDate": {- "type": [- "string",- "null"- ],- "format": "date-time"- },- "startDate": {- "type": [- "string",- "null"- ],- "format": "date-time"- },- "userId": {- "type": [- "string",- "null"- ]- },- "labels": {- "type": "array",- "items": {- "$ref": "#/components/schemas/ExportedTaskLabel"- },- "description": "Label names and colors, without their ids."}},"required": [- "title",- "description",- "status",- "priority",- "dueDate",- "startDate",- "userId",- "labels"+ "error"]},- "ExportedTaskLabel": {+ "McpAuthorizationRequest": {"type": "object","properties": {- "name": {+ "client_name": {"type": "string"},- "color": {+ "redirect_uri": {"type": "string"}},"required": [- "name",- "color"+ "client_name",+ "redirect_uri"]},- "TaskImportResult": {+ "McpAuthorizationDecision": {"type": "object","properties": {- "results": {- "$ref": "#/components/schemas/TaskImportSummary"+ "redirect": {+ "type": "string",+ "description": "Where to send the browser next: back to the client with a code on approval, or with an error on denial."}},"required": [- "results"+ "redirect"]},- "TaskImportSummary": {+ "OAuthIdToken": {"type": "object","properties": {- "total": {- "type": "number"- },- "successful": {- "type": "number"- },- "failed": {- "type": "number"- },- "tasks": {- "type": "array",- "items": {},- "description": "Per-task outcome, each carrying a success flag."+ "idToken": {+ "type": [+ "string",+ "null"+ ],+ "description": "The stored id_token for the user's `custom` OAuth account, or null when they have no such account."}},"required": [- "total",- "successful",- "failed",- "tasks"+ "idToken"]},- "TaskImageUpload": {- "type": "object",- "properties": {- "key": {- "type": "string",- "description": "Object key to send back to the finalize route."- },- "uploadUrl": {- "type": "string",- "description": "Presigned URL to PUT the image bytes to."+ "ProjectListItem": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Project"},- "headers": {+ {"type": "object",- "additionalProperties": {- "type": "string"- },- "description": "Headers that must accompany the upload request, including Content-Type."- }- },- "required": [- "key",- "uploadUrl",- "headers"+ "properties": {+ "statistics": {+ "$ref": "#/components/schemas/ProjectStatistics"+ },+ "archivedTasks": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BoardTask"+ },+ "description": "Always empty."+ },+ "plannedTasks": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BoardTask"+ },+ "description": "Always empty."+ },+ "columns": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BoardColumn"+ },+ "description": "Always empty."+ }+ },+ "required": [+ "statistics",+ "archivedTasks",+ "plannedTasks",+ "columns"+ ]+ }]},- "TaskImageAsset": {+ "ProjectStatistics": {"type": "object","properties": {- "id": {- "type": "string"+ "completionPercentage": {+ "type": "number"},- "url": {- "type": "string",- "description": "Where the stored image can be read back from."+ "totalTasks": {+ "type": "number"+ },+ "dueDate": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time",+ "description": "The soonest due date among the project's open tasks."}},"required": [- "id",- "url"+ "completionPercentage",+ "totalTasks",+ "dueDate"]},- "Column": {+ "Project": {"type": "object","properties": {"id": {"type": "string"},- "projectId": {- "type": "string"- },- "name": {+ "workspaceId": {"type": "string"},"slug": {"type": "string",- "description": "Stable identifier derived from the name; tasks store this as their status."- },- "position": {- "type": "number",- "description": "Board order, ascending. Columns are always returned sorted by it."+ "description": "Short prefix used in task identifiers, e.g. KAN-12."},"icon": {"type": [@@ -1062,179 +681,226 @@"null"]},- "color": {+ "name": {+ "type": "string"+ },+ "description": {"type": ["string","null"]},- "isFinal": {- "type": "boolean",- "description": "Marks the column as a done state, which stops overdue reminders for tasks in it."- },"createdAt": {"type": "string","format": "date-time"},- "updatedAt": {- "type": "string",- "format": "date-time"+ "isPublic": {+ "type": [+ "boolean",+ "null"+ ],+ "description": "When true the project's board is readable without signing in, via /api/public-project/{id}."+ },+ "archivedAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time",+ "description": "Non-null once archived; archived projects are hidden by default."+ },+ "position": {+ "type": "number",+ "description": "Sidebar order, ascending."+ },+ "lastTaskNumber": {+ "type": "number",+ "description": "Highest task number issued in this project; the next task gets this plus one."}},"required": ["id",- "projectId",- "name",+ "workspaceId","slug",- "position","icon",- "color",- "isFinal",+ "name",+ "description","createdAt",- "updatedAt"+ "isPublic",+ "archivedAt",+ "position",+ "lastTaskNumber"]},- "Activity": {+ "TaskDescriptionMatches": {"type": "object","properties": {- "id": {- "type": "string"+ "ids": {+ "type": "array",+ "items": {+ "type": "string"+ }},- "taskId": {- "type": "string"+ "nextCursor": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "ids",+ "nextCursor"+ ]+ },+ "BoardResponse": {+ "type": "object",+ "properties": {+ "data": {+ "$ref": "#/components/schemas/Board"},- "type": {- "type": "string",- "description": "One of: comment, task, create, status_changed, priority_changed, assignee_changed, unassigned, due_date_changed, title_changed, description_changed."+ "pagination": {+ "$ref": "#/components/schemas/BoardPagination"+ }+ },+ "required": [+ "data",+ "pagination"+ ]+ },+ "BulkTaskResult": {+ "type": "object",+ "properties": {+ "success": {+ "type": "boolean"},- "createdAt": {- "type": "string",- "format": "date-time"+ "updatedCount": {+ "type": "number"+ }+ },+ "required": [+ "success",+ "updatedCount"+ ]+ },+ "Task": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"},- "updatedAt": {- "type": "string",- "format": "date-time"+ "projectId": {+ "type": "string"},- "userId": {+ "position": {"type": [- "string",+ "number","null"- ]+ ],+ "description": "Order within its column, ascending."},- "content": {+ "number": {"type": [- "string",+ "number","null"- ]- },- "eventData": {- "description": "Type-specific payload, e.g. { oldStatus, newStatus } for status_changed. Null for plain comments."+ ],+ "description": "Per-project counter shown as {projectSlug}-{number}."},- "externalUserName": {+ "userId": {"type": ["string","null"],- "description": "Set when the activity was imported from another tool."+ "description": "The assignee, if any."},- "externalUserAvatar": {+ "title": {+ "type": "string"+ },+ "description": {"type": ["string","null"]},- "externalSource": {+ "descriptionDeferred": {+ "type": "boolean",+ "description": "True when the list omits a large description; load the task detail or description pages to read it. Do not replace stored text with this null summary."+ },+ "status": {+ "type": "string",+ "description": "The slug of the column the task sits in."+ },+ "priority": {+ "type": "string",+ "description": "One of: no-priority, low, medium, high, urgent."+ },+ "startDate": {"type": ["string","null"],- "description": "The tool it was imported from, e.g. planka, trello, jira."+ "format": "date-time"},- "externalUrl": {+ "dueDate": {"type": ["string","null"- ]- }- },- "required": [- "id",- "taskId",- "type",- "createdAt",- "updatedAt",- "userId",- "content",- "externalUserName",- "externalUserAvatar",- "externalSource",- "externalUrl"- ]- },- "Comment": {- "type": "object",- "properties": {- "id": {- "type": "string"- },- "taskId": {- "type": "string"- },- "userId": {- "type": "string"- },- "content": {- "type": "string"+ ],+ "format": "date-time"},"createdAt": {"type": "string","format": "date-time"},- "updatedAt": {- "type": "string",- "format": "date-time"- },- "user": {- "$ref": "#/components/schemas/CommentAuthor"+ "customFields": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "fieldId": {+ "type": "string"+ },+ "value": {+ "type": "string"+ }+ },+ "required": [+ "fieldId",+ "value"+ ]+ }}},"required": ["id",- "taskId",+ "projectId",+ "position",+ "number","userId",- "content",- "createdAt",- "updatedAt",- "user"- ]- },- "CommentAuthor": {- "type": "object",- "properties": {- "name": {- "type": "string"- },- "image": {- "type": [- "string",- "null"- ]- }- },- "required": [- "name",- "image"+ "title",+ "description",+ "status",+ "priority",+ "startDate",+ "dueDate",+ "createdAt"]},- "TimeEntryWithUser": {+ "TaskWithAssignee": {"allOf": [{- "$ref": "#/components/schemas/TimeEntry"+ "$ref": "#/components/schemas/Task"},{"type": "object","properties": {- "userName": {+ "assigneeName": {+ "type": [+ "string",+ "null"+ ]+ },+ "assigneeId": {"type": ["string","null"@@ -1242,387 +908,371 @@}},"required": [- "userName"+ "assigneeName",+ "assigneeId"]}]},- "TimeEntry": {+ "MoveTaskResult": {"type": "object","properties": {- "id": {- "type": "string"+ "task": {+ "$ref": "#/components/schemas/Task"},- "taskId": {+ "sourceProjectId": {"type": "string"},- "userId": {- "type": [- "string",- "null"- ],- "description": "Null once the user who logged the time has been removed."- },- "description": {- "type": [- "string",- "null"- ]- },- "startTime": {- "type": "string",- "format": "date-time"- },- "endTime": {- "type": [- "string",- "null"- ],- "format": "date-time",- "description": "Null while the timer is still running."- },- "duration": {- "type": [- "number",- "null"- ],- "description": "Elapsed seconds, filled in once the entry has an endTime."- },- "createdAt": {- "type": "string",- "format": "date-time"- },- "updatedAt": {- "type": "string",- "format": "date-time"+ "destinationProjectId": {+ "type": "string"}},"required": [- "id",- "taskId",- "userId",- "description",- "startTime",- "endTime",- "duration",- "createdAt",- "updatedAt"+ "task",+ "sourceProjectId",+ "destinationProjectId"]},- "Label": {+ "TaskExport": {"type": "object","properties": {- "id": {- "type": "string"+ "project": {+ "$ref": "#/components/schemas/TaskExportProject"},+ "tasks": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ExportedTask"+ }+ }+ },+ "required": [+ "project",+ "tasks"+ ]+ },+ "TaskExportProject": {+ "type": "object",+ "properties": {"name": {"type": "string"},- "color": {+ "slug": {"type": "string"},- "createdAt": {- "type": "string",- "format": "date-time"- },- "updatedAt": {- "type": "string",- "format": "date-time"- },- "taskId": {+ "description": {"type": ["string","null"]},- "workspaceId": {- "type": [- "string",- "null"- ]+ "exportedAt": {+ "type": "string",+ "format": "date-time"}},"required": [- "id","name",- "color",- "createdAt",- "updatedAt",- "taskId",- "workspaceId"+ "slug",+ "description",+ "exportedAt"]},- "Notification": {+ "ExportedTask": {"type": "object","properties": {- "id": {+ "title": {"type": "string"},- "userId": {+ "description": {"type": "string"},- "title": {- "type": [- "string",- "null"- ]+ "status": {+ "type": "string"},- "content": {+ "priority": {+ "type": "string"+ },+ "dueDate": {"type": ["string","null"],- "description": "Free-text body. Null for generated notifications, whose text the client renders from type and eventData."- },- "type": {- "type": "string",- "description": "One of: info, task_created, workspace_created, task_status_changed, task_assignee_changed, time_entry_created, due_date_reminder, task_overdue, task_mention, task_comment."- },- "eventData": {- "description": "Type-specific payload, e.g. { taskTitle, oldStatus, newStatus, projectId, workspaceId }."- },- "isRead": {- "type": [- "boolean",- "null"- ]+ "format": "date-time"},- "resourceId": {+ "startDate": {"type": ["string","null"],- "description": "The id of the task or workspace the notification points at."+ "format": "date-time"},- "resourceType": {+ "userId": {"type": ["string","null"- ],- "description": "`task` or `workspace`."- },- "createdAt": {- "type": "string",- "format": "date-time"+ ]},- "updatedAt": {- "type": "string",- "format": "date-time"+ "labels": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ExportedTaskLabel"+ },+ "description": "Label names and colors, without their ids."}},"required": [- "id",- "userId","title",- "content",- "type",- "isRead",- "resourceId",- "resourceType",- "createdAt",- "updatedAt"+ "description",+ "status",+ "priority",+ "dueDate",+ "startDate",+ "userId",+ "labels"]},- "NotificationBulkResult": {+ "ExportedTaskLabel": {"type": "object","properties": {- "success": {- "type": "boolean"- }+ "name": {+ "type": "string"+ },+ "color": {+ "type": "string"+ }},"required": [- "success"+ "name",+ "color"]},- "NotificationPreferences": {+ "TaskImportResult": {"type": "object","properties": {- "emailAddress": {- "type": [- "string",- "null"- ]+ "results": {+ "$ref": "#/components/schemas/TaskImportSummary"+ }+ },+ "required": [+ "results"+ ]+ },+ "TaskImportSummary": {+ "type": "object",+ "properties": {+ "total": {+ "type": "number"},- "emailEnabled": {- "type": "boolean"+ "successful": {+ "type": "number"},- "ntfyEnabled": {- "type": "boolean"+ "failed": {+ "type": "number"},- "ntfyConfigured": {- "type": "boolean"+ "tasks": {+ "type": "array",+ "items": {},+ "description": "Per-task outcome, each carrying a success flag."+ }+ },+ "required": [+ "total",+ "successful",+ "failed",+ "tasks"+ ]+ },+ "TaskImageUpload": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string",+ "description": "Object key to send back to the finalize route."},- "ntfyServerUrl": {+ "uploadUrl": {+ "type": "string",+ "description": "Presigned URL to PUT the image bytes to."+ },+ "headers": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ },+ "description": "Headers that must accompany the upload request, including Content-Type."+ }+ },+ "required": [+ "key",+ "uploadUrl",+ "headers"+ ]+ },+ "TaskImageAsset": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "url": {+ "type": "string",+ "description": "Where the stored image can be read back from."+ }+ },+ "required": [+ "id",+ "url"+ ]+ },+ "Column": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "projectId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "slug": {+ "type": "string",+ "description": "Stable identifier derived from the name; tasks store this as their status."+ },+ "position": {+ "type": "number",+ "description": "Board order, ascending. Columns are always returned sorted by it."+ },+ "icon": {"type": ["string","null"]},- "ntfyTopic": {+ "color": {"type": ["string","null"]},- "ntfyTokenConfigured": {- "type": "boolean"+ "isFinal": {+ "type": "boolean",+ "description": "Marks the column as a done state, which stops overdue reminders for tasks in it."},- "maskedNtfyToken": {- "type": [- "string",- "null"- ]+ "createdAt": {+ "type": "string",+ "format": "date-time"},- "gotifyEnabled": {- "type": "boolean"+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "projectId",+ "name",+ "slug",+ "position",+ "icon",+ "color",+ "isFinal",+ "createdAt",+ "updatedAt"+ ]+ },+ "Activity": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"},- "gotifyConfigured": {- "type": "boolean"+ "taskId": {+ "type": "string"},- "gotifyServerUrl": {+ "type": {+ "type": "string",+ "description": "One of: comment, task, create, status_changed, priority_changed, assignee_changed, unassigned, due_date_changed, title_changed, description_changed."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ },+ "userId": {"type": ["string","null"]},- "gotifyTokenConfigured": {- "type": "boolean"- },- "maskedGotifyToken": {+ "content": {"type": ["string","null"]},- "webhookEnabled": {- "type": "boolean"- },- "webhookConfigured": {- "type": "boolean"+ "eventData": {+ "description": "Type-specific payload, e.g. { oldStatus, newStatus } for status_changed. Null for plain comments."},- "webhookUrl": {+ "externalUserName": {"type": ["string","null"- ]- },- "webhookSecretConfigured": {- "type": "boolean"+ ],+ "description": "Set when the activity was imported from another tool."},- "maskedWebhookSecret": {+ "externalUserAvatar": {"type": ["string","null"]},- "taskAssignmentEnabled": {- "type": "boolean"- },- "taskCommentEnabled": {- "type": "boolean"- },- "taskStatusChangeEnabled": {- "type": "boolean"- },- "dueDateReminderEnabled": {- "type": "boolean"- },- "dueDateReminderLeadTimeMinutes": {- "type": "number",- "description": "How long before a due date the reminder fires, in minutes."- },- "workspaces": {- "type": "array",- "items": {- "$ref": "#/components/schemas/NotificationPreferenceWorkspaceRule"- },- "description": "Per-workspace overrides. A workspace with no rule follows the global settings."- },- "createdAt": {+ "externalSource": {"type": ["string","null"],- "format": "date-time"+ "description": "The tool it was imported from, e.g. planka, trello, jira."},- "updatedAt": {+ "externalUrl": {"type": ["string","null"- ],- "format": "date-time"+ ]}},"required": [- "emailAddress",- "emailEnabled",- "ntfyEnabled",- "ntfyConfigured",- "ntfyServerUrl",- "ntfyTopic",- "ntfyTokenConfigured",- "maskedNtfyToken",- "gotifyEnabled",- "gotifyConfigured",- "gotifyServerUrl",- "gotifyTokenConfigured",- "maskedGotifyToken",- "webhookEnabled",- "webhookConfigured",- "webhookUrl",- "webhookSecretConfigured",- "maskedWebhookSecret",- "taskAssignmentEnabled",- "taskCommentEnabled",- "taskStatusChangeEnabled",- "dueDateReminderEnabled",- "dueDateReminderLeadTimeMinutes",- "workspaces",+ "id",+ "taskId",+ "type","createdAt",- "updatedAt"- ]- },- "NotificationPreferenceWorkspaceRule": {+ "updatedAt",+ "userId",+ "content",+ "externalUserName",+ "externalUserAvatar",+ "externalSource",+ "externalUrl"+ ]+ },+ "Comment": {"type": "object","properties": {"id": {"type": "string"},- "workspaceId": {+ "taskId": {"type": "string"},- "workspaceName": {+ "userId": {"type": "string"},- "isActive": {- "type": "boolean",- "description": "Turn all notifications for this workspace on or off."- },- "emailEnabled": {- "type": "boolean"- },- "ntfyEnabled": {- "type": "boolean"- },- "gotifyEnabled": {- "type": "boolean"- },- "webhookEnabled": {- "type": "boolean"- },- "projectMode": {- "type": "string",- "enum": [- "all",- "selected"- ],- "description": "`all` notifies for every project in the workspace; `selected` restricts it to selectedProjectIds."- },- "selectedProjectIds": {- "type": "array",- "items": {- "type": "string"- }+ "content": {+ "type": "string"},"createdAt": {"type": "string",@@ -1631,397 +1281,461 @@"updatedAt": {"type": "string","format": "date-time"+ },+ "user": {+ "$ref": "#/components/schemas/CommentAuthor"}},"required": ["id",- "workspaceId",- "workspaceName",- "isActive",- "emailEnabled",- "ntfyEnabled",- "gotifyEnabled",- "webhookEnabled",- "projectMode",- "selectedProjectIds",+ "taskId",+ "userId",+ "content","createdAt",- "updatedAt"+ "updatedAt",+ "user"]},- "SearchResponse": {+ "CommentAuthor": {"type": "object","properties": {- "results": {- "type": "array",- "items": {- "$ref": "#/components/schemas/SearchResult"- }- },- "totalCount": {- "type": "number",- "description": "Total matches found before the `limit` slice, so a caller can tell that more exist."+ "name": {+ "type": "string"},- "searchQuery": {- "type": "string",- "description": "The query that was run."+ "image": {+ "type": [+ "string",+ "null"+ ]}},"required": [- "results",- "totalCount",- "searchQuery"+ "name",+ "image"]},- "SearchResult": {+ "TimeEntryWithUser": {+ "allOf": [+ {+ "$ref": "#/components/schemas/TimeEntry"+ },+ {+ "type": "object",+ "properties": {+ "userName": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "userName"+ ]+ }+ ]+ },+ "TimeEntry": {"type": "object","properties": {"id": {"type": "string"},- "type": {- "type": "string",- "enum": [- "task",- "project",- "workspace",- "comment",- "activity"- ]- },- "title": {+ "taskId": {"type": "string"},+ "userId": {+ "type": [+ "string",+ "null"+ ],+ "description": "Null once the user who logged the time has been removed."+ },"description": {- "type": "string"+ "type": [+ "string",+ "null"+ ]},- "content": {+ "startTime": {"type": "string",- "description": "Matched body text, for comment and activity results. Activities get a rendered summary such as `changed status from Todo to In Progress`."- },- "projectId": {- "type": "string"+ "format": "date-time"},- "projectName": {- "type": "string"+ "endTime": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time",+ "description": "Null while the timer is still running."},- "projectSlug": {- "type": "string"+ "duration": {+ "type": [+ "number",+ "null"+ ],+ "description": "Elapsed seconds, filled in once the entry has an endTime."},- "workspaceId": {- "type": "string"+ "createdAt": {+ "type": "string",+ "format": "date-time"},- "workspaceName": {+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "taskId",+ "userId",+ "description",+ "startTime",+ "endTime",+ "duration",+ "createdAt",+ "updatedAt"+ ]+ },+ "Label": {+ "type": "object",+ "properties": {+ "id": {"type": "string"},- "userId": {+ "name": {"type": "string"},- "userName": {+ "color": {"type": "string"},"createdAt": {"type": "string","format": "date-time"},- "relevanceScore": {- "type": "number",- "description": "Higher is a better match. Results are sorted by score, then by createdAt descending."+ "updatedAt": {+ "type": "string",+ "format": "date-time"},- "taskNumber": {- "type": "number"+ "deletionStartedAt": {+ "type": "string",+ "format": "date-time"},- "priority": {- "type": "string"+ "taskId": {+ "type": [+ "string",+ "null"+ ]},- "status": {- "type": "string"+ "workspaceId": {+ "type": [+ "string",+ "null"+ ]}},"required": ["id",- "type",- "title",+ "name",+ "color","createdAt",- "relevanceScore"+ "updatedAt",+ "taskId",+ "workspaceId"]},- "GitHubAppInfo": {+ "PendingLabelDeletion": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Label"+ },+ {+ "type": "object",+ "properties": {+ "pendingDeletion": {+ "type": "boolean",+ "enum": [+ true+ ]+ }+ },+ "required": [+ "pendingDeletion"+ ]+ }+ ]+ },+ "Notification": {"type": "object","properties": {- "appName": {+ "id": {+ "type": "string"+ },+ "userId": {+ "type": "string"+ },+ "title": {+ "type": [+ "string",+ "null"+ ]+ },+ "content": {"type": ["string","null"],- "description": "The configured GitHub App slug, or null when this instance has no App set up."- }- },- "required": [- "appName"- ]- },- "GitHubRepositoryList": {- "type": "object",- "properties": {- "repositories": {- "type": "array",- "items": {- "$ref": "#/components/schemas/GitHubRepository"- },- "description": "Deduplicated across installations, most recently updated first."- },- "installations": {- "type": "array",- "items": {- "$ref": "#/components/schemas/GitHubInstallation"- }- },- "total": {- "type": "number"- }- },- "required": [- "repositories",- "installations",- "total"- ]- },- "GitHubRepository": {- "type": "object",- "properties": {- "id": {- "type": "number"- },- "name": {- "type": "string"- },- "full_name": {- "type": "string"+ "description": "Free-text body. Null for generated notifications, whose text the client renders from type and eventData."},- "private": {- "type": "boolean"+ "type": {+ "type": "string",+ "description": "One of: info, task_created, workspace_created, task_status_changed, task_assignee_changed, time_entry_created, due_date_reminder, task_overdue, task_mention, task_comment."},- "owner": {- "$ref": "#/components/schemas/GitHubRepositoryOwner"+ "eventData": {+ "description": "Type-specific payload, e.g. { taskTitle, oldStatus, newStatus, projectId, workspaceId }."},- "description": {+ "isRead": {"type": [- "string",+ "boolean","null"]},- "html_url": {- "type": "string"+ "resourceId": {+ "type": [+ "string",+ "null"+ ],+ "description": "The id of the task or workspace the notification points at."},- "permissions": {- "$ref": "#/components/schemas/GitHubRepositoryPermissions"+ "resourceType": {+ "type": [+ "string",+ "null"+ ],+ "description": "`task` or `workspace`."},- "updated_at": {+ "createdAt": {"type": "string","format": "date-time"},- "installation_id": {- "type": "number",- "description": "Which App installation this repository came through."+ "updatedAt": {+ "type": "string",+ "format": "date-time"}},"required": ["id",- "name",- "full_name",- "private",- "owner",- "description",- "html_url",- "updated_at",- "installation_id"+ "userId",+ "title",+ "content",+ "type",+ "isRead",+ "resourceId",+ "resourceType",+ "createdAt",+ "updatedAt"]},- "GitHubRepositoryOwner": {+ "NotificationBulkResult": {"type": "object","properties": {- "login": {- "type": "string"- },- "avatar_url": {- "type": "string"- },- "type": {- "type": "string"+ "success": {+ "type": "boolean"}},"required": [- "login",- "avatar_url",- "type"+ "success"]},- "GitHubRepositoryPermissions": {+ "NotificationPreferences": {"type": "object","properties": {- "admin": {+ "emailAddress": {+ "type": [+ "string",+ "null"+ ]+ },+ "emailEnabled": {"type": "boolean"},- "push": {+ "ntfyEnabled": {"type": "boolean"},- "pull": {+ "ntfyConfigured": {"type": "boolean"- }- },- "required": [- "admin",- "push",- "pull"- ]- },- "GitHubInstallation": {- "type": "object",- "properties": {- "id": {- "type": "number"},- "account": {- "$ref": "#/components/schemas/GitHubInstallationAccount"+ "ntfyServerUrl": {+ "type": [+ "string",+ "null"+ ]},- "repositories": {- "type": "array",- "items": {- "type": "string"- },- "description": "Full names of the repositories under this installation. Empty when listing them failed."- }- },- "required": [- "id",- "account",- "repositories"- ]- },- "GitHubInstallationAccount": {- "type": [- "object",- "null"- ],- "properties": {- "login": {- "type": "string"+ "ntfyTopic": {+ "type": [+ "string",+ "null"+ ]},- "type": {- "type": "string"- }- },- "required": [- "login",- "type"- ]- },- "GitHubVerificationResult": {- "type": "object",- "properties": {- "isInstalled": {+ "ntfyTokenConfigured": {"type": "boolean"},- "installationId": {+ "maskedNtfyToken": {"type": [- "number",+ "string","null"]},- "repositoryExists": {+ "gotifyEnabled": {+ "type": "boolean"+ },+ "gotifyConfigured": {+ "type": "boolean"+ },+ "gotifyServerUrl": {"type": [- "boolean",+ "string","null"]},- "repositoryPrivate": {+ "gotifyTokenConfigured": {+ "type": "boolean"+ },+ "maskedGotifyToken": {"type": [- "boolean",+ "string","null"]},- "permissions": {+ "webhookEnabled": {+ "type": "boolean"+ },+ "webhookConfigured": {+ "type": "boolean"+ },+ "webhookUrl": {"type": [- "object",+ "string","null"- ],- "additionalProperties": {- "type": "string"- },- "description": "The permissions the installation currently grants."+ ]},- "hasRequiredPermissions": {+ "webhookSecretConfigured": {"type": "boolean"},- "missingPermissions": {+ "maskedWebhookSecret": {+ "type": [+ "string",+ "null"+ ]+ },+ "taskAssignmentEnabled": {+ "type": "boolean"+ },+ "taskCommentEnabled": {+ "type": "boolean"+ },+ "taskStatusChangeEnabled": {+ "type": "boolean"+ },+ "dueDateReminderEnabled": {+ "type": "boolean"+ },+ "dueDateReminderLeadTimeMinutes": {+ "type": "number",+ "description": "How long before a due date the reminder fires, in minutes."+ },+ "workspaces": {"type": "array","items": {- "type": "string"+ "$ref": "#/components/schemas/NotificationPreferenceWorkspaceRule"},- "description": "Permissions that must be granted before the link will work."+ "description": "Per-workspace overrides. A workspace with no rule follows the global settings."},- "message": {- "type": "string",- "description": "A human-readable summary to show the user."- },- "settingsUrl": {- "type": "string",- "description": "Where to adjust the installation, when one exists."+ "createdAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time"},- "installationUrl": {- "type": "string",- "description": "Where to install the App, when it is not installed yet."+ "updatedAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time"}},"required": [- "isInstalled",- "installationId",- "repositoryExists",- "repositoryPrivate",- "permissions",- "hasRequiredPermissions",- "missingPermissions",- "message"+ "emailAddress",+ "emailEnabled",+ "ntfyEnabled",+ "ntfyConfigured",+ "ntfyServerUrl",+ "ntfyTopic",+ "ntfyTokenConfigured",+ "maskedNtfyToken",+ "gotifyEnabled",+ "gotifyConfigured",+ "gotifyServerUrl",+ "gotifyTokenConfigured",+ "maskedGotifyToken",+ "webhookEnabled",+ "webhookConfigured",+ "webhookUrl",+ "webhookSecretConfigured",+ "maskedWebhookSecret",+ "taskAssignmentEnabled",+ "taskCommentEnabled",+ "taskStatusChangeEnabled",+ "dueDateReminderEnabled",+ "dueDateReminderLeadTimeMinutes",+ "workspaces",+ "createdAt",+ "updatedAt"]},- "GitHubIntegration": {- "type": [- "object",- "null"- ],+ "NotificationPreferenceWorkspaceRule": {+ "type": "object","properties": {"id": {"type": "string"},- "projectId": {+ "workspaceId": {"type": "string"},- "repositoryOwner": {+ "workspaceName": {"type": "string"},- "repositoryName": {- "type": "string"+ "isActive": {+ "type": "boolean",+ "description": "Turn all notifications for this workspace on or off."},- "installationId": {- "type": [- "number",- "null"- ],- "description": "The GitHub App installation that grants access to the repository."+ "emailEnabled": {+ "type": "boolean"},- "branchPattern": {- "type": "string",- "description": "Template used to name branches created for a task."+ "ntfyEnabled": {+ "type": "boolean"},- "commentTaskLinkOnGitHubIssue": {- "type": "boolean",- "description": "When on, Kaneo comments a link back to the task on the linked GitHub issue."+ "gotifyEnabled": {+ "type": "boolean"},- "isActive": {- "type": [- "boolean",- "null"- ]+ "webhookEnabled": {+ "type": "boolean"+ },+ "projectMode": {+ "type": "string",+ "enum": [+ "all",+ "selected"+ ],+ "description": "`all` notifies for every project in the workspace; `selected` restricts it to selectedProjectIds."+ },+ "selectedProjectIds": {+ "type": "array",+ "items": {+ "type": "string"+ }},"createdAt": {"type": "string",@@ -2034,129 +1748,185 @@},"required": ["id",- "projectId",- "repositoryOwner",- "repositoryName",- "installationId",+ "workspaceId",+ "workspaceName","isActive",+ "emailEnabled",+ "ntfyEnabled",+ "gotifyEnabled",+ "webhookEnabled",+ "projectMode",+ "selectedProjectIds","createdAt","updatedAt"]},- "CreatedGitHubIntegration": {+ "SearchResponse": {+ "type": "object",+ "properties": {+ "results": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/SearchResult"+ }+ },+ "totalCount": {+ "type": "number",+ "description": "Total matches found before the `limit` slice, so a caller can tell that more exist."+ },+ "searchQuery": {+ "type": "string",+ "description": "The query that was run."+ }+ },+ "required": [+ "results",+ "totalCount",+ "searchQuery"+ ]+ },+ "SearchResult": {"type": "object","properties": {"id": {"type": "string"},+ "type": {+ "type": "string",+ "enum": [+ "task",+ "project",+ "workspace",+ "comment",+ "activity"+ ]+ },+ "title": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "content": {+ "type": "string",+ "description": "Matched body text, for comment and activity results. Activities get a rendered summary such as `changed status from Todo to In Progress`."+ },"projectId": {"type": "string"},- "repositoryOwner": {+ "projectName": {"type": "string"},- "repositoryName": {+ "projectSlug": {"type": "string"},- "installationId": {- "type": [- "number",- "null"- ],- "description": "The GitHub App installation that grants access to the repository."+ "workspaceId": {+ "type": "string"},- "branchPattern": {- "type": "string",- "description": "Template used to name branches created for a task."+ "workspaceName": {+ "type": "string"},- "commentTaskLinkOnGitHubIssue": {- "type": "boolean",- "description": "When on, Kaneo comments a link back to the task on the linked GitHub issue."+ "userId": {+ "type": "string"},- "isActive": {- "type": [- "boolean",- "null"- ]+ "userName": {+ "type": "string"},"createdAt": {"type": "string","format": "date-time"},- "updatedAt": {- "type": "string",- "format": "date-time"- }- },- "required": [- "repositoryOwner",- "repositoryName",- "installationId"- ]- },- "GitHubIntegrationNotFound": {- "type": "object",- "properties": {- "error": {+ "relevanceScore": {+ "type": "number",+ "description": "Higher is a better match. Results are sorted by score, then by createdAt descending."+ },+ "taskNumber": {+ "type": "number"+ },+ "priority": {+ "type": "string"+ },+ "status": {"type": "string"}},"required": [- "error"+ "id",+ "type",+ "title",+ "createdAt",+ "relevanceScore"]},- "GitHubDeleteResult": {+ "GitHubAppInfo": {"type": "object","properties": {- "success": {+ "accountConnected": {"type": "boolean"},- "message": {- "type": "string"+ "accountLinkingAvailable": {+ "type": "boolean"+ },+ "appName": {+ "type": [+ "string",+ "null"+ ],+ "description": "The configured GitHub App slug, or null when this instance has no App set up."}},"required": [- "success",- "message"+ "accountConnected",+ "accountLinkingAvailable",+ "appName"]},- "IssueImportResult": {+ "GitHubRepositoryList": {"type": "object","properties": {- "imported": {- "type": "number"- },- "skipped": {- "type": "number",- "description": "Issues that already had a task, or were not importable."- },- "errors": {+ "repositories": {"type": "array","items": {- "type": "string"- }- }- },- "required": [- "imported",- "skipped"- ]- },- "GiteaRepositoryList": {- "type": "object",- "properties": {- "repositories": {+ "$ref": "#/components/schemas/GitHubRepository"+ },+ "description": "Deduplicated across installations, most recently updated first."+ },+ "installations": {"type": "array","items": {- "$ref": "#/components/schemas/GiteaRepository"+ "$ref": "#/components/schemas/GitHubInstallation"}+ },+ "total": {+ "type": "number"+ },+ "nextPage": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "installationPage": {+ "type": "number"+ },+ "repositoryPage": {+ "type": "number"+ }+ },+ "required": [+ "installationPage",+ "repositoryPage"+ ]}},"required": [- "repositories"+ "repositories",+ "installations",+ "total",+ "nextPage"]},- "GiteaRepository": {+ "GitHubRepository": {"type": "object","properties": {"id": {@@ -2168,89 +1938,193 @@"full_name": {"type": "string"},- "owner": {- "$ref": "#/components/schemas/GiteaRepositoryOwner"- },"private": {"type": "boolean"},+ "owner": {+ "$ref": "#/components/schemas/GitHubRepositoryOwner"+ },+ "description": {+ "type": [+ "string",+ "null"+ ]+ },"html_url": {"type": "string"+ },+ "permissions": {+ "$ref": "#/components/schemas/GitHubRepositoryPermissions"+ },+ "updated_at": {+ "type": "string",+ "format": "date-time"+ },+ "installation_id": {+ "type": "number",+ "description": "Which App installation this repository came through."}},"required": ["id","name","full_name",- "owner","private",- "html_url"+ "owner",+ "description",+ "html_url",+ "updated_at",+ "installation_id"]},- "GiteaRepositoryOwner": {+ "GitHubRepositoryOwner": {"type": "object","properties": {"login": {"type": "string"+ },+ "avatar_url": {+ "type": "string"+ },+ "type": {+ "type": "string"}},"required": [- "login"+ "login",+ "avatar_url",+ "type"]},- "GiteaVerificationResult": {+ "GitHubRepositoryPermissions": {"type": "object","properties": {- "isInstalled": {+ "admin": {"type": "boolean"},- "hasRequiredPermissions": {+ "push": {"type": "boolean"},- "repositoryExists": {+ "pull": {+ "type": "boolean"+ }+ },+ "required": [+ "admin",+ "push",+ "pull"+ ]+ },+ "GitHubInstallation": {+ "type": "object",+ "properties": {+ "id": {+ "type": "number"+ },+ "account": {+ "$ref": "#/components/schemas/GitHubInstallationAccount"+ },+ "repositories": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Full names of the repositories under this installation. Empty when listing them failed."+ }+ },+ "required": [+ "id",+ "account",+ "repositories"+ ]+ },+ "GitHubInstallationAccount": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "login": {+ "type": "string"+ },+ "type": {+ "type": "string"+ }+ },+ "required": [+ "login",+ "type"+ ]+ },+ "GitHubVerificationResult": {+ "type": "object",+ "properties": {+ "isInstalled": {"type": "boolean"},+ "installationId": {+ "type": [+ "number",+ "null"+ ]+ },+ "repositoryExists": {+ "type": [+ "boolean",+ "null"+ ]+ },"repositoryPrivate": {"type": ["boolean","null"]},+ "permissions": {+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": {+ "type": "string"+ },+ "description": "The permissions the installation currently grants."+ },+ "hasRequiredPermissions": {+ "type": "boolean"+ },"missingPermissions": {"type": "array","items": {"type": "string"- }+ },+ "description": "Permissions that must be granted before the link will work."},"message": {"type": "string","description": "A human-readable summary to show the user."},- "failureReason": {- "type": [- "string",- "null"- ],- "enum": [- "not_a_gitea_instance",- "redirected",- "repository_not_found",- null- ],- "description": "Why verification failed, when it did. `redirected` usually means the base URL is behind a proxy that rewrites it."+ "settingsUrl": {+ "type": "string",+ "description": "Where to adjust the installation, when one exists."+ },+ "installationUrl": {+ "type": "string",+ "description": "Where to install the App, when it is not installed yet."}},"required": ["isInstalled",- "hasRequiredPermissions",+ "installationId","repositoryExists","repositoryPrivate",+ "permissions",+ "hasRequiredPermissions","missingPermissions",- "message",- "failureReason"+ "message"]},- "GiteaIntegration": {+ "GitHubIntegration": {"type": ["object","null"@@ -2262,33 +2136,32 @@"projectId": {"type": "string"},- "baseUrl": {- "type": "string",- "description": "Root URL of the Gitea instance."- },"repositoryOwner": {"type": "string"},"repositoryName": {"type": "string"},- "maskedAccessToken": {- "type": "string"+ "installationId": {+ "type": [+ "number",+ "null"+ ],+ "description": "The GitHub App installation that grants access to the repository."},- "webhookUrl": {- "type": "string",- "description": "Where Gitea should POST events for this project."+ "requiresVerification": {+ "type": "boolean"},- "webhookSecret": {- "type": "string",- "description": "Only returned to callers with workspace:manage_settings, so the value can be pasted into Gitea."+ "importProgress": {+ "$ref": "#/components/schemas/IssueImportResult"},"branchPattern": {- "type": "string"+ "type": "string",+ "description": "Template used to name branches created for a task."},- "commentTaskLinkOnGiteaIssue": {+ "commentTaskLinkOnGitHubIssue": {"type": "boolean",- "description": "When on, Kaneo comments a link back to the task on the linked Gitea issue."+ "description": "When on, Kaneo comments a link back to the task on the linked GitHub issue."},"isActive": {"type": [@@ -2308,104 +2181,78 @@"required": ["id","projectId",- "baseUrl","repositoryOwner","repositoryName",- "maskedAccessToken",+ "installationId",+ "requiresVerification","isActive","createdAt","updatedAt"]},- "GiteaIntegrationNotFound": {+ "IssueImportResult": {"type": "object","properties": {- "error": {+ "runId": {"type": "string"+ },+ "pending": {+ "type": "boolean"+ },+ "imported": {+ "type": "number"+ },+ "updated": {+ "type": "number"+ },+ "skipped": {+ "type": "number",+ "description": "Issues whose linked task or source disappeared or belongs to another project."}},"required": [- "error"+ "runId",+ "pending",+ "imported",+ "updated",+ "skipped"]},- "GiteaDeleteResult": {+ "CreatedGitHubIntegration": {"type": "object","properties": {- "success": {- "type": "boolean"+ "id": {+ "type": "string"},- "message": {+ "projectId": {"type": "string"- }- },- "required": [- "success",- "message"- ]- },- "GiteaImportResult": {- "type": "object",- "properties": {- "imported": {- "type": "number"},- "updated": {- "type": "number",- "description": "Existing tasks that were refreshed from their issue."- },- "skipped": {- "type": "number"- },- "errors": {- "type": "array",- "items": {- "type": "string"- }- }- },- "required": [- "imported",- "updated",- "skipped"- ]- },- "GenericWebhookIntegration": {- "type": [- "object",- "null"- ],- "properties": {- "id": {+ "repositoryOwner": {"type": "string"},- "projectId": {+ "repositoryName": {"type": "string"},- "webhookConfigured": {- "type": "boolean"- },- "maskedWebhookUrl": {+ "installationId": {"type": [- "string",+ "number","null"- ]+ ],+ "description": "The GitHub App installation that grants access to the repository."},- "secretConfigured": {+ "requiresVerification": {"type": "boolean"},- "maskedSecret": {- "type": [- "string",- "null"- ],- "description": "A preview of the HMAC signing secret used to sign outgoing deliveries."+ "importProgress": {+ "$ref": "#/components/schemas/IssueImportResult"},- "events": {- "$ref": "#/components/schemas/GenericWebhookEvents"+ "branchPattern": {+ "type": "string",+ "description": "Template used to name branches created for a task."},- "dueDateReminderLeadTimeMinutes": {- "type": "number",- "description": "How long before a due date the dueDateReminder event fires, in minutes."+ "commentTaskLinkOnGitHubIssue": {+ "type": "boolean",+ "description": "When on, Kaneo comments a link back to the task on the linked GitHub issue."},"isActive": {"type": [@@ -2423,199 +2270,147 @@}},"required": [- "id",- "projectId",- "webhookConfigured",- "maskedWebhookUrl",- "secretConfigured",- "maskedSecret",- "events",- "dueDateReminderLeadTimeMinutes",- "isActive",- "createdAt",- "updatedAt"+ "repositoryOwner",+ "repositoryName",+ "installationId",+ "requiresVerification"]},- "GenericWebhookEvents": {- "allOf": [- {- "$ref": "#/components/schemas/IntegrationEvents"- },- {- "type": "object",- "properties": {- "taskDeleted": {- "type": "boolean"- },- "taskMoved": {- "type": "boolean"- },- "taskDueDateChanged": {- "type": "boolean"- },- "taskAssigneeChanged": {- "type": "boolean"- },- "taskUnassigned": {- "type": "boolean"- },- "dueDateReminder": {- "type": "boolean"- }- },- "required": [- "taskDeleted",- "taskMoved",- "taskDueDateChanged",- "taskAssigneeChanged",- "taskUnassigned",- "dueDateReminder"- ]+ "GitHubIntegrationNotFound": {+ "type": "object",+ "properties": {+ "error": {+ "type": "string"}+ },+ "required": [+ "error"]},- "IntegrationEvents": {+ "GitHubDeleteResult": {"type": "object","properties": {- "taskCreated": {- "type": "boolean"- },- "taskStatusChanged": {- "type": "boolean"- },- "taskPriorityChanged": {- "type": "boolean"- },- "taskTitleChanged": {- "type": "boolean"- },- "taskDescriptionChanged": {+ "success": {"type": "boolean"},- "taskCommentCreated": {- "type": "boolean"+ "message": {+ "type": "string"}},"required": [- "taskCreated",- "taskStatusChanged",- "taskPriorityChanged",- "taskTitleChanged",- "taskDescriptionChanged",- "taskCommentCreated"+ "success",+ "message"]},- "DiscordIntegration": {- "type": [- "object",- "null"- ],+ "GiteaRepositoryList": {+ "type": "object",+ "properties": {+ "repositories": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/GiteaRepository"+ }+ }+ },+ "required": [+ "repositories"+ ]+ },+ "GiteaRepository": {+ "type": "object","properties": {"id": {+ "type": "number"+ },+ "name": {"type": "string"},- "projectId": {+ "full_name": {"type": "string"},- "channelName": {- "type": [- "string",- "null"- ]+ "owner": {+ "$ref": "#/components/schemas/GiteaRepositoryOwner"},- "webhookConfigured": {+ "private": {"type": "boolean"},- "maskedWebhookUrl": {- "type": "string",- "description": "The webhook URL with its secret path segment masked, or an empty string when none is set."- },- "events": {- "$ref": "#/components/schemas/IntegrationEvents"- },- "isActive": {- "type": [- "boolean",- "null"- ]- },- "createdAt": {- "type": "string",- "format": "date-time"- },- "updatedAt": {- "type": "string",- "format": "date-time"+ "html_url": {+ "type": "string"}},"required": ["id",- "projectId",- "channelName",- "webhookConfigured",- "maskedWebhookUrl",- "events",- "isActive",- "createdAt",- "updatedAt"+ "name",+ "full_name",+ "owner",+ "private",+ "html_url"]},- "MattermostIntegration": {- "type": [- "object",- "null"- ],+ "GiteaRepositoryOwner": {+ "type": "object","properties": {- "id": {+ "login": {"type": "string"+ }+ },+ "required": [+ "login"+ ]+ },+ "GiteaVerificationResult": {+ "type": "object",+ "properties": {+ "isInstalled": {+ "type": "boolean"},- "projectId": {- "type": "string"+ "hasRequiredPermissions": {+ "type": "boolean"},- "channelName": {+ "repositoryExists": {+ "type": "boolean"+ },+ "repositoryPrivate": {"type": [- "string",+ "boolean","null"]},- "webhookConfigured": {- "type": "boolean"- },- "maskedWebhookUrl": {- "type": "string",- "description": "The webhook URL with its secret path segment masked, or an empty string when none is set."+ "missingPermissions": {+ "type": "array",+ "items": {+ "type": "string"+ }},- "events": {- "$ref": "#/components/schemas/IntegrationEvents"+ "message": {+ "type": "string",+ "description": "A human-readable summary to show the user."},- "isActive": {+ "failureReason": {"type": [- "boolean",+ "string","null"- ]- },- "createdAt": {- "type": "string",- "format": "date-time"- },- "updatedAt": {- "type": "string",- "format": "date-time"+ ],+ "enum": [+ "not_a_gitea_instance",+ "redirected",+ "repository_not_found",+ null+ ],+ "description": "Why verification failed, when it did. `redirected` usually means the base URL is behind a proxy that rewrites it."}},"required": [- "id",- "projectId",- "channelName",- "webhookConfigured",- "maskedWebhookUrl",- "events",- "isActive",- "createdAt",- "updatedAt"+ "isInstalled",+ "hasRequiredPermissions",+ "repositoryExists",+ "repositoryPrivate",+ "missingPermissions",+ "message",+ "failureReason"]},- "SlackIntegration": {+ "GiteaIntegration": {"type": ["object","null"@@ -2627,21 +2422,33 @@"projectId": {"type": "string"},- "channelName": {- "type": [- "string",- "null"- ]+ "baseUrl": {+ "type": "string",+ "description": "Root URL of the Gitea instance."},- "webhookConfigured": {- "type": "boolean"+ "repositoryOwner": {+ "type": "string"},- "maskedWebhookUrl": {+ "repositoryName": {+ "type": "string"+ },+ "maskedAccessToken": {+ "type": "string"+ },+ "webhookUrl": {"type": "string",- "description": "The webhook URL with its secret path segment masked, or an empty string when none is set."+ "description": "Where Gitea should POST events for this project."},- "events": {- "$ref": "#/components/schemas/IntegrationEvents"+ "webhookSecret": {+ "type": "string",+ "description": "Only returned to callers with workspace:manage_settings, so the value can be pasted into Gitea."+ },+ "branchPattern": {+ "type": "string"+ },+ "commentTaskLinkOnGiteaIssue": {+ "type": "boolean",+ "description": "When on, Kaneo comments a link back to the task on the linked Gitea issue."},"isActive": {"type": [@@ -2661,16 +2468,68 @@"required": ["id","projectId",- "channelName",- "webhookConfigured",- "maskedWebhookUrl",- "events",+ "baseUrl",+ "repositoryOwner",+ "repositoryName",+ "maskedAccessToken","isActive","createdAt","updatedAt"]},- "TelegramIntegration": {+ "GiteaIntegrationNotFound": {+ "type": "object",+ "properties": {+ "error": {+ "type": "string"+ }+ },+ "required": [+ "error"+ ]+ },+ "GiteaDeleteResult": {+ "type": "object",+ "properties": {+ "success": {+ "type": "boolean"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "success",+ "message"+ ]+ },+ "GiteaImportResult": {+ "type": "object",+ "properties": {+ "imported": {+ "type": "number"+ },+ "updated": {+ "type": "number",+ "description": "Existing tasks that were refreshed from their issue."+ },+ "skipped": {+ "type": "number"+ },+ "errors": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "imported",+ "updated",+ "skipped"+ ]+ },+ "GenericWebhookIntegration": {"type": ["object","null"@@ -2682,32 +2541,31 @@"projectId": {"type": "string"},- "chatId": {- "type": "string",- "description": "The Telegram chat, group, or channel messages are sent to."+ "webhookConfigured": {+ "type": "boolean"},- "threadId": {+ "maskedWebhookUrl": {"type": [- "number",+ "string","null"- ],- "description": "Forum topic id, when the target group uses topics."+ ]},- "chatLabel": {+ "secretConfigured": {+ "type": "boolean"+ },+ "maskedSecret": {"type": ["string","null"],- "description": "A human-readable name for the chat, shown in the UI."- },- "botTokenConfigured": {- "type": "boolean"- },- "maskedBotToken": {- "type": "string"+ "description": "A preview of the HMAC signing secret used to sign outgoing deliveries."},"events": {- "$ref": "#/components/schemas/IntegrationEvents"+ "$ref": "#/components/schemas/GenericWebhookEvents"+ },+ "dueDateReminderLeadTimeMinutes": {+ "type": "number",+ "description": "How long before a due date the dueDateReminder event fires, in minutes."},"isActive": {"type": [@@ -2727,40 +2585,87 @@"required": ["id","projectId",- "chatId",- "threadId",- "chatLabel",- "botTokenConfigured",- "maskedBotToken",+ "webhookConfigured",+ "maskedWebhookUrl",+ "secretConfigured",+ "maskedSecret","events",+ "dueDateReminderLeadTimeMinutes","isActive","createdAt","updatedAt"]},- "TaskRelationWithTasks": {+ "GenericWebhookEvents": {"allOf": [{- "$ref": "#/components/schemas/TaskRelation"+ "$ref": "#/components/schemas/IntegrationEvents"},{"type": "object","properties": {- "sourceTask": {- "$ref": "#/components/schemas/RelatedTask"+ "taskDeleted": {+ "type": "boolean"},- "targetTask": {- "$ref": "#/components/schemas/RelatedTask"+ "taskMoved": {+ "type": "boolean"+ },+ "taskDueDateChanged": {+ "type": "boolean"+ },+ "taskAssigneeChanged": {+ "type": "boolean"+ },+ "taskUnassigned": {+ "type": "boolean"+ },+ "dueDateReminder": {+ "type": "boolean"}},"required": [- "sourceTask",- "targetTask"+ "taskDeleted",+ "taskMoved",+ "taskDueDateChanged",+ "taskAssigneeChanged",+ "taskUnassigned",+ "dueDateReminder"]}]},- "RelatedTask": {+ "IntegrationEvents": {+ "type": "object",+ "properties": {+ "taskCreated": {+ "type": "boolean"+ },+ "taskStatusChanged": {+ "type": "boolean"+ },+ "taskPriorityChanged": {+ "type": "boolean"+ },+ "taskTitleChanged": {+ "type": "boolean"+ },+ "taskDescriptionChanged": {+ "type": "boolean"+ },+ "taskCommentCreated": {+ "type": "boolean"+ }+ },+ "required": [+ "taskCreated",+ "taskStatusChanged",+ "taskPriorityChanged",+ "taskTitleChanged",+ "taskDescriptionChanged",+ "taskCommentCreated"+ ]+ },+ "DiscordIntegration": {"type": ["object","null"@@ -2769,10 +2674,265 @@"id": {"type": "string"},- "title": {+ "projectId": {"type": "string"},- "status": {+ "channelName": {+ "type": [+ "string",+ "null"+ ]+ },+ "webhookConfigured": {+ "type": "boolean"+ },+ "maskedWebhookUrl": {+ "type": "string",+ "description": "The webhook URL with its secret path segment masked, or an empty string when none is set."+ },+ "events": {+ "$ref": "#/components/schemas/IntegrationEvents"+ },+ "isActive": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "projectId",+ "channelName",+ "webhookConfigured",+ "maskedWebhookUrl",+ "events",+ "isActive",+ "createdAt",+ "updatedAt"+ ]+ },+ "MattermostIntegration": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "projectId": {+ "type": "string"+ },+ "channelName": {+ "type": [+ "string",+ "null"+ ]+ },+ "webhookConfigured": {+ "type": "boolean"+ },+ "maskedWebhookUrl": {+ "type": "string",+ "description": "The webhook URL with its secret path segment masked, or an empty string when none is set."+ },+ "events": {+ "$ref": "#/components/schemas/IntegrationEvents"+ },+ "isActive": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "projectId",+ "channelName",+ "webhookConfigured",+ "maskedWebhookUrl",+ "events",+ "isActive",+ "createdAt",+ "updatedAt"+ ]+ },+ "SlackIntegration": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "projectId": {+ "type": "string"+ },+ "channelName": {+ "type": [+ "string",+ "null"+ ]+ },+ "webhookConfigured": {+ "type": "boolean"+ },+ "maskedWebhookUrl": {+ "type": "string",+ "description": "The webhook URL with its secret path segment masked, or an empty string when none is set."+ },+ "events": {+ "$ref": "#/components/schemas/IntegrationEvents"+ },+ "isActive": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "projectId",+ "channelName",+ "webhookConfigured",+ "maskedWebhookUrl",+ "events",+ "isActive",+ "createdAt",+ "updatedAt"+ ]+ },+ "TelegramIntegration": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "projectId": {+ "type": "string"+ },+ "chatId": {+ "type": "string",+ "description": "The Telegram chat, group, or channel messages are sent to."+ },+ "threadId": {+ "type": [+ "number",+ "null"+ ],+ "description": "Forum topic id, when the target group uses topics."+ },+ "chatLabel": {+ "type": [+ "string",+ "null"+ ],+ "description": "A human-readable name for the chat, shown in the UI."+ },+ "botTokenConfigured": {+ "type": "boolean"+ },+ "maskedBotToken": {+ "type": "string"+ },+ "events": {+ "$ref": "#/components/schemas/IntegrationEvents"+ },+ "isActive": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "projectId",+ "chatId",+ "threadId",+ "chatLabel",+ "botTokenConfigured",+ "maskedBotToken",+ "events",+ "isActive",+ "createdAt",+ "updatedAt"+ ]+ },+ "TaskRelationWithTasks": {+ "allOf": [+ {+ "$ref": "#/components/schemas/TaskRelation"+ },+ {+ "type": "object",+ "properties": {+ "sourceTask": {+ "$ref": "#/components/schemas/RelatedTask"+ },+ "targetTask": {+ "$ref": "#/components/schemas/RelatedTask"+ }+ },+ "required": [+ "sourceTask",+ "targetTask"+ ]+ }+ ]+ },+ "RelatedTask": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "status": {"type": "string"},"priority": {@@ -3301,31 +3461,389 @@"type": "boolean","description": "False when the user had no uploaded avatar to remove."}- },- "required": [- "deleted"- ]- }- },- "parameters": {}- },- "paths": {- "/instance/status": {- "get": {- "operationId": "getInstanceStatus",- "tags": [- "Instance"+ },+ "required": [+ "deleted"+ ]+ }+ },+ "parameters": {}+ },+ "paths": {+ "/instance/status": {+ "get": {+ "operationId": "getInstanceStatus",+ "tags": [+ "Instance"+ ],+ "summary": "Get instance status",+ "description": "Public instance setup status. When hasUsers is false the next signup becomes the instance admin.",+ "security": [],+ "responses": {+ "200": {+ "description": "Instance status",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/InstanceStatus"+ }+ }+ }+ }+ }+ }+ },+ "/public-project/{id}": {+ "get": {+ "operationId": "getPublicProject",+ "tags": [+ "Projects"+ ],+ "summary": "Get a public project board",+ "description": "Read a public board in bounded task pages. Visibility is checked before loading tasks. Continue through pagination.totalPages for all tasks and through relatedPage/pagination.relatedTotalPages for their complete related records.",+ "security": [],+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "id",+ "in": "path"+ },+ {+ "schema": {+ "type": "string"+ },+ "required": false,+ "name": "status",+ "in": "query"+ },+ {+ "schema": {+ "type": "string"+ },+ "required": false,+ "name": "priority",+ "in": "query"+ },+ {+ "schema": {+ "type": "string"+ },+ "required": false,+ "name": "assigneeId",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^\\d+$"+ },+ "required": false,+ "name": "page",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^\\d+$"+ },+ "required": false,+ "name": "relatedPage",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^\\d+$"+ },+ "required": false,+ "name": "limit",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "createdAt",+ "priority",+ "dueDate",+ "position",+ "title",+ "number"+ ]+ },+ "required": false,+ "name": "sortBy",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "asc",+ "desc"+ ]+ },+ "required": false,+ "name": "sortOrder",+ "in": "query"+ },+ {+ "schema": {+ "type": "string"+ },+ "required": false,+ "name": "dueBefore",+ "in": "query"+ },+ {+ "schema": {+ "type": "string"+ },+ "required": false,+ "name": "dueAfter",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "A public board page",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PublicBoardPage"+ }+ }+ }+ },+ "400": {+ "description": "Invalid pagination or filters",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "Project is not public",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Project not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "description": "Task list request timed out",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "/public-project/{id}/description": {+ "get": {+ "operationId": "getPublicProjectDescriptionPage",+ "tags": [+ "Projects"+ ],+ "summary": "Read a public project description page",+ "security": [],+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "id",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^\\d+$",+ "default": 0+ },+ "required": false,+ "name": "offset",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^[0-9]{1,10}$"+ },+ "required": false,+ "name": "version",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "Public project description page",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TaskDescriptionPage"+ }+ }+ }+ },+ "400": {+ "description": "Invalid description cursor",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Public project not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Description changed or no longer public",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "description": "Description request timed out",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "/public-project/{id}/task/{taskId}/description": {+ "get": {+ "operationId": "getPublicTaskDescriptionPage",+ "tags": [+ "Projects"+ ],+ "summary": "Read a public task description page",+ "security": [],+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "id",+ "in": "path"+ },+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "taskId",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^\\d+$",+ "default": 0+ },+ "required": false,+ "name": "offset",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^[0-9]{1,10}$"+ },+ "required": false,+ "name": "version",+ "in": "query"+ }],- "summary": "Get instance status",- "description": "Public instance setup status. When hasUsers is false the next signup becomes the instance admin.",- "security": [],"responses": {"200": {- "description": "Instance status",+ "description": "Public task description page","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/InstanceStatus"+ "$ref": "#/components/schemas/TaskDescriptionPage"+ }+ }+ }+ },+ "400": {+ "description": "Invalid description cursor",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Public task not found",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Description changed or no longer public",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "description": "Description request timed out",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"}}}@@ -5417,7 +5935,8 @@"type": "string","maxLength": 2048},- "minItems": 1+ "minItems": 1,+ "maxItems": 10},"client_name": {"type": "string",@@ -5437,7 +5956,8 @@"authorization_code","refresh_token"]- }+ },+ "maxItems": 2},"response_types": {"type": "array",@@ -5447,7 +5967,8 @@"code"]},- "minItems": 1+ "minItems": 1,+ "maxItems": 1}},"required": [@@ -5504,7 +6025,9 @@},{"schema": {- "type": "string"+ "type": "string",+ "minLength": 1,+ "maxLength": 128},"required": true,"name": "client_id",@@ -5522,7 +6045,7 @@{"schema": {"type": "string",- "minLength": 1,+ "pattern": "^[A-Za-z0-9_-]{43}$","description": "PKCE challenge; only S256 is accepted."},"required": true,@@ -5543,7 +6066,8 @@},{"schema": {- "type": "string"+ "type": "string",+ "maxLength": 1024},"required": false,"name": "state",@@ -5579,7 +6103,9 @@"parameters": [{"schema": {- "type": "string"+ "type": "string",+ "minLength": 1,+ "maxLength": 128},"required": true,"name": "requestId",@@ -5629,7 +6155,9 @@"parameters": [{"schema": {- "type": "string"+ "type": "string",+ "minLength": 1,+ "maxLength": 128},"required": true,"name": "requestId",@@ -6137,7 +6665,190 @@}},"400": {- "description": "Invalid body, or workspace ID could not be determined",+ "description": "Invalid body, or workspace ID could not be determined",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access, or missing project:update permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "/project/{id}/archive": {+ "put": {+ "operationId": "archiveProject",+ "tags": [+ "Projects"+ ],+ "summary": "Archive project",+ "description": "Hide a project from the default list without deleting it. Reversible with unarchive.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "id",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The archived project",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Project"+ }+ }+ }+ },+ "400": {+ "description": "Unknown project, or its workspace could not be determined",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access, or missing project:update permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "/project/{id}/unarchive": {+ "put": {+ "operationId": "unarchiveProject",+ "tags": [+ "Projects"+ ],+ "summary": "Unarchive project",+ "description": "Return an archived project to the default list.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "id",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The restored project",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Project"+ }+ }+ }+ },+ "400": {+ "description": "Unknown project, or its workspace could not be determined",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials"+ },+ "403": {+ "description": "No workspace access, or missing project:update permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ "/task/{id}/description": {+ "get": {+ "operationId": "getTaskDescriptionPage",+ "tags": [+ "Tasks"+ ],+ "summary": "Read a description page",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "id",+ "in": "path"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^\\d+$",+ "default": 0+ },+ "required": false,+ "name": "offset",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^[0-9]{1,10}$"+ },+ "required": false,+ "name": "version",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "Description page",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TaskDescriptionPage"+ }+ }+ }+ },+ "400": {+ "description": "Invalid offset or version","content": {"text/plain": {"schema": {@@ -6150,7 +6861,7 @@"description": "Missing or invalid credentials"},"403": {- "description": "No workspace access, or missing project:update permission",+ "description": "No workspace access","content": {"text/plain": {"schema": {@@ -6158,41 +6869,19 @@}}}- }- }- }- },- "/project/{id}/archive": {- "put": {- "operationId": "archiveProject",- "tags": [- "Projects"- ],- "summary": "Archive project",- "description": "Hide a project from the default list without deleting it. Reversible with unarchive.",- "parameters": [- {- "schema": {- "type": "string"- },- "required": true,- "name": "id",- "in": "path"- }- ],- "responses": {- "200": {- "description": "The archived project",+ },+ "404": {+ "description": "Task not found","content": {- "application/json": {+ "text/plain": {"schema": {- "$ref": "#/components/schemas/Project"+ "type": "string"}}}},- "400": {- "description": "Unknown project, or its workspace could not be determined",+ "409": {+ "description": "Description changed; reload from offset zero","content": {"text/plain": {"schema": {@@ -6201,11 +6890,8 @@}}},- "401": {- "description": "Missing or invalid credentials"- },- "403": {- "description": "No workspace access, or missing project:update permission",+ "503": {+ "description": "Description request timed out","content": {"text/plain": {"schema": {@@ -6217,37 +6903,56 @@}}},- "/project/{id}/unarchive": {- "put": {- "operationId": "unarchiveProject",+ "/task/description-matches/{projectId}": {+ "get": {+ "operationId": "findDeferredTaskDescriptions","tags": [- "Projects"+ "Tasks"],- "summary": "Unarchive project",- "description": "Return an archived project to the default list.",+ "summary": "Search descriptions omitted from task lists","parameters": [{"schema": {"type": "string"},"required": true,- "name": "id",+ "name": "projectId","in": "path"+ },+ {+ "schema": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256+ },+ "required": true,+ "name": "query",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "minLength": 1,+ "maxLength": 128+ },+ "required": false,+ "name": "after",+ "in": "query"}],"responses": {"200": {- "description": "The restored project",+ "description": "Matching task IDs","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/Project"+ "$ref": "#/components/schemas/TaskDescriptionMatches"}}}},"400": {- "description": "Unknown project, or its workspace could not be determined",+ "description": "Invalid search query or cursor","content": {"text/plain": {"schema": {@@ -6260,7 +6965,17 @@"description": "Missing or invalid credentials"},"403": {- "description": "No workspace access, or missing project:update permission",+ "description": "No workspace access",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "description": "Description search timed out","content": {"text/plain": {"schema": {@@ -6279,7 +6994,7 @@"Tasks"],"summary": "List tasks",- "description": "Get a project's board: its columns, each with the tasks in it, plus the archived and planned buckets. Filter and paginate with the query parameters.",+ "description": "Get a project's board: its columns, each with the tasks in it, plus the archived and planned buckets. Responses always contain at most 100 tasks (50 by default). Continue through pagination.totalPages for the whole board, and for each task page follow relatedPage through pagination.relatedTotalPages for all labels, links and column metadata. Filters and sorting apply before pagination. Descriptions larger than 64 KiB are omitted with descriptionDeferred=true; read the task detail or description pages for full text.","parameters": [{"schema": {@@ -6322,6 +7037,15 @@"name": "page","in": "query"},+ {+ "schema": {+ "type": "string",+ "pattern": "^\\d+$"+ },+ "required": false,+ "name": "relatedPage",+ "in": "query"+ },{"schema": {"type": "string",@@ -6409,6 +7133,16 @@}}}+ },+ "503": {+ "description": "Task list request timed out",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}}@@ -6713,7 +7447,8 @@"type": "string"},"description": {- "type": "string"+ "type": "string",+ "description": "Omit to preserve the existing description when updating a list summary."},"startDate": {"type": "string"@@ -6738,7 +7473,9 @@"type": "string"},"position": {- "type": "number"+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483646},"userId": {"type": "string"@@ -6746,7 +7483,6 @@},"required": ["title",- "description","priority","status","projectId",@@ -8602,7 +9338,7 @@"externalUserName": {"type": "string","maxLength": 120,- "description": "Attribution for an imported comment. Ignored unless externalSource is also given."+ "description": "Attribution for an imported comment. Requires workspace:manage_settings and externalSource; otherwise ignored."},"externalSource": {"type": "string",@@ -8611,7 +9347,7 @@"trello","jira"],- "description": "The tool the comment was imported from."+ "description": "The tool the comment was imported from. Supplying external attribution requires workspace:manage_settings."}},"required": [@@ -8646,7 +9382,7 @@"description": "Missing or invalid credentials"},"403": {- "description": "No workspace access, or missing task:update permission",+ "description": "No workspace access, missing task:update permission, or external attribution without workspace:manage_settings","content": {"text/plain": {"schema": {@@ -9273,6 +10009,16 @@}}}+ },+ "409": {+ "description": "The workspace label is being deleted",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}}@@ -9403,6 +10149,16 @@}}}+ },+ "409": {+ "description": "The workspace label is being deleted",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}},@@ -9412,7 +10168,7 @@"Labels"],"summary": "Delete label",- "description": "Delete a label by ID",+ "description": "Delete a label by ID. Large workspace cascades remove at most 25 task copies per request. Repeat DELETE with the same ID after HTTP 202 until HTTP 200 completes the operation. The persisted start boundary allows safe resumption after a disconnect. HTTP 429 asks the caller to retry later.","parameters": [{"schema": {@@ -9434,6 +10190,16 @@}}},+ "202": {+ "description": "Deletion has more batches; repeat the same request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PendingLabelDeletion"+ }+ }+ }+ },"400": {"description": "Unknown label, or its workspace could not be determined","content": {@@ -9466,6 +10232,16 @@}}}+ },+ "429": {+ "description": "Deletion capacity is busy; retry after Retry-After",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}}@@ -9549,6 +10325,16 @@}}}+ },+ "409": {+ "description": "The workspace label is being deleted",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}},@@ -10139,7 +10925,8 @@{"schema": {"type": "string",- "minLength": 1+ "minLength": 1,+ "maxLength": 512},"required": true,"name": "q",@@ -10276,6 +11063,26 @@"required": true,"name": "projectId","in": "path"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^[1-9][0-9]{0,5}$",+ "default": "1"+ },+ "required": false,+ "name": "installationPage",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "pattern": "^[1-9][0-9]{0,5}$",+ "default": "1"+ },+ "required": false,+ "name": "repositoryPage",+ "in": "query"}],"responses": {@@ -10336,11 +11143,13 @@},"repositoryOwner": {"type": "string",- "minLength": 1+ "minLength": 1,+ "maxLength": 100},"repositoryName": {"type": "string",- "minLength": 1+ "minLength": 1,+ "maxLength": 100}},"required": [@@ -10449,7 +11258,7 @@"GitHub"],"summary": "Create GitHub integration",- "description": "Link a project to a GitHub repository.",+ "description": "Link a project to a GitHub repository. Disconnect first to switch repositories; existing issue and pull request links cannot be reused for another repository.","parameters": [{"schema": {@@ -10469,11 +11278,13 @@"properties": {"repositoryOwner": {"type": "string",- "minLength": 1+ "minLength": 1,+ "maxLength": 100},"repositoryName": {"type": "string",- "minLength": 1+ "minLength": 1,+ "maxLength": 100}},"required": [@@ -10517,6 +11328,16 @@}}}+ },+ "409": {+ "description": "Integration changed or another repository is already linked",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}},@@ -10598,6 +11419,16 @@}}}+ },+ "409": {+ "description": "Integration changed or another repository is already linked",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}},@@ -10672,7 +11503,7 @@"GitHub"],"summary": "Import GitHub issues",- "description": "Import the linked repository's issues as tasks. Issues that already have a task are skipped.",+ "description": "Import open issues and link open pull requests in bounded steps. Existing tasks are updated. Continue 202 responses with the returned runId until 200; the same runId safely retries completion. Progress is saved after each page. New calls without runId resume an unfinished import or start a new one after completion.","requestBody": {"required": true,"content": {@@ -10681,7 +11512,14 @@"type": "object","properties": {"projectId": {- "type": "string"+ "type": "string",+ "minLength": 1,+ "maxLength": 128+ },+ "runId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 128}},"required": [@@ -10693,7 +11531,17 @@},"responses": {"200": {- "description": "Import summary",+ "description": "Completed import summary",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/IssueImportResult"+ }+ }+ }+ },+ "202": {+ "description": "Saved import progress; continue with runId","content": {"application/json": {"schema": {@@ -10734,6 +11582,36 @@}}}+ },+ "409": {+ "description": "Integration or import changed; refresh before resuming",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "429": {+ "description": "Import busy; retry after one second",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "502": {+ "description": "Provider unavailable or invalid page; progress is saved",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}}@@ -13618,7 +14496,7 @@"description": "Missing or invalid credentials"},"403": {- "description": "No access to the project's workspace",+ "description": "No workspace access or missing read permission","content": {"text/plain": {"schema": {@@ -13676,7 +14554,7 @@"description": "Missing or invalid credentials"},"403": {- "description": "No access to the project's workspace",+ "description": "No workspace access or missing read permission","content": {"text/plain": {"schema": {@@ -13734,7 +14612,7 @@"description": "Missing or invalid credentials"},"403": {- "description": "No access to the task's workspace",+ "description": "No workspace access or missing task:read permission","content": {"text/plain": {"schema": {@@ -13792,7 +14670,7 @@"description": "Missing or invalid credentials"},"403": {- "description": "No access to the project's workspace",+ "description": "No workspace access or missing read permission","content": {"text/plain": {"schema": {@@ -14126,11 +15004,13 @@"properties": {"contentType": {"type": "string",+ "maxLength": 64,"description": "One of image/png, image/jpeg, or image/webp.","example": "image/png"},"data": {"type": "string",+ "maxLength": 700076,"description": "Base64 encoded image bytes."}},@@ -14165,6 +15045,26 @@},"401": {"description": "Missing or invalid credentials"+ },+ "408": {+ "description": "Request body timed out",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "413": {+ "description": "Request body exceeds the upload limit",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }}}},diff --git a/apps/web/Dockerfile b/apps/web/Dockerfileindex 1c0e1dceb..2439f2606 100644--- a/apps/web/Dockerfile+++ b/apps/web/Dockerfile@@ -45,7 +45,7 @@ WORKDIR /app/apps/web# secret still succeed; the build just runs without it.RUN --mount=type=secret,id=SENTRY_AUTH_TOKEN,required=false \if [ -f /run/secrets/SENTRY_AUTH_TOKEN ]; then export SENTRY_AUTH_TOKEN="$(cat /run/secrets/SENTRY_AUTH_TOKEN)"; fi; \- pnpm run build+ pnpm run build && find dist -type f -name '*.map' -delete# Production stage with specific versionFROM nginx:1.29.5-alpine AS runtime@@ -72,12 +72,13 @@ RUN addgroup -g 1001 appuser && \# Copy built files from builder stageCOPY --from=builder --chown=appuser:appuser /app/apps/web/dist /usr/share/nginx/html-# Copy nginx configuration (writable so env.sh can substitute placeholders at runtime)+# Copy nginx configuration and public runtime configuration rendererCOPY --chown=appuser:appuser apps/web/nginx.conf /etc/nginx/conf.d/default.confRUN chown -R appuser:appuser /etc/nginx/conf.d# Copy and set permissions for environment scriptCOPY --chown=appuser:appuser apps/web/env.sh /docker-entrypoint.d/env.sh+COPY --chown=appuser:appuser apps/web/env.awk /docker-entrypoint.d/env.awkRUN chmod +x /docker-entrypoint.d/env.sh# Switch to non-root userdiff --git a/apps/web/env.awk b/apps/web/env.awknew file mode 100644index 000000000..f83052be3--- /dev/null+++ b/apps/web/env.awk@@ -0,0 +1,55 @@+# BusyBox/POSIX awk only: the standalone nginx image has no Node.js runtime.+function json(value, result, i, ch) {+ result = "\""+ for (i = 1; i <= length(value); i++) {+ ch = substr(value, i, 1)+ if (ch in escape) result = result escape[ch]+ else result = result ch+ }+ return result "\""+}++BEGIN {+ escape["\\"] = "\\\\"+ escape["\""] = "\\\""+ for (i = 1; i < 32; i++) escape[sprintf("%c", i)] = sprintf("\\u%04x", i)+ # Only these public build-time placeholders may enter browser assets.+ values["KANEO_API_URL"] = ENVIRON["KANEO_API_URL"]+ values["KANEO_CLIENT_URL"] = ENVIRON["KANEO_CLIENT_URL"]+ values["KANEO_TURNSTILE_SITE_KEY"] = ENVIRON["KANEO_TURNSTILE_SITE_KEY"]++ if (mode == "resource" || mode == "authorization") {+ base = values["KANEO_API_URL"]+ if (base == "") { print "{}"; exit }+ sub(/[?#].*$/, "", base)+ sub(/\/*$/, "", base)+ sub(/\/api$/, "", base)+ if (mode == "resource") {+ print "{\"resource\":" json(base "/api/mcp") ",\"authorization_servers\":[" json(base "/api") "]}"+ } else {+ print "{\"issuer\":" json(base "/api") ",\"authorization_endpoint\":" json(base "/api/mcp/authorize") ",\"token_endpoint\":" json(base "/api/mcp/token") ",\"registration_endpoint\":" json(base "/api/mcp/register") ",\"response_types_supported\":[\"code\"],\"grant_types_supported\":[\"authorization_code\"],\"code_challenge_methods_supported\":[\"S256\"],\"token_endpoint_auth_methods_supported\":[\"none\"]}"+ }+ exit+ }+}++{+ rest = $0+ output = ""+ # Match entire quoted literals. The emitted JSON string is never scanned+ # again, so a value containing another placeholder remains literal data.+ # Vite can fold a static path suffix into the same literal (for example+ # KANEO_CLIENT_URL/auth/sign-in). Only accept an unescaped static path.+ while (match(rest, /["'`]KANEO_(API_URL|CLIENT_URL|TURNSTILE_SITE_KEY)(\/[-A-Za-z0-9_.\/]*)?["'`]/)) {+ token = substr(rest, RSTART, RLENGTH)+ key = substr(token, 2, length(token) - 2)+ suffix = ""+ slash = index(key, "/")+ if (slash) { suffix = substr(key, slash); key = substr(key, 1, slash - 1) }+ output = output substr(rest, 1, RSTART - 1)+ if (substr(token, 1, 1) == substr(token, length(token), 1)) output = output json(values[key] suffix)+ else output = output token+ rest = substr(rest, RSTART + RLENGTH)+ }+ print output rest+}diff --git a/apps/web/env.sh b/apps/web/env.shindex 6fcbdbb2b..163154ace 100644--- a/apps/web/env.sh+++ b/apps/web/env.sh@@ -1,66 +1,39 @@#!/bin/sh-set -e+set -eu-echo "Starting environment variable replacement..."+# Values are read through awk's ENVIRON, never interpolated into shell, sed,+# JavaScript, or nginx source. Do not print public or private environment values.+script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+asset_root=/usr/share/nginx/html+export KANEO_ENV_RENDERER="$script_dir/env.awk"-# Process KANEO_API_URL first (with special handling)-if [ ! -z "$KANEO_API_URL" ]; then- echo "Found KANEO_API_URL: $KANEO_API_URL"-- # First, replace the exact string "KANEO_API_URL" in all JavaScript files- # Use grep -l to only process files that contain the string- find /usr/share/nginx/html -type f -name "*.js" -exec grep -l "KANEO_API_URL" {} \; | xargs -r sed -i "s#KANEO_API_URL#$KANEO_API_URL#g"-- # Also check for the escaped version which might appear in some files- find /usr/share/nginx/html -type f -name "*.js" -exec grep -l "\"KANEO_API_URL\"" {} \; | xargs -r sed -i "s#\"KANEO_API_URL\"#\"$KANEO_API_URL\"#g"-- # Build MCP OAuth discovery JSON for nginx to serve at /.well-known- BASE_URL=$(echo "$KANEO_API_URL" | sed 's#/api/*$##')- PRM_JSON="{\"resource\":\"${BASE_URL}/api/mcp\",\"authorization_servers\":[\"${BASE_URL}/api\"]}"- AS_JSON="{\"issuer\":\"${BASE_URL}/api\",\"authorization_endpoint\":\"${BASE_URL}/api/mcp/authorize\",\"token_endpoint\":\"${BASE_URL}/api/mcp/token\",\"registration_endpoint\":\"${BASE_URL}/api/mcp/register\",\"response_types_supported\":[\"code\"],\"grant_types_supported\":[\"authorization_code\"],\"code_challenge_methods_supported\":[\"S256\"],\"token_endpoint_auth_methods_supported\":[\"none\"]}"- sed -i "s#MCP_PRM_JSON_PLACEHOLDER#$PRM_JSON#g" /etc/nginx/conf.d/default.conf- sed -i "s#MCP_AS_JSON_PLACEHOLDER#$AS_JSON#g" /etc/nginx/conf.d/default.conf-- echo "✅ Replaced KANEO_API_URL with $KANEO_API_URL"-else- echo "WARNING: KANEO_API_URL environment variable is not set. API calls may fail."- # No API URL — remove MCP placeholders so nginx doesn't serve broken JSON- sed -i "s#MCP_PRM_JSON_PLACEHOLDER#{}#g" /etc/nginx/conf.d/default.conf- sed -i "s#MCP_AS_JSON_PLACEHOLDER#{}#g" /etc/nginx/conf.d/default.conf+if [ -z "${KANEO_API_URL:-}" ]; then+ echo "WARNING: KANEO_API_URL is not set. API calls may fail." >&2fi-# Process KANEO_CLIENT_URL efficiently-if [ ! -z "$KANEO_CLIENT_URL" ]; then- echo "Found KANEO_CLIENT_URL: $KANEO_CLIENT_URL"-- # Only process files that actually contain the string- find /usr/share/nginx/html -type f -name "*.js" -exec grep -l "KANEO_CLIENT_URL" {} \; | xargs -r sed -i "s#KANEO_CLIENT_URL#$KANEO_CLIENT_URL#g"- find /usr/share/nginx/html -type f -name "*.js" -exec grep -l "\"KANEO_CLIENT_URL\"" {} \; | xargs -r sed -i "s#\"KANEO_CLIENT_URL\"#\"$KANEO_CLIENT_URL\"#g"-- echo "✅ Replaced KANEO_CLIENT_URL with $KANEO_CLIENT_URL"-fi--# Process any other KANEO_ prefixed environment variables (for future extensibility)-# Exclude the ones we've already processed-for key in $(env | grep '^KANEO_' | grep -v 'KANEO_API_URL\|KANEO_CLIENT_URL' | cut -d= -f1); do- value=$(printenv "$key")-- if [ ! -z "$value" ]; then- echo "Found $key: $value"-- # Only process files that contain this specific key- find /usr/share/nginx/html -type f \( -name "*.js" -o -name "*.css" \) -exec grep -l "$key" {} \; | xargs -r sed -i "s#$key#$value#g"-- echo "✅ Replaced $key with $value"- fi+# find -exec preserves spaces/newlines in filenames. Write each replacement+# beside its source before atomically replacing the complete file.+find "$asset_root" -type f -name '*.js' -exec sh -eu -c '+ for asset do+ temporary=$(mktemp "${asset}.XXXXXX")+ trap '\''rm -f "$temporary"'\'' EXIT HUP INT TERM+ LC_ALL=C awk -v mode=bundle -f "$KANEO_ENV_RENDERER" "$asset" > "$temporary"+ chmod 644 "$temporary"+ mv "$temporary" "$asset"+ trap - EXIT HUP INT TERM+ done+' sh {} +++# Serve JSON as static content. It must never become an nginx configuration+# string, where quotes, backslashes, and dollar signs have another meaning.+for mode in resource authorization; do+ target="$asset_root/mcp-oauth-$mode.json"+ temporary=$(mktemp "${target}.XXXXXX")+ trap 'rm -f "$temporary"' EXIT HUP INT TERM+ LC_ALL=C awk -v mode="$mode" -f "$KANEO_ENV_RENDERER" > "$temporary"+ chmod 644 "$temporary"+ mv "$temporary" "$target"+ trap - EXIT HUP INT TERMdone-# Empty the quoted Turnstile placeholder when its env var was left unset.-# Without this, the literal placeholder stays in the bundle and is read by-# the frontend as a truthy string — which broke self-hosted signup when-# KANEO_TURNSTILE_SITE_KEY was left unset (issue #1304).-echo "Stripping unset KANEO_* placeholders..."-find /usr/share/nginx/html -type f \( -name "*.js" -o -name "*.css" \) \- -exec sed -i -E 's#[`"'"'"']KANEO_TURNSTILE_SITE_KEY[`"'"'"']#""#g' {} +--echo "✅ Environment variable replacement complete"+echo "Public web configuration prepared."diff --git a/apps/web/nginx.conf b/apps/web/nginx.confindex ff2e0af1c..2ca58a66d 100644--- a/apps/web/nginx.conf+++ b/apps/web/nginx.conf@@ -18,12 +18,12 @@ server {location = /.well-known/oauth-protected-resource/api/mcp {default_type application/json;- return 200 'MCP_PRM_JSON_PLACEHOLDER';+ alias /usr/share/nginx/html/mcp-oauth-resource.json;}location = /.well-known/oauth-authorization-server/api {default_type application/json;- return 200 'MCP_AS_JSON_PLACEHOLDER';+ alias /usr/share/nginx/html/mcp-oauth-authorization.json;}location /.well-known/ {@@ -31,6 +31,11 @@ server {}# Root location+ # Defense in depth if a build leaves a source map in the static directory.+ location ~* \.map$ {+ return 404;+ }+location / {root /usr/share/nginx/html;index index.html;diff --git a/apps/web/nginx.kaneo.conf b/apps/web/nginx.kaneo.confindex 449f0c234..4bf67befe 100644--- a/apps/web/nginx.kaneo.conf+++ b/apps/web/nginx.kaneo.conf@@ -21,6 +21,8 @@ server {proxy_set_header Host $host;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";+ proxy_set_header CF-Connecting-IP "";+ proxy_set_header X-Kaneo-Client-IP "";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;@@ -32,6 +34,8 @@ server {proxy_set_header Host $host;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";+ proxy_set_header CF-Connecting-IP "";+ proxy_set_header X-Kaneo-Client-IP "";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;@@ -47,11 +51,18 @@ server {proxy_set_header Host $host;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";+ proxy_set_header CF-Connecting-IP "";+ proxy_set_header X-Kaneo-Client-IP "";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;}+ # Defense in depth if a build leaves a source map in the static directory.+ location ~* \.map$ {+ return 404;+ }+location / {root /usr/share/nginx/html;index index.html;diff --git a/apps/web/src/components/activity/comment-card.test.tsx b/apps/web/src/components/activity/comment-card.test.tsxindex 13489ceea..9d9f3cb18 100644--- a/apps/web/src/components/activity/comment-card.test.tsx+++ b/apps/web/src/components/activity/comment-card.test.tsx@@ -1,10 +1,12 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { fireEvent, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";import type { ReactElement, ReactNode } from "react";import { cloneElement, isValidElement } from "react";-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import CommentCard from "./comment-card";+afterEach(cleanup);+vi.mock("@/components/activity/comment-editor", () => ({default: ({ value }: { value: string }) => <div>{value}</div>,}));@@ -22,7 +24,8 @@ vi.mock("@/hooks/mutations/comment/use-update-comment", () => ({vi.mock("react-i18next", () => ({useTranslation: () => ({- t: (key: string) => key,+ t: (key: string, values?: Record<string, string>) =>+ `${key}${values ? ` ${Object.values(values).join(" ")}` : ""}`,}),}));@@ -93,7 +96,7 @@ vi.mock("@/components/ui/tooltip", async () => {};});-function renderCommentCard() {+function renderCommentCard(externalSource?: string, importedBy?: string) {const queryClient = new QueryClient({defaultOptions: {queries: { retry: false },@@ -104,6 +107,8 @@ function renderCommentCard() {return render(<QueryClientProvider client={queryClient}><CommentCard+ externalSource={externalSource}+ importedBy={importedBy}commentId="comment-1"taskId="task-1"content="Test comment"@@ -120,6 +125,24 @@ function renderCommentCard() {}describe("CommentCard", () => {+ it.each(["planka", "trello", "jira", "github"])(+ "visibly identifies %s authors as imported without hovering",+ (source) => {+ renderCommentCard(source, "Actual Importer");+ expect(screen.getByText(/activity:comment.importedFrom/)).toBeVisible();+ expect(+ screen.getByText(/activity:comment.importedBy Actual Importer/),+ ).toBeVisible();+ },+ );++ it("does not label ordinary comments as imports", () => {+ renderCommentCard();+ expect(+ screen.queryByText(/activity:comment.importedFrom/),+ ).not.toBeInTheDocument();+ });+it("shows full date+short time in tooltip on hover/focus", async () => {renderCommentCard();diff --git a/apps/web/src/components/activity/comment-card.tsx b/apps/web/src/components/activity/comment-card.tsxindex efc764744..8a665c5f3 100644--- a/apps/web/src/components/activity/comment-card.tsx+++ b/apps/web/src/components/activity/comment-card.tsx@@ -35,6 +35,7 @@ type CommentCardProps = {image?: string | null;} | null;createdAt: string;+ importedBy?: string;externalSource?: string | null;externalUrl?: string | null;};@@ -47,6 +48,7 @@ export default function CommentCard({createdAt,externalSource,externalUrl,+ importedBy,}: CommentCardProps) {const { t } = useTranslation();const { user: currentUser } = useAuth();@@ -58,6 +60,16 @@ export default function CommentCard({const queryClient = useQueryClient();const canEdit = currentUser?.id === user?.id;+ const sourceName =+ externalSource === "github"+ ? "GitHub"+ : externalSource === "planka"+ ? "Planka"+ : externalSource === "trello"+ ? "Trello"+ : externalSource === "jira"+ ? "Jira"+ : externalSource;const isFromGitHub = externalSource === "github";const githubProfileUrl =isFromGitHub && user?.name ? `https://github.com/${user.name}` : null;@@ -111,7 +123,7 @@ export default function CommentCard({return (<TooltipProvider><div className="group relative w-full rounded-xl border border-border/80 bg-card/60">- <div className="flex items-center gap-2 px-3 pt-2.5">+ <div className="flex flex-wrap items-center gap-2 px-3 pt-2.5"><HoverCard><HoverCardTrigger><div className="flex cursor-pointer items-center gap-2">@@ -167,6 +179,13 @@ export default function CommentCard({</HoverCardContent></HoverCard>+ {sourceName && (+ <span className="rounded border px-1.5 py-0.5 text-xs text-muted-foreground">+ {t("activity:comment.importedFrom", { source: sourceName })}+ {importedBy &&+ ` · ${t("activity:comment.importedBy", { name: importedBy })}`}+ </span>+ )}<Tooltip><TooltipTrigger asChild><buttondiff --git a/apps/web/src/components/activity/index.tsx b/apps/web/src/components/activity/index.tsxindex 671db9bec..2a61648f0 100644--- a/apps/web/src/components/activity/index.tsx+++ b/apps/web/src/components/activity/index.tsx@@ -458,6 +458,11 @@ function Activity({content={activity.content || ""}user={commentUser}createdAt={activity.createdAt}+ importedBy={+ activity.userId && activity.externalSource !== "github"+ ? actorName+ : undefined+ }externalSource={activity.externalSource}externalUrl={activity.externalUrl}/>diff --git a/apps/web/src/components/auth/otp-sign-in-form.tsx b/apps/web/src/components/auth/otp-sign-in-form.tsxindex 8bde15b33..bde22010a 100644--- a/apps/web/src/components/auth/otp-sign-in-form.tsx+++ b/apps/web/src/components/auth/otp-sign-in-form.tsx@@ -18,6 +18,8 @@ import { authClient } from "@/lib/auth-client";import { toast } from "@/lib/toast";type OtpSignInFormProps = {+ turnstileToken?: string | null;+ onAttemptComplete?: () => void;invitationId?: string;defaultEmail?: string;redirect?: string;@@ -31,6 +33,8 @@ const emailSchema = z.object({type EmailFormValues = z.infer<typeof emailSchema>;export function OtpSignInForm({+ turnstileToken,+ onAttemptComplete,invitationId,defaultEmail,redirect,@@ -45,12 +49,20 @@ export function OtpSignInForm({});const onSubmit = async (data: EmailFormValues) => {+ if (turnstileToken !== undefined && !turnstileToken) return;setIsPending(true);try {- const result = await authClient.emailOtp.sendVerificationOtp({- email: data.email,- type: "sign-in",- });+ const result = await authClient.emailOtp.sendVerificationOtp(+ {+ email: data.email,+ type: "sign-in",+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) {toast.error(result.error.message || t("auth:otpSignIn.sendFailed"));@@ -67,6 +79,7 @@ export function OtpSignInForm({history.push(`/auth/verify-otp?${searchParams.toString()}`);} finally {setIsPending(false);+ onAttemptComplete?.();}};@@ -94,7 +107,13 @@ export function OtpSignInForm({)}/>- <Button type="submit" disabled={isPending} className="w-full mt-4">+ <Button+ type="submit"+ disabled={+ isPending || (turnstileToken !== undefined && !turnstileToken)+ }+ className="w-full mt-4"+ >{isPending? t("auth:otpSignIn.sending"): t("auth:otpSignIn.sendVerificationCode")}diff --git a/apps/web/src/components/auth/sign-up-form.tsx b/apps/web/src/components/auth/sign-up-form.tsxindex 275bf57fd..ee6a3c53b 100644--- a/apps/web/src/components/auth/sign-up-form.tsx+++ b/apps/web/src/components/auth/sign-up-form.tsx@@ -34,12 +34,14 @@ type SignUpFormProps = {* `undefined` means captcha isn't required at all (self-hosted).*/turnstileToken?: string | null;+ onAttemptComplete?: () => void;};export function SignUpForm({invitationId,defaultEmail,turnstileToken,+ onAttemptComplete,}: SignUpFormProps) {const { t } = useTranslation();const [showPassword, setShowPassword] = useState(false);@@ -69,6 +71,7 @@ export function SignUpForm({});const onSubmit = async (data: SignUpFormValues) => {+ if (captchaRequired && !turnstileToken) return;setIsPending(true);try {const headers: Record<string, string> = {};@@ -108,6 +111,7 @@ export function SignUpForm({);} finally {setIsPending(false);+ onAttemptComplete?.();}};diff --git a/apps/web/src/components/auth/sso-providers.tsx b/apps/web/src/components/auth/sso-providers.tsxindex 16ec4169f..b8a009bbd 100644--- a/apps/web/src/components/auth/sso-providers.tsx+++ b/apps/web/src/components/auth/sso-providers.tsx@@ -14,6 +14,8 @@ type Props = {errorCallbackURL: string;lastLoginMethod?: string | null;disabled?: boolean;+ turnstileToken?: string | null;+ onAttemptComplete?: () => void;};export function SSOProviders({@@ -22,6 +24,8 @@ export function SSOProviders({errorCallbackURL,lastLoginMethod,disabled = false,+ turnstileToken,+ onAttemptComplete,}: Props) {const { t } = useTranslation();const [loadingProvider, setLoadingProvider] = useState<string | null>(null);@@ -30,29 +34,46 @@ export function SSOProviders({provider: "google" | "github" | "discord",errorKey: string,) => {+ if (disabled) return;setLoadingProvider(provider);try {- const result = await authClient.signIn.social({- provider,- callbackURL,- errorCallbackURL,- });+ const result = await authClient.signIn.social(+ {+ provider,+ callbackURL,+ errorCallbackURL,+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) throw new Error(result.error.message);} catch (error) {toast.error(error instanceof Error ? error.message : t(errorKey));} finally {setLoadingProvider(null);+ onAttemptComplete?.();}};const handleCustomOAuth = async () => {+ if (disabled) return;setLoadingProvider("custom");try {- const result = await authClient.signIn.oauth2({- providerId: "custom",- callbackURL,- errorCallbackURL,- });+ const result = await authClient.signIn.oauth2(+ {+ providerId: "custom",+ callbackURL,+ errorCallbackURL,+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) throw new Error(result.error.message);} catch (error) {toast.error(@@ -60,6 +81,7 @@ export function SSOProviders({);} finally {setLoadingProvider(null);+ onAttemptComplete?.();}};diff --git a/apps/web/src/components/auth/turnstile.test.tsx b/apps/web/src/components/auth/turnstile.test.tsxnew file mode 100644index 000000000..c3a81db04--- /dev/null+++ b/apps/web/src/components/auth/turnstile.test.tsx@@ -0,0 +1,30 @@+import { cleanup, render, waitFor } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { Turnstile } from "./turnstile";++afterEach(() => {+ cleanup();+ delete window.turnstile;+});+it("binds the auth action and removes consumed widgets before a new attempt", async () => {+ const widget = {+ render: vi.fn().mockReturnValueOnce("first").mockReturnValueOnce("second"),+ remove: vi.fn(),+ reset: vi.fn(),+ };+ window.turnstile = widget;+ const verify = vi.fn();+ const { rerender } = render(+ <Turnstile key={0} siteKey="test" onVerify={verify} />,+ );+ await waitFor(() => expect(widget.render).toHaveBeenCalledTimes(1));+ expect(widget.render.mock.calls[0]?.[1]).toMatchObject({+ sitekey: "test",+ action: "auth",+ });+ widget.render.mock.calls[0]?.[1].callback("token");+ expect(verify).toHaveBeenCalledWith("token");+ rerender(<Turnstile key={1} siteKey="test" onVerify={verify} />);+ await waitFor(() => expect(widget.render).toHaveBeenCalledTimes(2));+ expect(widget.remove).toHaveBeenCalledWith("first");+});diff --git a/apps/web/src/components/auth/turnstile.tsx b/apps/web/src/components/auth/turnstile.tsxindex cc28f8f83..0e0499eae 100644--- a/apps/web/src/components/auth/turnstile.tsx+++ b/apps/web/src/components/auth/turnstile.tsx@@ -11,6 +11,7 @@ declare global {container: HTMLElement,options: {sitekey: string;+ action?: string;callback?: (token: string) => void;"error-callback"?: () => void;"expired-callback"?: () => void;@@ -89,6 +90,7 @@ export function Turnstile({if (cancelled || !containerRef.current || !window.turnstile) return;widgetIdRef.current = window.turnstile.render(containerRef.current, {sitekey: siteKey,+ action: "auth",callback: (token) => onVerifyRef.current(token),"expired-callback": () => onExpireRef.current?.(),"error-callback": () => onErrorRef.current?.(),diff --git a/apps/web/src/components/gantt/gantt-task-bar.tsx b/apps/web/src/components/gantt/gantt-task-bar.tsxindex 3a43aec02..dc5e03fd0 100644--- a/apps/web/src/components/gantt/gantt-task-bar.tsx+++ b/apps/web/src/components/gantt/gantt-task-bar.tsx@@ -87,6 +87,12 @@ export function GanttTaskBar({trackCount,);+ const startIsVisible =+ differenceInCalendarDays(task.scheduleStart, timeline.rangeStart) >= 0;+ const endIsVisible =+ differenceInCalendarDays(task.scheduleEnd, timeline.rangeStart) <+ trackCount;+const persistDates = useCallback(async (nextStart: Date, nextEnd: Date): Promise<boolean> => {try {@@ -219,6 +225,10 @@ export function GanttTaskBar({const originX = event.clientX;const initialStart = task.scheduleStart;const initialEnd = task.scheduleEnd;+ if (!startIsVisible || !endIsVisible) {+ onOpenTask();+ return;+ }const durationDays = differenceInCalendarDays(initialEnd, initialStart);const startIdx = differenceInCalendarDays(initialStart,@@ -294,6 +304,7 @@ export function GanttTaskBar({<buttontype="button"aria-label={t("tasks:gantt.resizeStart")}+ disabled={!startIsVisible}onPointerDown={handleResizeLeftPointerDown}className={cn("relative z-20 shrink-0 cursor-ew-resize touch-none border-r border-primary/15 bg-primary/8 hover:bg-primary/18",@@ -319,6 +330,7 @@ export function GanttTaskBar({<buttontype="button"aria-label={t("tasks:gantt.resizeDue")}+ disabled={!endIsVisible}onPointerDown={handleResizeRightPointerDown}className={cn("relative z-20 shrink-0 cursor-ew-resize touch-none border-l border-primary/15 bg-primary/8 hover:bg-primary/18",diff --git a/apps/web/src/components/gantt/gantt-window.test.tsx b/apps/web/src/components/gantt/gantt-window.test.tsxnew file mode 100644index 000000000..31d8bb907--- /dev/null+++ b/apps/web/src/components/gantt/gantt-window.test.tsx@@ -0,0 +1,167 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import type { ComponentType, ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const m = vi.hoisted(() => ({+ component: (() => null) as ComponentType,+ navigate: vi.fn(),+ update: vi.fn(),+ tasks: [] as Record<string, unknown>[],+}));+vi.mock("@tanstack/react-router", () => ({+ createFileRoute: () => (options: { component: ComponentType }) => {+ m.component = options.component;+ return {+ useParams: () => ({ projectId: "project", workspaceId: "workspace" }),+ useSearch: () => ({}),+ };+ },+ useNavigate: () => m.navigate,+}));+vi.mock("@/components/common/project-layout", () => ({+ default: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));+vi.mock("@/components/page-title", () => ({ default: () => null }));+vi.mock("@/components/task/task-details-sheet", () => ({+ default: () => null,+}));+vi.mock("@/hooks/queries/task/use-get-tasks", () => ({+ useGetTasks: () => ({+ data: {+ name: "Project",+ slug: "PROJ",+ columns: [{ tasks: m.tasks }],+ plannedTasks: [],+ },+ }),+}));+vi.mock("@/hooks/mutations/task/use-update-task", () => ({+ useUpdateTask: () => ({ mutateAsync: m.update }),+}));+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => false }));+vi.mock("@/store/user-preferences", () => ({+ useUserPreferencesStore: () => 1,+}));+vi.mock("@/lib/i18n/domain", () => ({+ getStatusLabel: (status: string) => status,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+ initReactI18next: { type: "3rdParty", init: vi.fn() },+}));+vi.mock("@/lib/toast", () => ({ toast: { error: vi.fn() } }));++await import(+ "@/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/gantt"+);+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});+beforeEach(() => {+ vi.clearAllMocks();+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ configurable: true,+ value: vi.fn(),+ });+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ disconnect() {}+ },+ );+ vi.stubGlobal("PointerEvent", MouseEvent);+});+function task(id: string, startDate: string, dueDate: string) {+ return {+ id,+ projectId: "project",+ title: id,+ number: 1,+ status: "to-do",+ startDate,+ dueDate,+ description: "",+ labels: [],+ priority: "low",+ position: 1,+ };+}+function show() {+ const Component = m.component;+ return render(<Component />);+}++describe("Gantt window UI", () => {+ it("renders a bounded grid for a centuries-long legacy task and makes clipped bars safe to open", () => {+ m.tasks = [task("Long-lived", "0001-01-01", "9999-12-31")];+ const { container } = show();+ const grids = Array.from(+ container.querySelectorAll<HTMLElement>(+ '[style*="grid-template-columns: repeat"]',+ ),+ );+ expect(grids.length).toBeGreaterThan(0);+ expect(+ grids.every((grid) => /repeat\(91,/.test(grid.style.gridTemplateColumns)),+ ).toBe(true);+ expect(+ screen.getByRole("button", { name: "tasks:gantt.resizeStart" }),+ ).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "tasks:gantt.resizeDue" }),+ ).toBeDisabled();+ fireEvent.pointerDown(+ screen.getByRole("button", { name: "tasks:gantt.taskAriaLabel" }),+ { button: 0 },+ );+ expect(m.navigate).toHaveBeenCalledWith(+ expect.objectContaining({ search: { taskId: "Long-lived" } }),+ );+ expect(m.update).not.toHaveBeenCalled();+ });++ it("can jump to a far-away task and navigate without losing its row", () => {+ m.tasks = [+ task("Ancient", "0001-01-01", "0001-01-02"),+ task("Future", "9999-12-30", "9999-12-31"),+ ];+ const { container } = show();+ const jump = screen.getAllByRole("button", {+ name: "tasks:gantt.showTaskDates",+ });+ expect(jump).toHaveLength(2);+ fireEvent.click(jump[1]);+ expect(screen.getByLabelText("tasks:gantt.periodStart")).toHaveValue(+ "9999-10-02",+ );+ expect(+ screen.getByRole("button", { name: "tasks:gantt.nextPeriod" }),+ ).toBeDisabled();+ expect(screen.getByText("Ancient")).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "tasks:gantt.previousPeriod" }),+ );+ expect(+ screen.getByRole("button", { name: "tasks:gantt.nextPeriod" }),+ ).not.toBeDisabled();+ expect(+ container.querySelectorAll('[style*="repeat(91,"]').length,+ ).toBeGreaterThan(0);+ });++ it("supports entering a date directly while keeping the allocated period bounded", () => {+ m.tasks = [task("Long-lived", "0001-01-01", "9999-12-31")];+ const { container } = show();+ fireEvent.change(screen.getByLabelText("tasks:gantt.periodStart"), {+ target: { value: "2050-01-01" },+ });+ expect(screen.getByLabelText("tasks:gantt.periodStart")).toHaveValue(+ "2050-01-01",+ );+ expect(+ container.querySelectorAll('[style*="repeat(91,"]').length,+ ).toBeGreaterThan(0);+ });+});diff --git a/apps/web/src/components/gantt/timeline.test.ts b/apps/web/src/components/gantt/timeline.test.tsnew file mode 100644index 000000000..4b7b31abb--- /dev/null+++ b/apps/web/src/components/gantt/timeline.test.ts@@ -0,0 +1,82 @@+import { addDays, differenceInCalendarDays, parseISO } from "date-fns";+import { describe, expect, it } from "vitest";+import {+ buildGanttTimeline,+ GANTT_WINDOW_DAYS,+ parseTaskDate,+} from "./timeline";++const span = (start: string, end = start) => ({+ scheduleStart: parseISO(start),+ scheduleEnd: parseISO(end),+});++describe("bounded Gantt timeline", () => {+ it("bounds allocation even for one task spanning years 0001 through 9999", () => {+ const timeline = buildGanttTimeline(+ [span("0001-01-01", "9999-12-31")],+ 1,+ 2.75,+ null,+ parseISO("2026-09-19"),+ );+ expect(timeline?.days).toHaveLength(GANTT_WINDOW_DAYS);+ expect(timeline?.rangeStart.getFullYear()).toBe(2026);+ expect(timeline?.timelineMinWidthRem).toBe(GANTT_WINDOW_DAYS * 2.75);+ });+ it("bounds separate distant tasks and supports jumping directly to either endpoint", () => {+ const tasks = [span("0001-01-01"), span("9999-12-31")];+ for (const date of ["0001-01-01", "9999-12-31"]) {+ const timeline = buildGanttTimeline(tasks, 1, 3, parseISO(date));+ expect(timeline?.days.length).toBeLessThanOrEqual(GANTT_WINDOW_DAYS);+ expect(+ timeline?.days.every((day) => Number.isFinite(day.getTime())),+ ).toBe(true);+ expect(parseISO(date).getTime()).toBeGreaterThanOrEqual(+ timeline?.rangeStart.getTime() ?? 0,+ );+ expect(parseISO(date).getTime()).toBeLessThanOrEqual(+ timeline?.rangeEnd.getTime() ?? 0,+ );+ }+ });+ it("retains week padding for a small normal schedule", () => {+ const timeline = buildGanttTimeline(+ [span("2026-09-14", "2026-09-18")],+ 1,+ 3,+ );+ expect(timeline?.rangeStart).toEqual(parseISO("2026-09-07"));+ expect(timeline?.rangeEnd).toEqual(parseISO("2026-10-18"));+ expect(timeline?.hasPrevious).toBe(false);+ expect(timeline?.hasNext).toBe(false);+ });+ it("pages a long project without gaps and stops at the final window", () => {+ const tasks = [span("2026-01-01", "2027-12-31")];+ let timeline = buildGanttTimeline(tasks, 0, 3, parseISO("2026-01-01"));+ for (let page = 0; page < 12 && timeline?.hasNext; page++) {+ const previous = timeline;+ timeline = buildGanttTimeline(+ tasks,+ 0,+ 3,+ addDays(previous.rangeStart, GANTT_WINDOW_DAYS),+ );+ expect(+ differenceInCalendarDays(+ timeline?.rangeStart ?? new Date(),+ previous.rangeEnd,+ ),+ ).toBeLessThanOrEqual(1);+ expect(timeline?.days.length).toBeLessThanOrEqual(GANTT_WINDOW_DAYS);+ }+ expect(timeline?.hasNext).toBe(false);+ expect(timeline?.rangeStart).toEqual(timeline?.maximumStart);+ });+ it.each([null, "invalid", "+275760-09-13", "-000001-01-01"])(+ "ignores unsupported legacy dates safely (%s)",+ (value) => {+ expect(parseTaskDate(value)).toBeNull();+ },+ );+});diff --git a/apps/web/src/components/gantt/timeline.ts b/apps/web/src/components/gantt/timeline.tsnew file mode 100644index 000000000..507bfd393--- /dev/null+++ b/apps/web/src/components/gantt/timeline.ts@@ -0,0 +1,96 @@+import {+ addDays,+ differenceInCalendarDays,+ eachDayOfInterval,+ endOfWeek,+ parseISO,+ startOfDay,+ startOfWeek,+ subDays,+} from "date-fns";++export const GANTT_WINDOW_DAYS = 91;+const minimumDate = parseISO("0001-01-01");+const maximumDate = parseISO("9999-12-31");++export function parseTaskDate(value: string | null) {+ if (!value) return null;+ const parsed = parseISO(value);+ return Number.isNaN(parsed.getTime()) ||+ parsed < minimumDate ||+ startOfDay(parsed) > maximumDate+ ? null+ : parsed;+}++function clampDate(date: Date, minimum: Date, maximum: Date) {+ return new Date(+ Math.max(minimum.getTime(), Math.min(date.getTime(), maximum.getTime())),+ );+}++export function buildGanttTimeline(+ tasks: { scheduleStart: Date; scheduleEnd: Date }[],+ weekStartsOn: 0 | 1 | 2 | 3 | 4 | 5 | 6,+ dayColumnWidthRem: number,+ requestedStart: Date | null = null,+ today: Date = new Date(),+) {+ if (tasks.length === 0) return null;+ let earliest = tasks[0].scheduleStart;+ let latest = tasks[0].scheduleEnd;+ for (const task of tasks) {+ if (task.scheduleStart < earliest) earliest = task.scheduleStart;+ if (task.scheduleEnd > latest) latest = task.scheduleEnd;+ }+ const minimumStart = clampDate(+ subDays(startOfWeek(earliest, { weekStartsOn }), 7),+ minimumDate,+ maximumDate,+ );+ const maximumEnd = clampDate(+ startOfDay(addDays(endOfWeek(latest, { weekStartsOn }), 28)),+ minimumDate,+ maximumDate,+ );+ const maximumStart = new Date(+ Math.max(+ minimumStart.getTime(),+ subDays(maximumEnd, GANTT_WINDOW_DAYS - 1).getTime(),+ ),+ );+ const fits =+ differenceInCalendarDays(maximumEnd, minimumStart) < GANTT_WINDOW_DAYS;+ const anchor = today >= earliest && today <= latest ? today : earliest;+ const defaultStart = fits+ ? minimumStart+ : subDays(startOfWeek(anchor, { weekStartsOn }), 7);+ const rangeStart = startOfDay(+ clampDate(+ requestedStart && !Number.isNaN(requestedStart.getTime())+ ? requestedStart+ : defaultStart,+ minimumStart,+ maximumStart,+ ),+ );+ const rangeEnd = clampDate(+ addDays(rangeStart, GANTT_WINDOW_DAYS - 1),+ rangeStart,+ maximumEnd,+ );+ // Bound BEFORE allocating Date objects or grid columns, including old/imported+ // tasks whose dates were never checked by today's API validation.+ const days = eachDayOfInterval({ start: rangeStart, end: rangeEnd });+ return {+ days,+ rangeStart,+ rangeEnd,+ minimumStart,+ maximumStart,+ hasPrevious: rangeStart > minimumStart,+ hasNext: rangeEnd < maximumEnd,+ gridTemplateColumns: `repeat(${days.length}, minmax(${dayColumnWidthRem}rem, ${dayColumnWidthRem}rem))`,+ timelineMinWidthRem: days.length * dayColumnWidthRem,+ };+}diff --git a/apps/web/src/components/kanban-board/task-card.tsx b/apps/web/src/components/kanban-board/task-card.tsxindex f79a0a4c7..e52cddd50 100644--- a/apps/web/src/components/kanban-board/task-card.tsx+++ b/apps/web/src/components/kanban-board/task-card.tsx@@ -40,6 +40,7 @@ import {getDueDateStatus,isTaskCompleted,} from "@/lib/due-date-status";+import { getExternalWebUrl, openExternalWebUrl } from "@/lib/external-url";import { getInitials } from "@/lib/get-initials";import { getTaskItemStats } from "@/lib/get-task-item-stats";import { getPriorityIcon } from "@/lib/priority";@@ -84,13 +85,18 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {const isTaskSelected = isSelected(task.id);const isTaskFocused = isFocused(task.id);const taskItemStats = useMemo(- () => getTaskItemStats(task.description),- [task.description],+ () =>+ showTaskItemCounts && !task.descriptionDeferred+ ? getTaskItemStats(task.description)+ : null,+ [task.description, task.descriptionDeferred, showTaskItemCounts],);const pullRequests = useMemo(() => {return (task.externalLinks ?? []).filter(- (link) => link.resourceType === "pull_request",+ (link) =>+ link.resourceType === "pull_request" &&+ getExternalWebUrl(link.url) !== null,);}, [task.externalLinks]);@@ -334,7 +340,7 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {</HoverCard>)}- {showTaskItemCounts && taskItemStats.total > 0 && (+ {taskItemStats && taskItemStats.total > 0 && (<spanclassName={cn("flex items-center gap-1 text-[10px] px-2 py-1 rounded bg-muted/50 text-muted-foreground h-5.5",@@ -372,7 +378,7 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {type="button"onClick={(e) => {e.stopPropagation();- window.open(pullRequests[0].url, "_blank");+ openExternalWebUrl(pullRequests[0].url);}}className="inline-flex items-center gap-1.5 rounded border border-border/70 bg-muted/55 px-2 py-1 text-[10px] font-medium text-muted-foreground">@@ -450,7 +456,7 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {)}<buttontype="button"- onClick={() => window.open(pr.url, "_blank")}+ onClick={() => openExternalWebUrl(pr.url)}className="w-full px-2 py-1.5 text-left hover:bg-muted/50 rounded transition-colors"><div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">diff --git a/apps/web/src/components/list-view/task-row.tsx b/apps/web/src/components/list-view/task-row.tsxindex a6a04f3cc..4ee0a2e8a 100644--- a/apps/web/src/components/list-view/task-row.tsx+++ b/apps/web/src/components/list-view/task-row.tsx@@ -36,6 +36,7 @@ import {getDueDateStatus,isTaskCompleted,} from "@/lib/due-date-status";+import { getExternalWebUrl, openExternalWebUrl } from "@/lib/external-url";import { getInitials } from "@/lib/get-initials";import { getPriorityIcon } from "@/lib/priority";import { toast } from "@/lib/toast";@@ -92,7 +93,9 @@ function TaskRow({ task, projectSlug }: TaskRowProps) {const pullRequests = useMemo(() => {return (task.externalLinks ?? []).filter(- (link) => link.resourceType === "pull_request",+ (link) =>+ link.resourceType === "pull_request" &&+ getExternalWebUrl(link.url) !== null,);}, [task.externalLinks]);@@ -223,7 +226,7 @@ function TaskRow({ task, projectSlug }: TaskRowProps) {type="button"onClick={(e) => {e.stopPropagation();- window.open(pullRequests[0].url, "_blank");+ openExternalWebUrl(pullRequests[0].url);}}className="inline-flex items-center gap-1.5 px-2 py-1 rounded border border-border bg-sidebar text-[10px] font-medium text-muted-foreground">@@ -301,9 +304,7 @@ function TaskRow({ task, projectSlug }: TaskRowProps) {)}<buttontype="button"- onClick={() =>- window.open(pr.url, "_blank")- }+ onClick={() => openExternalWebUrl(pr.url)}className="w-full px-2 py-1.5 text-left hover:bg-muted/50 rounded transition-colors"><div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">diff --git a/apps/web/src/components/project/gitea-repository-browser-modal.test.tsx b/apps/web/src/components/project/gitea-repository-browser-modal.test.tsxnew file mode 100644index 000000000..24b73e08e--- /dev/null+++ b/apps/web/src/components/project/gitea-repository-browser-modal.test.tsx@@ -0,0 +1,121 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { GiteaRepositoryBrowserModal } from "./gitea-repository-browser-modal";++const m = vi.hoisted(() => ({ list: vi.fn(), userId: "user-1" }));+vi.mock("@/fetchers/gitea-integration/list-gitea-repositories", () => ({+ default: m.list,+}));+vi.mock("@/lib/auth-client", () => ({+ authClient: { useSession: () => ({ data: { user: { id: m.userId } } }) },+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+ initReactI18next: { type: "3rdParty", init: vi.fn() },+}));+const clients: QueryClient[] = [];+afterEach(() => {+ cleanup();+ for (const client of clients) client.clear();+ clients.length = 0;+});+beforeEach(() => {+ vi.resetAllMocks();+ m.userId = "user-1";+});+const result = (name: string) => ({+ repositories: [+ {+ id: 1,+ name,+ full_name: `owner/${name}`,+ owner: { login: "owner" },+ private: true,+ html_url: "https://gitea.example/owner/repo",+ },+ ],+});+function show() {+ const client = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ staleTime: Number.POSITIVE_INFINITY,+ placeholderData: (previous: unknown) => previous,+ },+ },+ });+ clients.push(client);+ const node = (accessToken: string) => (+ <QueryClientProvider client={client}>+ <GiteaRepositoryBrowserModal+ open+ projectId="project"+ baseUrl="https://gitea.example"+ accessToken={accessToken}+ onOpenChange={vi.fn()}+ onSelectRepository={vi.fn()}+ />+ </QueryClientProvider>+ );+ const view = render(node("privileged-secret"));+ return { client, change: (token: string) => view.rerender(node(token)) };+}++describe("Gitea repository credential isolation", () => {+ it("hides privileged cached repositories immediately when a token changes, including on errors", async () => {+ m.list+ .mockResolvedValueOnce(result("private-repo"))+ .mockRejectedValueOnce(new Error("Unauthorized"));+ const { client, change } = show();+ await screen.findByText("owner/private-repo");+ change("unprivileged-secret");+ expect(screen.queryByText("owner/private-repo")).toBeNull();+ await screen.findByText("Unauthorized");+ expect(screen.queryByText("owner/private-repo")).toBeNull();+ expect(+ JSON.stringify(+ client+ .getQueryCache()+ .getAll()+ .map((query) => query.queryKey),+ ),+ ).not.toMatch(/privileged-secret/);+ });++ it("cannot display a late response from the previous token", async () => {+ let resolve!: (value: ReturnType<typeof result>) => void;+ m.list+ .mockImplementationOnce(+ () =>+ new Promise((done) => {+ resolve = done;+ }),+ )+ .mockResolvedValueOnce(result("allowed-repo"));+ const { change } = show();+ await waitFor(() => expect(m.list).toHaveBeenCalledTimes(1));+ change("restricted-token");+ await screen.findByText("owner/allowed-repo");+ await act(async () => {+ resolve(result("private-repo"));+ });+ expect(screen.queryByText("owner/private-repo")).toBeNull();+ expect(screen.getByText("owner/allowed-repo")).toBeInTheDocument();+ });++ it("isolates sessions even when the token and project props stay unchanged", async () => {+ m.list+ .mockResolvedValueOnce(result("private-repo"))+ .mockResolvedValueOnce(result("new-session-repo"));+ const { change } = show();+ await screen.findByText("owner/private-repo");+ m.userId = "user-2";+ change("privileged-secret");+ expect(screen.queryByText("owner/private-repo")).toBeNull();+ await screen.findByText("owner/new-session-repo");+ change("");+ expect(screen.queryByText("owner/new-session-repo")).toBeNull();+ });+});diff --git a/apps/web/src/components/project/gitea-repository-browser-modal.tsx b/apps/web/src/components/project/gitea-repository-browser-modal.tsxindex 002997e8d..d3aacf17d 100644--- a/apps/web/src/components/project/gitea-repository-browser-modal.tsx+++ b/apps/web/src/components/project/gitea-repository-browser-modal.tsx@@ -15,6 +15,7 @@ import { Input } from "@/components/ui/input";import listGiteaRepositories, {type ListGiteaRepositoriesResponse,} from "@/fetchers/gitea-integration/list-gitea-repositories";+import { authClient } from "@/lib/auth-client";import { cn } from "@/lib/cn";type GiteaRepositoryBrowserModalProps = {@@ -38,14 +39,37 @@ export function GiteaRepositoryBrowserModal({}: GiteaRepositoryBrowserModalProps) {const { t } = useTranslation();const [searchTerm, setSearchTerm] = React.useState("");+ const { data: session } = authClient.useSession();+ // A credential change needs a fresh cache namespace without putting the+ // secret itself into serializable query keys, logs or query devtools.+ const credentials = React.useMemo(+ () => ({ accessToken, cacheId: crypto.randomUUID() }),+ [accessToken],+ );const canFetch =- open && baseUrl.trim().length > 0 && accessToken.trim().length > 0;+ open &&+ Boolean(session?.user.id) &&+ baseUrl.trim().length > 0 &&+ accessToken.trim().length > 0;const { data, isLoading, error, refetch } = useQuery({- queryKey: ["gitea-repositories", projectId, baseUrl],- queryFn: () => listGiteaRepositories({ projectId, baseUrl, accessToken }),+ queryKey: [+ "gitea-repositories",+ session?.user.id,+ projectId,+ baseUrl,+ credentials.cacheId,+ ],+ queryFn: () =>+ listGiteaRepositories({+ projectId,+ baseUrl,+ accessToken: credentials.accessToken,+ }),enabled: canFetch,+ gcTime: 0,+ placeholderData: () => undefined,});const filteredRepositories = React.useMemo(() => {diff --git a/apps/web/src/components/project/github-integration-settings.test.tsx b/apps/web/src/components/project/github-integration-settings.test.tsxnew file mode 100644index 000000000..a791bbb41--- /dev/null+++ b/apps/web/src/components/project/github-integration-settings.test.tsx@@ -0,0 +1,214 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const m = vi.hoisted(() => ({+ appInfo: vi.fn(),+ link: vi.fn(),+ importIssues: vi.fn(),+ integration: { current: null as null | Record<string, unknown> },+}));+vi.mock("@/fetchers/github-integration/get-app-info", () => ({+ default: m.appInfo,+}));+vi.mock("@/lib/auth-client", () => ({+ authClient: {+ useSession: () => ({ data: { user: { id: "user-1" } } }),+ linkSocial: m.link,+ },+}));+vi.mock(+ "@/hooks/queries/github-integration/use-get-github-integration",+ () => ({+ default: () => ({ data: m.integration.current, isLoading: false }),+ }),+);+vi.mock(+ "@/hooks/mutations/github-integration/use-create-github-integration",+ () => ({+ useCreateGithubIntegration: () => ({+ mutateAsync: vi.fn(),+ isPending: false,+ }),+ useDeleteGithubIntegration: () => ({+ mutateAsync: vi.fn(),+ isPending: false,+ }),+ useVerifyGithubInstallation: () => ({+ mutateAsync: vi.fn(),+ isPending: false,+ }),+ }),+);+vi.mock(+ "@/hooks/mutations/github-integration/use-import-github-issues",+ () => ({+ default: () => ({ mutateAsync: m.importIssues, isPending: false }),+ }),+);+vi.mock(+ "@/hooks/mutations/github-integration/use-update-github-integration",+ () => ({+ useUpdateGithubIntegration: () => ({+ mutateAsync: vi.fn(),+ isPending: false,+ }),+ }),+);+vi.mock("@/components/project/repository-browser-modal", () => ({+ RepositoryBrowserModal: () => null,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("@/lib/toast", () => ({+ toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },+}));++import { toast } from "@/lib/toast";++import { GitHubIntegrationSettings } from "./github-integration-settings";++function show() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <GitHubIntegrationSettings projectId="project" />+ </QueryClientProvider>,+ );+}+afterEach(() => cleanup());+beforeEach(() => {+ vi.clearAllMocks();+ m.integration.current = null;+ m.link.mockResolvedValue({ error: null });+});+describe("GitHub account verification flow", () => {+ it("offers explicit account linking and returns to the same settings page", async () => {+ m.appInfo.mockResolvedValue({+ accountConnected: false,+ accountLinkingAvailable: true,+ });+ show();+ const button = await screen.findByRole("button", {+ name: "settings:githubIntegration.connect GitHub",+ });+ fireEvent.click(button);+ await waitFor(() =>+ expect(m.link).toHaveBeenCalledWith({+ provider: "github",+ callbackURL: window.location.href,+ }),+ );+ expect(+ screen.getByRole("button", { name: "settings:githubIntegration.browse" }),+ ).toBeDisabled();+ });+ it("explains the administrator prerequisite when GitHub sign-in is disabled", async () => {+ m.appInfo.mockResolvedValue({+ accountConnected: false,+ accountLinkingAvailable: false,+ });+ show();+ expect(+ await screen.findByText(+ "settings:githubIntegration.enableGithubSignInHint",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", {+ name: "settings:githubIntegration.connect GitHub",+ }),+ ).not.toBeInTheDocument();+ });+ it("shows reconnection for legacy integrations and still permits removal", async () => {+ m.appInfo.mockResolvedValue({+ accountConnected: true,+ accountLinkingAvailable: true,+ });+ m.integration.current = {+ repositoryOwner: "owner",+ repositoryName: "repo",+ requiresVerification: true,+ isActive: false,+ };+ show();+ expect(+ await screen.findByText("settings:githubIntegration.reverifyHint"),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", {+ name: "settings:githubIntegration.disconnect",+ }),+ ).toBeEnabled();+ expect(+ screen.getByText("settings:githubIntegration.badgeNotConnected"),+ ).toBeInTheDocument();+ });+});++describe("saved GitHub import progress", () => {+ it("offers resume after refresh and forwards the persisted run ID", async () => {+ m.appInfo.mockResolvedValue({+ accountConnected: true,+ accountLinkingAvailable: true,+ });+ m.integration.current = {+ repositoryOwner: "owner",+ repositoryName: "repo",+ installationId: 1,+ requiresVerification: false,+ isActive: true,+ importProgress: {+ runId: "saved-run",+ pending: true,+ imported: 4,+ updated: 0,+ skipped: 0,+ },+ };+ let complete!: (result: unknown) => void;+ m.importIssues.mockImplementation(+ () =>+ new Promise((resolve) => {+ complete = resolve;+ }),+ );+ show();+ const resume = await screen.findByRole("button", {+ name: "settings:githubIntegration.resumeImport",+ });+ expect(screen.getByRole("status")).toHaveTextContent(+ "settings:githubIntegration.importPaused",+ );+ fireEvent.click(resume);+ await waitFor(() =>+ expect(m.importIssues).toHaveBeenCalledWith({+ projectId: "project",+ runId: "saved-run",+ }),+ );+ expect(toast.success).not.toHaveBeenCalled();+ complete({+ runId: "saved-run",+ pending: false,+ imported: 9,+ updated: 1,+ skipped: 2,+ });+ await waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith(+ "settings:githubIntegration.toast.issuesImported",+ { description: "settings:githubIntegration.importSummary" },+ ),+ );+ });+});diff --git a/apps/web/src/components/project/github-integration-settings.tsx b/apps/web/src/components/project/github-integration-settings.tsxindex 62704d9b8..56ffb302c 100644--- a/apps/web/src/components/project/github-integration-settings.tsx+++ b/apps/web/src/components/project/github-integration-settings.tsx@@ -1,4 +1,5 @@import { standardSchemaResolver } from "@hookform/resolvers/standard-schema";+import { useQuery } from "@tanstack/react-query";import {AlertTriangle,CheckCircle,@@ -29,6 +30,7 @@ import {import { Input } from "@/components/ui/input";import { Separator } from "@/components/ui/separator";import { Switch } from "@/components/ui/switch";+import getGitHubAppInfo from "@/fetchers/github-integration/get-app-info";import type { VerifyGithubInstallationResponse } from "@/fetchers/github-integration/verify-github-installation";import {useCreateGithubIntegration,@@ -38,6 +40,7 @@ import {import useImportGithubIssues from "@/hooks/mutations/github-integration/use-import-github-issues";import { useUpdateGithubIntegration } from "@/hooks/mutations/github-integration/use-update-github-integration";import useGetGithubIntegration from "@/hooks/queries/github-integration/use-get-github-integration";+import { authClient } from "@/lib/auth-client";import { cn } from "@/lib/cn";import { toast } from "@/lib/toast";@@ -52,6 +55,31 @@ export function GitHubIntegrationSettings({projectId: string;}) {const { t } = useTranslation();+ const { data: session } = authClient.useSession();+ const { data: appInfo } = useQuery({+ queryKey: ["github-app-info", session?.user.id],+ queryFn: getGitHubAppInfo,+ enabled: Boolean(session?.user.id),+ });+ const [isLinkingAccount, setIsLinkingAccount] = React.useState(false);+ const linkAccount = async () => {+ setIsLinkingAccount(true);+ try {+ const result = await authClient.linkSocial({+ provider: "github",+ callbackURL: window.location.href,+ });+ if (result.error) throw new Error(result.error.message);+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : t("settings:githubIntegration.toast.updateError"),+ );+ } finally {+ setIsLinkingAccount(false);+ }+ };const githubIntegrationSchema = React.useMemo(() =>z.object({@@ -146,10 +174,16 @@ export function GitHubIntegrationSettings({);React.useEffect(() => {- if (repositoryOwner && repositoryName && form.formState.isValid) {+ if (+ appInfo?.accountConnected &&+ repositoryOwner &&+ repositoryName &&+ form.formState.isValid+ ) {handleVerifyInstallation({ repositoryOwner, repositoryName }, false);}}, [+ appInfo?.accountConnected,repositoryOwner,repositoryName,form.formState.isValid,@@ -224,8 +258,15 @@ export function GitHubIntegrationSettings({const handleImportIssues = async () => {try {- await importIssues({ projectId });- toast.success(t("settings:githubIntegration.toast.issuesImported"));+ const result = await importIssues({+ projectId,+ ...(integration?.importProgress?.pending+ ? { runId: integration.importProgress.runId }+ : {}),+ });+ toast.success(t("settings:githubIntegration.toast.issuesImported"), {+ description: t("settings:githubIntegration.importSummary", result),+ });} catch (error) {toast.error(error instanceof Error@@ -257,13 +298,42 @@ export function GitHubIntegrationSettings({}const isConnected = !!integration && integration.isActive;- const canImport =- isConnected &&- verificationResult?.isInstalled &&- verificationResult?.hasRequiredPermissions;+ // The saved binding is verified again by each import request. Resuming must+ // also work after refresh, without a new administrator-only account check.+ const canImport = isConnected && !integration.requiresVerification;return (<div className="space-y-4">+ {appInfo && !appInfo.accountConnected && (+ <div className="space-y-3 rounded-md border border-border bg-sidebar p-4">+ <p className="text-sm">+ {t("settings:githubIntegration.accountVerificationHint")}+ </p>+ {appInfo.accountLinkingAvailable ? (+ <Button+ type="button"+ variant="outline"+ loading={isLinkingAccount}+ onClick={linkAccount}+ >+ <GithubIcon aria-hidden="true" />+ {t("settings:githubIntegration.connect")} GitHub+ </Button>+ ) : (+ <p className="text-sm text-muted-foreground">+ {t("settings:githubIntegration.enableGithubSignInHint")}+ </p>+ )}+ </div>+ )}+ {integration?.requiresVerification && (+ <p+ role="status"+ className="rounded-md border border-border p-4 text-sm"+ >+ {t("settings:githubIntegration.reverifyHint")}+ </p>+ )}<div className="space-y-4 border border-border rounded-md p-4 bg-sidebar"><div className="flex items-center justify-between"><div className="space-y-0.5">@@ -489,6 +559,7 @@ export function GitHubIntegrationSettings({variant="outline"size="sm"onClick={() => setShowRepositoryBrowser(true)}+ disabled={!appInfo?.accountConnected}className="gap-2"><GitBranch className="size-3" />@@ -500,7 +571,11 @@ export function GitHubIntegrationSettings({variant="outline"size="sm"onClick={() => handleVerifyInstallation(form.getValues())}- disabled={isVerifying || !form.formState.isValid}+ disabled={+ !appInfo?.accountConnected ||+ isVerifying ||+ !form.formState.isValid+ }className="gap-2"><RefreshCw@@ -513,6 +588,7 @@ export function GitHubIntegrationSettings({type="submit"size="sm"disabled={+ !appInfo?.accountConnected ||isCreating ||isDeleting ||!form.formState.isValid ||@@ -529,7 +605,7 @@ export function GitHubIntegrationSettings({: t("settings:githubIntegration.connect")}</Button>- {isConnected && (+ {integration && (<Buttontype="button"variant="destructive"@@ -665,10 +741,21 @@ export function GitHubIntegrationSettings({)}{isImporting? t("settings:githubIntegration.importing")- : t("settings:githubIntegration.importIssues")}+ : integration?.importProgress?.pending+ ? t("settings:githubIntegration.resumeImport")+ : t("settings:githubIntegration.importIssues")}</Button></div></div>+ {integration?.importProgress?.pending && !isImporting && (+ <p role="status" className="text-xs text-muted-foreground">+ {t("settings:githubIntegration.importPaused")}{" "}+ {t(+ "settings:githubIntegration.importSummary",+ integration.importProgress,+ )}+ </p>+ )}{!canImport && (<><Separator />diff --git a/apps/web/src/components/project/repository-browser-modal.test.tsx b/apps/web/src/components/project/repository-browser-modal.test.tsxnew file mode 100644index 000000000..ccc562608--- /dev/null+++ b/apps/web/src/components/project/repository-browser-modal.test.tsx@@ -0,0 +1,146 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { RepositoryBrowserModal } from "./repository-browser-modal";++const m = vi.hoisted(() => ({ list: vi.fn(), userId: "user-1" }));+vi.mock("@/fetchers/github-integration/list-repositories", () => ({+ default: m.list,+}));+vi.mock("@/fetchers/github-integration/get-app-info", () => ({+ default: async () => ({ appName: null }),+}));+vi.mock("@/lib/auth-client", () => ({+ authClient: { useSession: () => ({ data: { user: { id: m.userId } } }) },+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+ initReactI18next: { type: "3rdParty", init: vi.fn() },+}));+const clients: QueryClient[] = [];+afterEach(() => {+ cleanup();+ for (const client of clients) client.clear();+ clients.length = 0;+});+beforeEach(() => {+ vi.clearAllMocks();+ m.userId = "user-1";+});+function result(+ name: string,+ nextPage: { installationPage: number; repositoryPage: number } | null,+) {+ return {+ repositories: name+ ? [+ {+ id: 1,+ name,+ full_name: `owner/${name}`,+ owner: { login: "owner", avatar_url: "", type: "User" },+ private: true,+ html_url: "https://github.com/owner/repo",+ description: "",+ updated_at: "2026-09-01",+ },+ ]+ : [],+ installations: [],+ total: name ? 1 : 0,+ nextPage,+ };+}+function show() {+ const client = new QueryClient({+ defaultOptions: {+ queries: { retry: false, staleTime: Number.POSITIVE_INFINITY },+ },+ });+ clients.push(client);+ const selected = vi.fn();+ const node = () => (+ <QueryClientProvider client={client}>+ <RepositoryBrowserModal+ open+ projectId="project"+ onOpenChange={vi.fn()}+ onSelectRepository={selected}+ />+ </QueryClientProvider>+ );+ const view = render(node());+ return { selected, refresh: () => view.rerender(node()) };+}+describe("bounded GitHub repository browser", () => {+ it("requests later pages only on Next, including an empty installation page, and supports Previous", async () => {+ m.list+ .mockResolvedValueOnce(+ result("first", { installationPage: 2, repositoryPage: 1 }),+ )+ .mockResolvedValueOnce(+ result("", { installationPage: 3, repositoryPage: 1 }),+ )+ .mockResolvedValueOnce(result("last", null));+ const { selected } = show();+ await screen.findByText("owner/first");+ expect(m.list).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByText("common:pagination.next"));+ await screen.findByText("settings:repositoryBrowser.emptyTitle");+ expect(m.list).toHaveBeenLastCalledWith("project", {+ installationPage: 2,+ repositoryPage: 1,+ });+ fireEvent.click(screen.getByText("common:pagination.next"));+ await screen.findByText("owner/last");+ expect(+ screen.getByText("common:pagination.next").closest("button"),+ ).toBeDisabled();+ fireEvent.click(screen.getByText("common:pagination.previous"));+ await screen.findByText("settings:repositoryBrowser.emptyTitle");+ fireEvent.click(screen.getByText("common:pagination.previous"));+ await screen.findByText("owner/first");+ expect(m.list).toHaveBeenCalledTimes(3);+ fireEvent.click(screen.getByText("owner/first"));+ expect(selected).toHaveBeenCalledWith({ owner: "owner", name: "first" });+ });+ it("isolates cached results after an account switch", async () => {+ m.list+ .mockResolvedValueOnce(result("private-old-user", null))+ .mockRejectedValueOnce(new Error("Forbidden"));+ const { refresh } = show();+ await screen.findByText("owner/private-old-user");+ m.userId = "user-2";+ refresh();+ expect(screen.queryByText("owner/private-old-user")).toBeNull();+ await screen.findByText("settings:repositoryBrowser.loadError");+ expect(screen.queryByText("owner/private-old-user")).toBeNull();+ });+ it("retries a failed continuation without silently showing the previous page", async () => {+ m.list+ .mockResolvedValueOnce(+ result("first", { installationPage: 1, repositoryPage: 2 }),+ )+ .mockRejectedValueOnce(new Error("Unavailable"))+ .mockResolvedValueOnce(result("second", null));+ show();+ await screen.findByText("owner/first");+ fireEvent.click(screen.getByText("common:pagination.next"));+ await screen.findByText("settings:repositoryBrowser.loadError");+ expect(screen.queryByText("owner/first")).toBeNull();+ fireEvent.click(screen.getByText("settings:repositoryBrowser.tryAgain"));+ await screen.findByText("owner/second");+ await waitFor(() =>+ expect(m.list).toHaveBeenLastCalledWith("project", {+ installationPage: 1,+ repositoryPage: 2,+ }),+ );+ });+});diff --git a/apps/web/src/components/project/repository-browser-modal.tsx b/apps/web/src/components/project/repository-browser-modal.tsxindex c83b143b3..dc5ea01ac 100644--- a/apps/web/src/components/project/repository-browser-modal.tsx+++ b/apps/web/src/components/project/repository-browser-modal.tsx@@ -26,8 +26,11 @@ import { Separator } from "@/components/ui/separator";import getGitHubAppInfo from "@/fetchers/github-integration/get-app-info";import listRepositories, {type ListRepositoriesResponse,+ type RepositoryPage,} from "@/fetchers/github-integration/list-repositories";+import { authClient } from "@/lib/auth-client";import { cn } from "@/lib/cn";+import { openExternalWebUrl } from "@/lib/external-url";import { getInitials } from "@/lib/get-initials";type RepositoryBrowserModalProps = {@@ -47,15 +50,23 @@ export function RepositoryBrowserModal({}: RepositoryBrowserModalProps) {const { t } = useTranslation();const [searchTerm, setSearchTerm] = React.useState("");+ const { data: session } = authClient.useSession();+ const [pageHistory, setPageHistory] = React.useState<RepositoryPage[]>([+ { installationPage: 1, repositoryPage: 1 },+ ]);+ const page = pageHistory[pageHistory.length - 1] ?? {+ installationPage: 1,+ repositoryPage: 1,+ };const { data, isLoading, error, refetch } = useQuery({- queryKey: ["github-repositories", projectId],- queryFn: () => listRepositories(projectId),- enabled: open,+ queryKey: ["github-repositories", projectId, session?.user.id, page],+ queryFn: () => listRepositories(projectId, page),+ enabled: open && Boolean(session?.user.id),});const { data: appInfo } = useQuery({- queryKey: ["github-app-info"],+ queryKey: ["github-app-info", session?.user.id],queryFn: getGitHubAppInfo,enabled: open,});@@ -112,6 +123,7 @@ export function RepositoryBrowserModal({const resetAndCloseModal = (open: boolean) => {if (!open) {setSearchTerm("");+ setPageHistory([{ installationPage: 1, repositoryPage: 1 }]);}onOpenChange(open);};@@ -269,7 +281,7 @@ export function RepositoryBrowserModal({size="sm"onClick={(e) => {e.stopPropagation();- window.open(repository.html_url, "_blank");+ openExternalWebUrl(repository.html_url);}}className="opacity-0 group-hover:opacity-100 transition-opacity">@@ -298,6 +310,29 @@ export function RepositoryBrowserModal({)}</div>+ {data && (+ <div className="flex items-center justify-between gap-2 border-t px-6 py-3">+ <Button+ type="button"+ variant="outline"+ disabled={pageHistory.length <= 1}+ onClick={() => setPageHistory((pages) => pages.slice(0, -1))}+ >+ {t("common:pagination.previous")}+ </Button>+ <Button+ type="button"+ variant="outline"+ disabled={!data.nextPage}+ onClick={() => {+ const next = data.nextPage;+ if (next) setPageHistory((pages) => [...pages, next]);+ }}+ >+ {t("common:pagination.next")}+ </Button>+ </div>+ )}{data && data.installations.length > 0 && (<><Separator />diff --git a/apps/web/src/components/public-project/project-description.test.tsx b/apps/web/src/components/public-project/project-description.test.tsxnew file mode 100644index 000000000..488ed251a--- /dev/null+++ b/apps/web/src/components/public-project/project-description.test.tsx@@ -0,0 +1,52 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { getPublicProjectDescription } from "@/fetchers/task/get-description-pages";+import { PublicProjectDescription } from "./project-description";++vi.mock("@/fetchers/task/get-description-pages", () => ({+ getPublicProjectDescription: vi.fn(),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+afterEach(() => {+ cleanup();+ vi.resetAllMocks();+});+it("loads deferred project text, with an explicit retry after failure", async () => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ vi.mocked(getPublicProjectDescription)+ .mockRejectedValueOnce(new Error("changed"))+ .mockResolvedValueOnce("Full project description");+ render(+ <QueryClientProvider client={client}>+ <PublicProjectDescription+ project={{+ id: "project",+ description: null,+ descriptionDeferred: true,+ }}+ />+ </QueryClientProvider>,+ );+ await screen.findByRole("alert");+ fireEvent.click(screen.getByText("tasks:descriptionRetry"));+ expect(await screen.findByText("Full project description")).toBeTruthy();+ client.clear();+});+it("keeps ordinary project descriptions immediate", () => {+ const client = new QueryClient();+ render(+ <QueryClientProvider client={client}>+ <PublicProjectDescription+ project={{ id: "project", description: "Small description" }}+ />+ </QueryClientProvider>,+ );+ expect(screen.getByText("Small description")).toBeTruthy();+ expect(getPublicProjectDescription).not.toHaveBeenCalled();+ client.clear();+});diff --git a/apps/web/src/components/public-project/project-description.tsx b/apps/web/src/components/public-project/project-description.tsxnew file mode 100644index 000000000..97fd84caa--- /dev/null+++ b/apps/web/src/components/public-project/project-description.tsx@@ -0,0 +1,46 @@+import { useQuery } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { getPublicProjectDescription } from "@/fetchers/task/get-description-pages";++export function PublicProjectDescription({+ project,+}: {+ project: {+ id: string;+ description: string | null;+ descriptionDeferred?: boolean;+ };+}) {+ const { t } = useTranslation();+ const query = useQuery({+ queryKey: ["public-project-description", project.id],+ queryFn: ({ signal }) => getPublicProjectDescription(project.id, signal),+ enabled: !!project.descriptionDeferred,+ retry: false,+ staleTime: 0,+ gcTime: 0,+ });+ if (project.descriptionDeferred && query.isLoading)+ return (+ <p role="status" className="text-xs text-muted-foreground">+ {t("tasks:descriptionLoading")}+ </p>+ );+ if (project.descriptionDeferred && query.isError)+ return (+ <p role="alert" className="text-xs text-muted-foreground">+ {t("tasks:descriptionLoadError")}{" "}+ <button+ type="button"+ className="underline"+ onClick={() => void query.refetch()}+ >+ {t("tasks:descriptionRetry")}+ </button>+ </p>+ );+ const text = project.descriptionDeferred ? query.data : project.description;+ return text ? (+ <p className="text-xs text-muted-foreground truncate">{text}</p>+ ) : null;+}diff --git a/apps/web/src/components/public-project/public-pr-badge.tsx b/apps/web/src/components/public-project/public-pr-badge.tsxindex 40109227a..c8ee19701 100644--- a/apps/web/src/components/public-project/public-pr-badge.tsx+++ b/apps/web/src/components/public-project/public-pr-badge.tsx@@ -6,6 +6,7 @@ import {HoverCardContent,HoverCardTrigger,} from "@/components/ui/preview-card";+import { getExternalWebUrl, openExternalWebUrl } from "@/lib/external-url";import type { ExternalLink } from "@/types/external-link";type PublicPRBadgeProps = {@@ -16,7 +17,11 @@ export function PublicPRBadge({ externalLinks }: PublicPRBadgeProps) {const { t } = useTranslation();const pullRequests = useMemo(() => {if (!externalLinks) return [];- return externalLinks.filter((link) => link.resourceType === "pull_request");+ return externalLinks.filter(+ (link) =>+ link.resourceType === "pull_request" &&+ getExternalWebUrl(link.url) !== null,+ );}, [externalLinks]);if (pullRequests.length === 0) return null;@@ -56,7 +61,7 @@ export function PublicPRBadge({ externalLinks }: PublicPRBadgeProps) {type="button"onClick={(e) => {e.stopPropagation();- window.open(pullRequests[0].url, "_blank");+ openExternalWebUrl(pullRequests[0].url);}}className="inline-flex items-center gap-1.5 px-2 py-1 rounded border border-border bg-sidebar text-[10px] font-medium text-muted-foreground hover:bg-muted/50 transition-colors">@@ -122,7 +127,7 @@ export function PublicPRBadge({ externalLinks }: PublicPRBadgeProps) {{index > 0 && <hr className="border-border my-1" />}<buttontype="button"- onClick={() => window.open(pr.url, "_blank")}+ onClick={() => openExternalWebUrl(pr.url)}className="w-full px-2 py-1.5 text-left hover:bg-muted/50 rounded transition-colors"><div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">diff --git a/apps/web/src/components/public-project/task-detail-modal.test.tsx b/apps/web/src/components/public-project/task-detail-modal.test.tsxnew file mode 100644index 000000000..97fd76211--- /dev/null+++ b/apps/web/src/components/public-project/task-detail-modal.test.tsx@@ -0,0 +1,111 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { getPublicTaskDescription } from "@/fetchers/task/get-description-pages";+import type Task from "@/types/task";+import { PublicTaskDetailModal } from "./task-detail-modal";++vi.mock("@/fetchers/task/get-description-pages", () => ({+ getPublicTaskDescription: vi.fn(),+}));+vi.mock("react-i18next", async (importOriginal) => ({+ ...(await importOriginal<typeof import("react-i18next")>()),+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("./markdown-renderer", () => ({+ MarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div>,+}));+vi.mock("@/components/ui/dialog", () => ({+ Dialog: ({ open, children }: { open: boolean; children: ReactNode }) =>+ open ? <div>{children}</div> : null,+ DialogPopup: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ DialogClose: ({ children }: { children: ReactNode }) => (+ <button type="button">{children}</button>+ ),+}));+const task: Task = {+ id: "task",+ projectId: "project",+ title: "Task",+ number: 1,+ description: null,+ descriptionDeferred: true,+ status: "",+ priority: null,+ startDate: null,+ dueDate: null,+ position: 0,+ createdAt: "2026-01-01T00:00:00Z",+ userId: null,+ assigneeId: null,+ assigneeName: null,+};+let client: QueryClient;+function modal(selected: Task | null, open = true) {+ return (+ <QueryClientProvider client={client}>+ <PublicTaskDetailModal+ task={selected}+ projectSlug="PRJ"+ open={open}+ onOpenChange={() => {}}+ />+ </QueryClientProvider>+ );+}+beforeEach(() => {+ vi.clearAllMocks();+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+});+afterEach(() => {+ cleanup();+ client.clear();+});++describe("public deferred task details", () => {+ it("loads only when opened, shows loading, then renders the full description", async () => {+ let resolve!: (value: string) => void;+ vi.mocked(getPublicTaskDescription).mockReturnValue(+ new Promise<string>((done) => {+ resolve = done;+ }),+ );+ const view = render(modal(task, false));+ expect(getPublicTaskDescription).not.toHaveBeenCalled();+ view.rerender(modal(task));+ expect(screen.getByRole("status").textContent).toContain(+ "descriptionLoading",+ );+ resolve("Full deferred description");+ expect(await screen.findByText("Full deferred description")).toBeTruthy();+ expect(getPublicTaskDescription).toHaveBeenCalledWith(+ "project",+ "task",+ expect.any(AbortSignal),+ );+ });+ it("shows a retry on failure and does not display partial content as success", async () => {+ vi.mocked(getPublicTaskDescription)+ .mockRejectedValueOnce(new Error("changed"))+ .mockResolvedValueOnce("Current revision");+ render(modal(task));+ await screen.findByRole("alert");+ fireEvent.click(screen.getByText("tasks:descriptionRetry"));+ expect(await screen.findByText("Current revision")).toBeTruthy();+ await waitFor(() => expect(screen.queryByRole("alert")).toBeNull());+ });+ it("renders ordinary descriptions without requesting chunks", () => {+ render(+ modal({ ...task, descriptionDeferred: false, description: "Small text" }),+ );+ expect(screen.getByText("Small text")).toBeTruthy();+ expect(getPublicTaskDescription).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/components/public-project/task-detail-modal.tsx b/apps/web/src/components/public-project/task-detail-modal.tsxindex d1cd14d41..21a8f0931 100644--- a/apps/web/src/components/public-project/task-detail-modal.tsx+++ b/apps/web/src/components/public-project/task-detail-modal.tsx@@ -12,6 +12,7 @@ import { useMemo } from "react";import { useTranslation } from "react-i18next";import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";import { Dialog, DialogClose, DialogPopup } from "@/components/ui/dialog";+import { usePublicTaskDescription } from "@/hooks/queries/task/use-public-task-description";import {dueDateStatusColors,getDueDateStatus,@@ -49,6 +50,12 @@ export function PublicTaskDetailModal({}: PublicTaskDetailModalProps) {const taskIsCompleted = isTaskCompleted(task?.status ?? "", columns);const { t } = useTranslation();+ const descriptionQuery = usePublicTaskDescription(task, open);+ const description = task?.descriptionDeferred+ ? descriptionQuery.isError+ ? undefined+ : descriptionQuery.data+ : task?.description;const getPRStatus = useMemo(() => (pr: { metadata?: { merged?: boolean; draft?: boolean } | null }) => {@@ -168,9 +175,24 @@ export function PublicTaskDetailModal({</div></div>- {task.description && (+ {task.descriptionDeferred && descriptionQuery.isLoading && (+ <p role="status">{t("tasks:descriptionLoading")}</p>+ )}+ {task.descriptionDeferred && descriptionQuery.isError && (+ <p role="alert">+ {t("tasks:descriptionLoadError")}{" "}+ <button+ type="button"+ className="underline"+ onClick={() => void descriptionQuery.refetch()}+ >+ {t("tasks:descriptionRetry")}+ </button>+ </p>+ )}+ {description && (<div className="pt-1">- <MarkdownRenderer content={task.description} />+ <MarkdownRenderer content={description} /></div>)}diff --git a/apps/web/src/components/shared/modals/create-task-modal.test.tsx b/apps/web/src/components/shared/modals/create-task-modal.test.tsxindex d5d99ceb1..cf9b18520 100644--- a/apps/web/src/components/shared/modals/create-task-modal.test.tsx+++ b/apps/web/src/components/shared/modals/create-task-modal.test.tsx@@ -1,7 +1,14 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+} from "@testing-library/react";import type { ReactNode } from "react";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import CreateTaskModal from "./create-task-modal";function createTestQueryClient() {@@ -25,6 +32,23 @@ function createWrapper() {}const useLocation = vi.fn();+const deleteTask = vi.fn(async () => {});+const updateTask = vi.fn(async (input: Record<string, unknown>) => input);+const setProject = vi.fn();+let workspaceId = "workspace-1";+let projects: { id: string; name: string; slug: string }[] | undefined;+let storedProject: { id: string; columns: unknown[] } | null = null;+let ensureTaskId: (() => Promise<string | null>) | undefined;++beforeEach(() => {+ workspaceId = "workspace-1";+ projects = [+ { id: "project-1", name: "Alpha", slug: "alp" },+ { id: "project-2", name: "Beta", slug: "bet" },+ ];+ storedProject = null;+ useLocation.mockReturnValue({ pathname: "/dashboard/workspace/workspace-1" });+});const createTask = vi.fn(async (input: Record<string, unknown>) => ({id: "task-1",title: input.title,@@ -41,10 +65,24 @@ afterEach(() => {vi.mock("@tanstack/react-router", () => ({useLocation: () => useLocation(),+ useParams: ({+ select,+ }: {+ select: (params: { workspaceId?: string }) => unknown;+ }) =>+ select({+ workspaceId: useLocation().pathname.match(/\/workspace\/([^/]+)/)?.[1],+ }),}));vi.mock("@/components/task/task-description-editor", () => ({- default: () => <div data-testid="description-editor" />,+ default: (props: {+ taskId?: string;+ ensureTaskId: () => Promise<string | null>;+ }) => {+ ensureTaskId = props.ensureTaskId;+ return <div data-testid="description-editor" data-task-id={props.taskId} />;+ },}));vi.mock("@/hooks/mutations/label/use-create-label", () => ({@@ -56,11 +94,11 @@ vi.mock("@/hooks/mutations/task/use-create-task", () => ({}));vi.mock("@/hooks/mutations/task/use-delete-task", () => ({- useDeleteTask: () => ({ mutateAsync: vi.fn() }),+ useDeleteTask: () => ({ mutateAsync: deleteTask }),}));vi.mock("@/hooks/mutations/task/use-update-task", () => ({- useUpdateTask: () => ({ mutateAsync: vi.fn() }),+ useUpdateTask: () => ({ mutateAsync: updateTask }),}));vi.mock("@/hooks/queries/label/use-get-labels-by-workspace", () => ({@@ -68,7 +106,7 @@ vi.mock("@/hooks/queries/label/use-get-labels-by-workspace", () => ({}));vi.mock("@/hooks/queries/workspace/use-active-workspace", () => ({- default: () => ({ data: { id: "workspace-1", name: "WS" } }),+ default: () => ({ data: { id: workspaceId, name: "WS" } }),}));vi.mock(@@ -86,16 +124,11 @@ vi.mock("@/hooks/use-workspace-permission", () => ({}));vi.mock("@/hooks/queries/project/use-get-projects", () => ({- default: () => ({- data: [- { id: "project-1", name: "Alpha", slug: "alp" },- { id: "project-2", name: "Beta", slug: "bet" },- ],- }),+ default: () => ({ data: projects }),}));vi.mock("@/store/project", () => ({- default: () => ({ project: null, setProject: vi.fn() }),+ default: () => ({ project: storedProject, setProject }),}));vi.mock("@/lib/toast", () => ({@@ -237,3 +270,196 @@ describe("CreateTaskModal", () => {).toBeNull();});});++function enterTitle(title = "Private task") {+ fireEvent.change(+ screen.getByPlaceholderText(+ "common:modals.createTask.taskTitlePlaceholder",+ ),+ {+ target: { value: title },+ },+ );+}++async function chooseBeta() {+ fireEvent.click(screen.getByText("common:modals.createTask.selectProject"));+ fireEvent.click(await screen.findByText("Beta"));+}++function submit() {+ fireEvent.submit(document.querySelector("form") as HTMLFormElement);+}++function pendingCreate() {+ let resolve!: (task: never) => void;+ createTask.mockImplementationOnce(+ () =>+ new Promise((done) => {+ resolve = done;+ }),+ );+ return () =>+ resolve({+ id: "old-draft",+ title: "Draft",+ status: "planned",+ projectId: "project-2",+ createdAt: "2026-08-05T00:00:00.000Z",+ } as never);+}++describe("CreateTaskModal context isolation", () => {+ it("never falls back to the last globally visited project", () => {+ storedProject = { id: "foreign-project", columns: [] };+ render(<CreateTaskModal open onClose={vi.fn()} />, {+ wrapper: createWrapper(),+ });+ enterTitle();+ expect(+ screen.getByText("common:modals.createTask.createButton"),+ ).toBeDisabled();+ submit();+ expect(createTask).not.toHaveBeenCalled();+ });++ it("clears selected project and private fields after close and reopen", async () => {+ const props = { open: true, onClose: vi.fn() };+ const view = render(<CreateTaskModal {...props} />, {+ wrapper: createWrapper(),+ });+ await chooseBeta();+ enterTitle();+ view.rerender(<CreateTaskModal {...props} open={false} />);+ view.rerender(<CreateTaskModal {...props} />);+ expect(+ screen.getByPlaceholderText(+ "common:modals.createTask.taskTitlePlaceholder",+ ),+ ).toHaveValue("");+ enterTitle("New task");+ submit();+ expect(createTask).not.toHaveBeenCalled();+ });++ it("clears workspace A's selection when workspace B becomes active", async () => {+ const view = render(<CreateTaskModal open onClose={vi.fn()} />, {+ wrapper: createWrapper(),+ });+ await chooseBeta();+ enterTitle();+ workspaceId = "workspace-2";+ projects = [{ id: "project-3", name: "Gamma", slug: "gam" }];+ useLocation.mockReturnValue({+ pathname: "/dashboard/workspace/workspace-2",+ });+ view.rerender(<CreateTaskModal open onClose={vi.fn()} />);+ enterTitle("Workspace B secret");+ submit();+ expect(createTask).not.toHaveBeenCalled();+ expect(+ screen.getByText("common:modals.createTask.selectProject"),+ ).toBeInTheDocument();+ });++ it("does not expose the previous workspace while the route's workspace is loading", async () => {+ const view = render(<CreateTaskModal open onClose={vi.fn()} />, {+ wrapper: createWrapper(),+ });+ await chooseBeta();+ enterTitle();+ useLocation.mockReturnValue({+ pathname: "/dashboard/workspace/workspace-2",+ });+ view.rerender(<CreateTaskModal open onClose={vi.fn()} />);+ expect(screen.queryByTestId("description-editor")).toBeNull();+ expect(createTask).not.toHaveBeenCalled();+ });++ it.each([undefined, []])(+ "rejects explicit project IDs until current workspace query proves membership (%s)",+ async (data) => {+ projects = data;+ render(<CreateTaskModal open projectId="project-2" onClose={vi.fn()} />, {+ wrapper: createWrapper(),+ });+ enterTitle();+ submit();+ await expect(ensureTaskId?.()).resolves.toBeNull();+ expect(createTask).not.toHaveBeenCalled();+ },+ );++ it("deletes a late draft after navigation without handing its ID to an upload", async () => {+ const finish = pendingCreate();+ const view = render(<CreateTaskModal open onClose={vi.fn()} />, {+ wrapper: createWrapper(),+ });+ await chooseBeta();+ let pending!: Promise<string | null>;+ act(() => {+ pending = ensureTaskId?.() as Promise<string | null>;+ });+ workspaceId = "workspace-2";+ useLocation.mockReturnValue({+ pathname: "/dashboard/workspace/workspace-2",+ });+ view.rerender(<CreateTaskModal open onClose={vi.fn()} />);+ await act(async () => {+ finish();+ await pending;+ });+ await expect(pending).resolves.toBeNull();+ expect(deleteTask).toHaveBeenCalledExactlyOnceWith("old-draft");+ expect(screen.getByTestId("description-editor")).not.toHaveAttribute(+ "data-task-id",+ );+ expect(updateTask).not.toHaveBeenCalled();+ expect(setProject).not.toHaveBeenCalled();+ });++ it("waits for the upload draft on submit and saves that task only once", async () => {+ const finish = pendingCreate();+ render(<CreateTaskModal open onClose={vi.fn()} />, {+ wrapper: createWrapper(),+ });+ await chooseBeta();+ enterTitle();+ let pending!: Promise<string | null>;+ act(() => {+ pending = ensureTaskId?.() as Promise<string | null>;+ });+ submit();+ submit();+ expect(updateTask).not.toHaveBeenCalled();+ await act(async () => {+ finish();+ await pending;+ });+ await vi.waitFor(() =>+ expect(updateTask).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ id: "old-draft",+ projectId: "project-2",+ title: "Private task",+ }),+ ),+ );+ expect(createTask).toHaveBeenCalledTimes(1);+ expect(deleteTask).not.toHaveBeenCalled();+ });++ it("discards an existing draft on close and never puts it into another project's store", async () => {+ storedProject = { id: "project-1", columns: [] };+ const view = render(<CreateTaskModal open onClose={vi.fn()} />, {+ wrapper: createWrapper(),+ });+ await chooseBeta();+ await act(async () => {+ await ensureTaskId?.();+ });+ view.rerender(<CreateTaskModal open={false} onClose={vi.fn()} />);+ expect(deleteTask).toHaveBeenCalledExactlyOnceWith("task-1");+ expect(setProject).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/components/shared/modals/create-task-modal.tsx b/apps/web/src/components/shared/modals/create-task-modal.tsxindex 385bbf52b..30555be0b 100644--- a/apps/web/src/components/shared/modals/create-task-modal.tsx+++ b/apps/web/src/components/shared/modals/create-task-modal.tsx@@ -1,4 +1,4 @@-import { useLocation } from "@tanstack/react-router";+import { useLocation, useParams } from "@tanstack/react-router";import { produce } from "immer";import {CalendarIcon,@@ -141,7 +141,7 @@ function normalizeTask(};}-function CreateTaskModal({+function CreateTaskModalContent({open,onClose,status,@@ -238,17 +238,24 @@ function CreateTaskModal({location.pathname.match(/\/project\/([^/]+)/)?.[1] ?? null;const explicitProjectId = projectId || routeProjectId || "";const [selectedProjectId, setSelectedProjectId] = useState("");- const resolvedProjectId =- explicitProjectId || selectedProjectId || project?.id || "";const { data: workspaceProjects } = useGetProjects({workspaceId: workspace?.id || "",});- const resolvedProject = explicitProjectId- ? project- : (workspaceProjects?.find((p) => p.id === resolvedProjectId) ?? null);+ // Only a project from this workspace's query may receive new content.+ // The global project store can still contain the last visited workspace.+ const resolvedProject = workspaceProjects?.find(+ (candidate) => candidate.id === (explicitProjectId || selectedProjectId),+ );+ const resolvedProjectId = resolvedProject?.id ?? "";const searchInputRef = useRef<HTMLInputElement>(null);- const draftCreationPromiseRef = useRef<Promise<Task> | null>(null);+ const draftCreationPromiseRef = useRef<Promise<Task | null> | null>(null);+ const draftTaskRef = useRef<Task | null>(null);+ const activeRef = useRef(true);+ const submittingRef = useRef(false);+ const [isPreparingDraft, setIsPreparingDraft] = useState(false);+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [editorVersion, setEditorVersion] = useState(0);const didSubmitRef = useRef(false);const { mutateAsync: createTask } = useCreateTask();@@ -326,34 +333,33 @@ function CreateTaskModal({draftTask,);- const closeAndReset = () => {- const shouldDeleteDraft = draftTask && !didSubmitRef.current;+ const discardDraft = useCallback(() => {+ const abandoned = draftTaskRef.current;+ if (abandoned && !didSubmitRef.current) {+ draftTaskRef.current = null;+ void deleteTask(abandoned.id).catch(() => {+ // An expired session can prevent cleanup; never reuse the draft.+ });+ }+ }, [deleteTask]);- setDiscardConfirmationOpen(false);- setTitle("");- setDescription("");- setPriority("no-priority");- setAssigneeId("");- setStartDate(undefined);- setDueDate(undefined);- setSelectedProjectId("");- setCreateMore(false);- setLabels([]);- setLabelsStep("select");- setSearchValue("");- setSelectedColor("gray");- setNewLabelName("");- draftCreationPromiseRef.current = null;- didSubmitRef.current = false;- setDraftTask(null);- setCustomFieldValues(buildDefaultCustomFieldValues());+ useEffect(() => {+ activeRef.current = true;+ return () => {+ activeRef.current = false;+ discardDraft();+ };+ }, [discardDraft]);++ const handleClose = () => {+ activeRef.current = false;+ discardDraft();onClose();+ };- if (shouldDeleteDraft) {- void deleteTask(draftTask.id).catch(() => {- // ignore cleanup failures for abandoned empty drafts- });- }+ const closeAndReset = () => {+ setDiscardConfirmationOpen(false);+ handleClose();};const handleOpenChange = (nextOpen: boolean) => {@@ -369,7 +375,7 @@ function CreateTaskModal({const syncTaskIntoProject = useCallback((task: Task) => {- if (!project) return;+ if (!activeRef.current || project?.id !== task.projectId) return;const updatedProject = produce(project, (draft) => {let existingTask:@@ -423,13 +429,16 @@ function CreateTaskModal({);const ensureDraftTask = useCallback(async () => {- if (draftTask) {- return draftTask.id;+ if (!activeRef.current || submittingRef.current) return null;+ if (draftTaskRef.current) {+ return draftTaskRef.current.projectId === resolvedProjectId+ ? draftTaskRef.current.id+ : null;}if (draftCreationPromiseRef.current) {const pendingTask = await draftCreationPromiseRef.current;- return pendingTask.id;+ return activeRef.current ? (pendingTask?.id ?? null) : null;}if (!resolvedProjectId) {@@ -437,6 +446,7 @@ function CreateTaskModal({return null;}+ setIsPreparingDraft(true);const draftStatus = "planned";const draftPromise = createTask({title: title.trim() || t("common:modals.createTask.untitledTask"),@@ -453,14 +463,22 @@ function CreateTaskModal({fieldId,value,})),- }).then((task) => normalizeTask(task));+ }).then((task) => {+ const createdTask = normalizeTask(task);+ if (!activeRef.current) {+ void deleteTask(createdTask.id).catch(() => {});+ return null;+ }+ draftTaskRef.current = createdTask;+ setDraftTask(createdTask);+ return createdTask;+ });draftCreationPromiseRef.current = draftPromise;try {const createdTask = await draftPromise;- setDraftTask(createdTask);- return createdTask.id;+ return activeRef.current ? (createdTask?.id ?? null) : null;} catch (error) {toast.error(error instanceof Error@@ -470,12 +488,13 @@ function CreateTaskModal({return null;} finally {draftCreationPromiseRef.current = null;+ if (activeRef.current) setIsPreparingDraft(false);}}, [assigneeId,createTask,description,- draftTask,+ deleteTask,startDate,dueDate,priority,@@ -487,16 +506,32 @@ function CreateTaskModal({const handleSubmit = async (e: React.FormEvent) => {e.preventDefault();- if (!title.trim() || !resolvedProjectId || !workspace?.id) return;+ if (+ !activeRef.current ||+ submittingRef.current ||+ !canCreateTaskCapability ||+ !title.trim() ||+ !resolvedProjectId ||+ !workspace?.id+ )+ return;+ submittingRef.current = true;+ setIsSubmitting(true);try {+ // Submitting while a file prepares its draft must update that same task.+ const pendingDraft = draftCreationPromiseRef.current;+ if (pendingDraft) await pendingDraft;+ if (!activeRef.current) return;+ const currentDraft = draftTaskRef.current;+ if (currentDraft && currentDraft.projectId !== resolvedProjectId) return;const taskStatus = status ?? "to-do";didSubmitRef.current = true;- const savedTask = draftTask+ const savedTask = currentDraft? normalizeTask(await updateTask({- ...draftTask,+ ...currentDraft,title: title.trim(),description: description.trim() || "",userId: assigneeId || null,@@ -542,7 +577,7 @@ function CreateTaskModal({}}- if (draftTask) {+ if (currentDraft) {for (const [fieldId, value] of Object.entries(customFieldValues)) {if (value) {await setCustomFieldValue({@@ -554,6 +589,8 @@ function CreateTaskModal({}}+ draftTaskRef.current = null;+ if (!activeRef.current) return;setDraftTask(savedTask);syncTaskIntoProject(savedTask);toast.success(@@ -575,6 +612,7 @@ function CreateTaskModal({setSelectedColor("gray");setNewLabelName("");draftCreationPromiseRef.current = null;+ setEditorVersion((version) => version + 1);didSubmitRef.current = false;setDraftTask(null);setCustomFieldValues(buildDefaultCustomFieldValues());@@ -583,11 +621,18 @@ function CreateTaskModal({}} catch (error) {didSubmitRef.current = false;+ if (!activeRef.current) {+ discardDraft();+ return;+ }toast.error(error instanceof Error? error.message: t("common:modals.createTask.createError"),);+ } finally {+ submittingRef.current = false;+ if (activeRef.current) setIsSubmitting(false);}};@@ -852,6 +897,7 @@ function CreateTaskModal({<div className="min-h-[200px]"><TaskDescriptionEditor+ key={editorVersion}value={description}onChange={setDescription}placeholder={t(@@ -938,9 +984,18 @@ function CreateTaskModal({key={workspaceProject.id}type="button"className="w-full flex items-center gap-2 px-2 py-1.5 text-sm hover:bg-accent/50 text-left transition-colors h-8"- onClick={() =>- setSelectedProjectId(workspaceProject.id)+ disabled={+ isPreparingDraft || !!draftTask || isSubmitting}+ onClick={() => {+ if (+ !draftCreationPromiseRef.current &&+ !draftTaskRef.current &&+ !submittingRef.current+ ) {+ setSelectedProjectId(workspaceProject.id);+ }+ }}><span className="text-sm truncate">{workspaceProject.name}@@ -1327,7 +1382,7 @@ function CreateTaskModal({</Button><Buttontype="submit"- disabled={!title.trim()}+ disabled={!title.trim() || !resolvedProjectId || isSubmitting}size="sm"className="disabled:opacity-50">@@ -1371,4 +1426,29 @@ function CreateTaskModal({);}+function CreateTaskModal(props: CreateTaskModalProps) {+ const { data: workspace } = useActiveWorkspace();+ const location = useLocation();+ const routeWorkspaceId = useParams({+ strict: false,+ select: (params) =>+ "workspaceId" in params && typeof params.workspaceId === "string"+ ? params.workspaceId+ : undefined,+ });+ // useActiveWorkspace may temporarily fall back to the previous organization+ // while the new route's organization list is loading.+ if (!props.open || (routeWorkspaceId && routeWorkspaceId !== workspace?.id))+ return null;++ // Closing or navigating ends the whole editing session, including pending+ // upload drafts, instead of carrying confidential fields into a new context.+ return (+ <CreateTaskModalContent+ key={JSON.stringify([workspace?.id, location.pathname, props.projectId])}+ {...props}+ />+ );+}+export default CreateTaskModal;diff --git a/apps/web/src/components/ui/preview-card.tsx b/apps/web/src/components/ui/preview-card.tsxindex 7e48f3fbd..ebf916b62 100644--- a/apps/web/src/components/ui/preview-card.tsx+++ b/apps/web/src/components/ui/preview-card.tsx@@ -5,6 +5,11 @@ import * as React from "react";import { cn } from "@/lib/cn";+const PreviewCardDelays = React.createContext<{+ openDelay?: number;+ closeDelay?: number;+}>({});+function PreviewCard({closeDelay,openDelay,@@ -13,23 +18,34 @@ function PreviewCard({openDelay?: number;closeDelay?: number;}) {- void openDelay;- void closeDelay;- return <PreviewCardPrimitive.Root {...props} />;+ const delays = React.useMemo(+ () => ({ openDelay, closeDelay }),+ [openDelay, closeDelay],+ );+ return (+ <PreviewCardDelays.Provider value={delays}>+ <PreviewCardPrimitive.Root {...props} />+ </PreviewCardDelays.Provider>+ );}function PreviewCardTrigger({asChild = false,children,render,+ delay,+ closeDelay,...props}: PreviewCardPrimitive.Trigger.Props & { asChild?: boolean }) {+ const rootDelays = React.useContext(PreviewCardDelays);const resolvedRender =asChild && React.isValidElement(children) ? children : render;return (<PreviewCardPrimitive.Triggerdata-slot="preview-card-trigger"+ delay={delay ?? rootDelays.openDelay}+ closeDelay={closeDelay ?? rootDelays.closeDelay}render={resolvedRender}{...props}>diff --git a/apps/web/src/env.test.ts b/apps/web/src/env.test.tsindex 651ab7afe..d45b60742 100644--- a/apps/web/src/env.test.ts+++ b/apps/web/src/env.test.ts@@ -1,42 +1,41 @@import { execFileSync } from "node:child_process";-import { readFileSync } from "node:fs";import { resolve } from "node:path";+import { runInNewContext } from "node:vm";import { describe, expect, it } from "vitest";-const placeholderPattern = "[`\\\"']KANEO_TURNSTILE_SITE_KEY[`\\\"']";-const turnstilePlaceholder = "KANEO_TURNSTILE_SITE_KEY";--describe("runtime environment replacement", () => {- it("strips unset placeholders regardless of the quote emitted by the bundler", () => {- const bundle = [- `const doubleQuoted = "${turnstilePlaceholder}";`,- `const singleQuoted = '${turnstilePlaceholder}';`,- `const templateLiteral = \`${turnstilePlaceholder}\`;`,- `const required = "KANEO_API_URL";`,- `const configured = "https://example.com";`,- ].join("\n");-- const result = execFileSync("sed", ["-E", `s#${placeholderPattern}#""#g`], {+function renderBundle(bundle: string, key = "") {+ return execFileSync(+ "awk",+ ["-f", resolve(import.meta.dirname, "../env.awk")],+ {input: bundle,encoding: "utf8",- });-- expect(result).not.toContain("KANEO_TURNSTILE_SITE_KEY");- expect(result).toContain(`const required = "KANEO_API_URL";`);- expect(result).toContain(`const doubleQuoted = "";`);- expect(result).toContain(`const singleQuoted = "";`);- expect(result).toContain(`const templateLiteral = "";`);- expect(result).toContain(`const configured = "https://example.com";`);- });-- it("uses the quote-agnostic pattern in the container entrypoint", () => {- const entrypoint = readFileSync(- resolve(import.meta.dirname, "../env.sh"),- "utf8",+ env: {+ ...process.env,+ KANEO_TURNSTILE_SITE_KEY: key,+ KANEO_API_URL: "https://api.example.test",+ KANEO_CLIENT_URL: "https://app.example.test",+ },+ },+ );+}+describe("runtime environment replacement", () => {+ it("clears unset optional placeholders for every emitted literal quote", () => {+ const rendered = renderBundle(+ "globalThis.values = [\"KANEO_TURNSTILE_SITE_KEY\", 'KANEO_TURNSTILE_SITE_KEY', `KANEO_TURNSTILE_SITE_KEY`, 'https://example.test'];",);-- expect(entrypoint).toContain(- `sed -i -E 's#[\`"'"'"']KANEO_TURNSTILE_SITE_KEY[\`"'"'"']#""#g' {} +`,+ const context: { values?: string[] } = {};+ runInNewContext(rendered, context);+ expect(context.values).toEqual(["", "", "", "https://example.test"]);+ });+ it("encodes configured punctuation as literal data rather than JavaScript", () => {+ const key = '";globalThis.injected=true;//\\\n`';+ const context: { value?: string; injected?: boolean } = {};+ runInNewContext(+ renderBundle('globalThis.value = "KANEO_TURNSTILE_SITE_KEY";', key),+ context,);+ expect(context.value).toBe(key);+ expect(context.injected).toBeUndefined();});});diff --git a/apps/web/src/fetchers/github-integration/import-github-issues.test.ts b/apps/web/src/fetchers/github-integration/import-github-issues.test.tsnew file mode 100644index 000000000..2ddc8b024--- /dev/null+++ b/apps/web/src/fetchers/github-integration/import-github-issues.test.ts@@ -0,0 +1,99 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import importGithubIssues from "./import-github-issues";++const { request } = vi.hoisted(() => ({ request: vi.fn() }));+vi.mock("@kaneo/libs", () => ({+ client: { "github-integration": { "import-issues": { $post: request } } },+}));+const progress = {+ runId: "run-1",+ pending: true,+ imported: 4,+ updated: 0,+ skipped: 0,+};+beforeEach(() => {+ request.mockReset();+});+afterEach(() => {+ vi.useRealTimers();+});+describe("resumable GitHub import client", () => {+ it("awaits each page and carries the run ID until completion", async () => {+ let resolve!: (response: Response) => void;+ request+ .mockImplementationOnce(+ () =>+ new Promise<Response>((r) => {+ resolve = r;+ }),+ )+ .mockResolvedValueOnce(+ Response.json({ ...progress, imported: 8 }, { status: 202 }),+ )+ .mockResolvedValueOnce(+ Response.json({ ...progress, pending: false, imported: 9 }),+ );+ let finished = false;+ const pending = importGithubIssues({ projectId: "project" }).then(+ (result) => {+ finished = true;+ return result;+ },+ );+ await Promise.resolve();+ expect(request).toHaveBeenCalledTimes(1);+ expect(finished).toBe(false);+ resolve(Response.json(progress, { status: 202 }));+ await expect(pending).resolves.toMatchObject({+ pending: false,+ imported: 9,+ });+ expect(request.mock.calls).toEqual([+ [{ json: { projectId: "project", runId: undefined } }],+ [{ json: { projectId: "project", runId: "run-1" } }],+ [{ json: { projectId: "project", runId: "run-1" } }],+ ]);+ });+ it("resumes a saved run after refresh", async () => {+ request.mockResolvedValueOnce(+ Response.json({ ...progress, pending: false }),+ );+ await importGithubIssues({ projectId: "project", runId: "run-1" });+ expect(request).toHaveBeenCalledWith({+ json: { projectId: "project", runId: "run-1" },+ });+ });+ it("surfaces failures after partial progress instead of reporting success", async () => {+ request+ .mockResolvedValueOnce(Response.json(progress, { status: 202 }))+ .mockRejectedValueOnce(new TypeError("connection lost"));+ await expect(importGithubIssues({ projectId: "project" })).rejects.toThrow(+ "connection lost",+ );+ expect(request).toHaveBeenCalledTimes(2);+ });+ it("backs off for busy imports and stops after five retries", async () => {+ vi.useFakeTimers();+ request.mockImplementation(+ async () => new Response("busy", { status: 429 }),+ );+ const pending = importGithubIssues({ projectId: "project" });+ const rejection = expect(pending).rejects.toMatchObject({ status: 429 });+ await vi.advanceTimersByTimeAsync(999);+ expect(request).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(4001);+ await rejection;+ expect(request).toHaveBeenCalledTimes(6);+ });+ it.each([403, 409, 502])(+ "does not automatically restart on HTTP %i",+ async (status) => {+ request.mockResolvedValueOnce(new Response("paused", { status }));+ await expect(+ importGithubIssues({ projectId: "project", runId: "run-1" }),+ ).rejects.toMatchObject({ status });+ expect(request).toHaveBeenCalledTimes(1);+ },+ );+});diff --git a/apps/web/src/fetchers/github-integration/import-github-issues.ts b/apps/web/src/fetchers/github-integration/import-github-issues.tsindex 6f24826d1..5e2ff8350 100644--- a/apps/web/src/fetchers/github-integration/import-github-issues.ts+++ b/apps/web/src/fetchers/github-integration/import-github-issues.ts@@ -7,16 +7,25 @@ export type ImportGithubIssuesRequest = InferRequestType<>["json"];async function importGithubIssues(data: ImportGithubIssuesRequest) {- const response = await client["github-integration"]["import-issues"].$post({- json: data,- });-- if (!response.ok) {- throw new HttpError(response.status, await response.text());+ let runId = data.runId;+ let busyRetries = 0;+ for (;;) {+ const response = await client["github-integration"]["import-issues"].$post({+ json: { ...data, runId },+ });+ if (response.status === 429 && busyRetries < 5) {+ busyRetries++;+ await new Promise((resolve) => setTimeout(resolve, 1000));+ continue;+ }+ if (!response.ok)+ throw new HttpError(response.status, await response.text());+ const result = await response.json();+ if (response.status !== 202) return result;+ runId = result.runId;+ busyRetries = 0;+ // The server persists each page. A later call can resume even after the+ // browser closes; retries of a completed run do not start another import.}-- const result = await response.json();- return result;}-export default importGithubIssues;diff --git a/apps/web/src/fetchers/github-integration/list-repositories.ts b/apps/web/src/fetchers/github-integration/list-repositories.tsindex 7f207d1bc..79bde3fd0 100644--- a/apps/web/src/fetchers/github-integration/list-repositories.ts+++ b/apps/web/src/fetchers/github-integration/list-repositories.ts@@ -7,13 +7,23 @@ export type ListRepositoriesResponse = InferResponseType<200>;+export type RepositoryPage = {+ installationPage: number;+ repositoryPage: number;+};+async function listRepositories(projectId: string,+ page: RepositoryPage = { installationPage: 1, repositoryPage: 1 },): Promise<ListRepositoriesResponse> {const response = await client["github-integration"].repositories[":projectId"].$get({param: { projectId },+ query: {+ installationPage: String(page.installationPage),+ repositoryPage: String(page.repositoryPage),+ },});if (!response.ok) {diff --git a/apps/web/src/fetchers/label/delete-label.test.ts b/apps/web/src/fetchers/label/delete-label.test.tsnew file mode 100644index 000000000..ea6cf8c35--- /dev/null+++ b/apps/web/src/fetchers/label/delete-label.test.ts@@ -0,0 +1,99 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import deleteLabel from "./delete-label";++const { request } = vi.hoisted(() => ({ request: vi.fn() }));+vi.mock("@kaneo/libs", () => ({+ client: { label: { ":id": { $delete: request } } },+}));+const root = {+ id: "root",+ name: "bug",+ workspaceId: "workspace",+ taskId: null,+};+beforeEach(() => {+ request.mockReset();+});+afterEach(() => {+ vi.useRealTimers();+});++describe("resumable label deletion client", () => {+ it("awaits each batch and resolves only after the final response", async () => {+ let release!: (response: Response) => void;+ request+ .mockImplementationOnce(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ )+ .mockResolvedValueOnce(+ Response.json({ ...root, pendingDeletion: true }, { status: 202 }),+ )+ .mockResolvedValueOnce(Response.json(root));+ let finished = false;+ const operation = deleteLabel({ id: root.id }).then((result) => {+ finished = true;+ return result;+ });+ await Promise.resolve();+ expect(request).toHaveBeenCalledTimes(1);+ expect(finished).toBe(false);+ release(Response.json({ ...root, pendingDeletion: true }, { status: 202 }));+ await expect(operation).resolves.toEqual(root);+ expect(request.mock.calls).toEqual(+ Array.from({ length: 3 }, () => [{ param: { id: root.id } }]),+ );+ });++ it("surfaces an interrupted operation and resumes with the same label ID on retry", async () => {+ request+ .mockResolvedValueOnce(+ Response.json({ ...root, pendingDeletion: true }, { status: 202 }),+ )+ .mockRejectedValueOnce(new TypeError("Network unavailable"));+ await expect(deleteLabel({ id: root.id })).rejects.toThrow(+ "Network unavailable",+ );+ request.mockResolvedValueOnce(Response.json(root));+ await expect(deleteLabel({ id: root.id })).resolves.toEqual(root);+ expect(request).toHaveBeenLastCalledWith({ param: { id: root.id } });+ });++ it("backs off when busy and stops after five retries", async () => {+ vi.useFakeTimers();+ request.mockImplementation(+ async () => new Response("busy", { status: 429 }),+ );+ const operation = deleteLabel({ id: root.id });+ const rejection = expect(operation).rejects.toMatchObject({ status: 429 });+ await vi.advanceTimersByTimeAsync(999);+ expect(request).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(4001);+ await rejection;+ expect(request).toHaveBeenCalledTimes(6);+ });++ it("continues after temporary contention without reporting success early", async () => {+ vi.useFakeTimers();+ request+ .mockResolvedValueOnce(new Response("busy", { status: 429 }))+ .mockResolvedValueOnce(+ Response.json({ ...root, pendingDeletion: true }, { status: 202 }),+ )+ .mockResolvedValueOnce(Response.json(root));+ const operation = deleteLabel({ id: root.id });+ await vi.advanceTimersByTimeAsync(1000);+ await expect(operation).resolves.toEqual(root);+ expect(request).toHaveBeenCalledTimes(3);+ });++ it("does not retry authorization failures", async () => {+ request.mockResolvedValueOnce(new Response("forbidden", { status: 403 }));+ await expect(deleteLabel({ id: root.id })).rejects.toMatchObject({+ status: 403,+ });+ expect(request).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/web/src/fetchers/label/delete-label.ts b/apps/web/src/fetchers/label/delete-label.tsindex b498a198c..00a90c253 100644--- a/apps/web/src/fetchers/label/delete-label.ts+++ b/apps/web/src/fetchers/label/delete-label.ts@@ -7,17 +7,21 @@ export type DeleteLabelRequest = InferRequestType<>["param"];async function deleteLabel({ id }: DeleteLabelRequest) {- const response = await client.label[":id"].$delete({- param: { id },- });-- if (!response.ok) {- throw new HttpError(response.status, await response.text());+ let busyRetries = 0;+ for (;;) {+ const response = await client.label[":id"].$delete({ param: { id } });+ if (response.status === 429 && busyRetries < 5) {+ busyRetries++;+ await new Promise((resolve) => setTimeout(resolve, 1000));+ continue;+ }+ if (!response.ok)+ throw new HttpError(response.status, await response.text());+ const data = await response.json();+ if (response.status !== 202) return data;+ busyRetries = 0;+ // Each successful step persists its progress. Continue the same operation;+ // a later call with this ID also resumes after a failed or closed client.}-- const data = await response.json();-- return data;}-export default deleteLabel;diff --git a/apps/web/src/fetchers/project/get-public-project.ts b/apps/web/src/fetchers/project/get-public-project.tsindex f99e5282e..bd3050d40 100644--- a/apps/web/src/fetchers/project/get-public-project.ts+++ b/apps/web/src/fetchers/project/get-public-project.ts@@ -1,23 +1,30 @@import { client } from "@kaneo/libs";import type { InferRequestType } from "hono/client";+import { loadBoardPages } from "@/fetchers/task/load-board-pages";import { HttpError } from "@/lib/http-error";-export type GetPublicProjectRequest = InferRequestType<(typeof client)["public-project"][":id"]["$get"]>["param"];--async function getPublicProject({ id }: GetPublicProjectRequest) {- const response = await client["public-project"][":id"].$get({- param: { id },- });-- if (!response.ok) {- throw new HttpError(response.status, await response.text());- }-- const data = await response.json();-- return data;+async function getPublicProject(+ { id }: GetPublicProjectRequest,+ signal?: AbortSignal,+) {+ return loadBoardPages(async (page, relatedPage) => {+ const response = await client["public-project"][":id"].$get(+ {+ param: { id },+ query: {+ page: String(page),+ limit: "100",+ ...(relatedPage ? { relatedPage: String(relatedPage) } : {}),+ },+ },+ { init: { signal } },+ );+ if (!response.ok)+ throw new HttpError(response.status, await response.text());+ const { pagination, ...data } = await response.json();+ return { data, pagination };+ }, signal);}-export default getPublicProject;diff --git a/apps/web/src/fetchers/task/board-fetchers.test.ts b/apps/web/src/fetchers/task/board-fetchers.test.tsnew file mode 100644index 000000000..da70c2df1--- /dev/null+++ b/apps/web/src/fetchers/task/board-fetchers.test.ts@@ -0,0 +1,143 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import getPublicProject from "../project/get-public-project";+import getTasks from "./get-tasks";++const { privateRequest, publicRequest } = vi.hoisted(() => ({+ privateRequest: vi.fn(),+ publicRequest: vi.fn(),+}));+vi.mock("@kaneo/libs", () => ({+ client: {+ task: { tasks: { ":projectId": { $get: privateRequest } } },+ "public-project": { ":id": { $get: publicRequest } },+ },+}));+function data(page: number) {+ return {+ id: "project",+ name: "Project",+ slug: "project",+ icon: null,+ description: null,+ isPublic: true,+ workspaceId: "workspace",+ columns: [+ {+ id: "todo",+ slug: "todo",+ name: "To do",+ icon: null,+ isFinal: false,+ tasks: [+ {+ id: `task-${page}`,+ title: `Task ${page}`,+ description: `text-${page}`,+ labels: [],+ externalLinks: [],+ },+ ],+ },+ ],+ archivedTasks: [],+ plannedTasks: [],+ };+}+beforeEach(() => {+ privateRequest.mockReset();+ publicRequest.mockReset();+});+describe("authenticated and public board fetchers", () => {+ it.each(["private", "public"])(+ "reads every %s page through the typed client and propagates cancellation",+ async (visibility) => {+ const request = visibility === "private" ? privateRequest : publicRequest;+ request.mockImplementation(+ async ({ query }: { query: { page: string } }) => {+ const page = Number(query.page);+ const pagination = { page, pageSize: 100, total: 201, totalPages: 3 };+ return Response.json(+ visibility === "private"+ ? { data: data(page), pagination }+ : { ...data(page), pagination },+ );+ },+ );+ const controller = new AbortController();+ const result =+ visibility === "private"+ ? await getTasks("project", controller.signal)+ : await getPublicProject({ id: "project" }, controller.signal);+ expect(result.columns[0].tasks.map((task) => task.id)).toEqual([+ "task-1",+ "task-2",+ "task-3",+ ]);+ expect(request).toHaveBeenCalledTimes(3);+ for (let index = 0; index < 3; index++)+ expect(request.mock.calls[index]).toEqual([+ {+ param:+ visibility === "private"+ ? { projectId: "project" }+ : { id: "project" },+ query: { page: String(index + 1), limit: "100" },+ },+ { init: { signal: controller.signal } },+ ]);+ },+ );+ it.each(["private", "public"])(+ "sends relatedPage for %s continuations and merges their labels",+ async (visibility) => {+ const request = visibility === "private" ? privateRequest : publicRequest;+ request.mockImplementation(+ async ({ query }: { query: { relatedPage?: string } }) => {+ const related = Number(query.relatedPage ?? 1);+ const board = data(1);+ Object.assign(board.columns[0].tasks[0], {+ labels: [{ id: `label-${related}`, name: "Label", color: "red" }],+ });+ const pagination = {+ page: 1,+ pageSize: 100,+ total: 1,+ totalPages: 1,+ relatedTotalPages: 2,+ };+ return Response.json(+ visibility === "private"+ ? { data: board, pagination }+ : { ...board, pagination },+ );+ },+ );+ const result =+ visibility === "private"+ ? await getTasks("project")+ : await getPublicProject({ id: "project" });+ expect(result.columns[0].tasks[0].labels).toHaveLength(2);+ expect(request.mock.calls[1][0].query).toMatchObject({+ page: "1",+ relatedPage: "2",+ limit: "100",+ });+ },+ );+ it("does not cache a partial public board when its visibility is revoked", async () => {+ publicRequest+ .mockResolvedValueOnce(+ Response.json({+ ...data(1),+ pagination: { page: 1, pageSize: 100, total: 101, totalPages: 2 },+ }),+ )+ .mockResolvedValueOnce(+ new Response("Project is not public", { status: 403 }),+ );+ await expect(getPublicProject({ id: "project" })).rejects.toMatchObject({+ status: 403,+ });+ expect(publicRequest).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/web/src/fetchers/task/description-pages.test.ts b/apps/web/src/fetchers/task/description-pages.test.tsnew file mode 100644index 000000000..03e7236c4--- /dev/null+++ b/apps/web/src/fetchers/task/description-pages.test.ts@@ -0,0 +1,139 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type Task from "@/types/task";+import { getDescriptionMatches } from "./get-description-matches";+import {+ getPublicTaskDescription,+ loadDescriptionPages,+} from "./get-description-pages";+import updateTask from "./update-task";++const { descriptionRequest, matchRequest, updateRequest } = vi.hoisted(() => ({+ descriptionRequest: vi.fn(),+ matchRequest: vi.fn(),+ updateRequest: vi.fn(),+}));+vi.mock("@kaneo/libs", () => ({+ client: {+ "public-project": {+ ":id": {+ task: { ":taskId": { description: { $get: descriptionRequest } } },+ },+ },+ task: {+ "description-matches": { ":projectId": { $get: matchRequest } },+ ":id": { $put: updateRequest },+ },+ },+}));+beforeEach(() => vi.resetAllMocks());++describe("deferred descriptions", () => {+ it("assembles full public text and forwards the first version plus cancellation on every page", async () => {+ descriptionRequest+ .mockResolvedValueOnce(+ Response.json({ content: "😺", version: "123", nextOffset: 1 }),+ )+ .mockResolvedValueOnce(+ Response.json({ content: "é", version: "123", nextOffset: null }),+ );+ const signal = new AbortController().signal;+ expect(await getPublicTaskDescription("project", "task", signal)).toBe(+ "😺é",+ );+ expect(descriptionRequest.mock.calls).toEqual([+ [+ {+ param: { id: "project", taskId: "task" },+ query: { offset: "0", version: undefined },+ },+ { init: { signal } },+ ],+ [+ {+ param: { id: "project", taskId: "task" },+ query: { offset: "1", version: "123" },+ },+ { init: { signal } },+ ],+ ]);+ });+ it("rejects a revoked public description without returning partial text", async () => {+ descriptionRequest+ .mockResolvedValueOnce(+ Response.json({ content: "partial", version: "1", nextOffset: 7 }),+ )+ .mockResolvedValueOnce(new Response("unavailable", { status: 409 }));+ await expect(+ getPublicTaskDescription("project", "task"),+ ).rejects.toMatchObject({ status: 409 });+ });+ it("rejects changed versions and nonadvancing offsets", async () => {+ for (const next of [+ { version: "2", nextOffset: null },+ { version: "1", nextOffset: 1 },+ ]) {+ const load = vi+ .fn()+ .mockResolvedValueOnce({ content: "a", version: "1", nextOffset: 1 })+ .mockResolvedValueOnce({ content: "b", ...next });+ await expect(loadDescriptionPages(load)).rejects.toThrow();+ expect(load).toHaveBeenCalledTimes(2);+ }+ });+ it("stops loading after cancellation", async () => {+ const controller = new AbortController();+ const load = vi.fn(async () => {+ controller.abort();+ return { content: "a", version: "1", nextOffset: 1 };+ });+ await expect(+ loadDescriptionPages(load, controller.signal),+ ).rejects.toThrow();+ expect(load).toHaveBeenCalledTimes(1);+ });+ it("collects later description matches and rejects failures instead of claiming a complete search", async () => {+ const signal = new AbortController().signal;+ matchRequest+ .mockResolvedValueOnce(Response.json({ ids: ["a"], nextCursor: "a" }))+ .mockResolvedValueOnce(Response.json({ ids: ["b"], nextCursor: null }));+ expect(await getDescriptionMatches("project", "text", signal)).toEqual([+ "a",+ "b",+ ]);+ expect(matchRequest.mock.calls[1]).toEqual([+ { param: { projectId: "project" }, query: { query: "text", after: "a" } },+ { init: { signal } },+ ]);+ matchRequest+ .mockResolvedValueOnce(Response.json({ ids: ["a"], nextCursor: "a" }))+ .mockResolvedValueOnce(new Response("busy", { status: 503 }));+ await expect(+ getDescriptionMatches("project", "text"),+ ).rejects.toMatchObject({ status: 503 });+ });+ it("omits deferred text from generic board mutations but sends explicit ordinary edits", async () => {+ const task = {+ id: "task",+ title: "Task",+ projectId: "project",+ status: "to-do",+ description: null,+ descriptionDeferred: true,+ } as Task;+ updateRequest.mockImplementation(async () => Response.json(task));+ await updateTask(task.id, task);+ expect(updateRequest.mock.calls[0][0].json.description).toBeUndefined();+ await updateTask(task.id, {+ ...task,+ descriptionDeferred: false,+ description: "Edited",+ });+ expect(updateRequest.mock.calls[1][0].json.description).toBe("Edited");+ await updateTask(task.id, {+ ...task,+ descriptionDeferred: false,+ description: "",+ });+ expect(updateRequest.mock.calls[2][0].json.description).toBe("");+ });+});diff --git a/apps/web/src/fetchers/task/get-description-matches.ts b/apps/web/src/fetchers/task/get-description-matches.tsnew file mode 100644index 000000000..1cd70efe9--- /dev/null+++ b/apps/web/src/fetchers/task/get-description-matches.ts@@ -0,0 +1,30 @@+import { client } from "@kaneo/libs";+import { HttpError } from "@/lib/http-error";++export async function getDescriptionMatches(+ projectId: string,+ query: string,+ signal?: AbortSignal,+) {+ const ids = new Set<string>();+ let after: string | undefined;+ while (true) {+ signal?.throwIfAborted();+ const response = await client.task["description-matches"][+ ":projectId"+ ].$get(+ { param: { projectId }, query: { query, after } },+ { init: { signal } },+ );+ if (!response.ok)+ throw new HttpError(response.status, "Failed to search descriptions");+ const page = await response.json();+ for (const id of page.ids) ids.add(id);+ if (page.nextCursor === null) break;+ if (page.nextCursor === after || page.ids.length === 0)+ throw new Error("Description search did not advance");+ after = page.nextCursor;+ }+ signal?.throwIfAborted();+ return Array.from(ids);+}diff --git a/apps/web/src/fetchers/task/get-description-pages.ts b/apps/web/src/fetchers/task/get-description-pages.tsnew file mode 100644index 000000000..2ea09aa1b--- /dev/null+++ b/apps/web/src/fetchers/task/get-description-pages.ts@@ -0,0 +1,70 @@+import { client } from "@kaneo/libs";+import { HttpError } from "@/lib/http-error";++type DescriptionPage = {+ content: string;+ version: string;+ nextOffset: number | null;+};++export async function loadDescriptionPages(+ load: (offset: number, version?: string) => Promise<DescriptionPage>,+ signal?: AbortSignal,+) {+ const chunks: string[] = [];+ let offset = 0;+ let version: string | undefined;+ while (true) {+ signal?.throwIfAborted();+ const page = await load(offset, version);+ if (version !== undefined && page.version !== version)+ throw new Error("Description changed while loading");+ version = page.version;+ chunks.push(page.content);+ if (page.nextOffset === null) break;+ if (page.nextOffset <= offset)+ throw new Error("Description page did not advance");+ offset = page.nextOffset;+ }+ signal?.throwIfAborted();+ return chunks.join("");+}++export async function getPublicTaskDescription(+ projectId: string,+ taskId: string,+ signal?: AbortSignal,+) {+ return loadDescriptionPages(async (offset, version) => {+ const response = await client["public-project"][":id"].task[+ ":taskId"+ ].description.$get(+ {+ param: { id: projectId, taskId },+ query: { offset: String(offset), version },+ },+ { init: { signal } },+ );+ if (!response.ok)+ throw new HttpError(response.status, "Failed to load description");+ return response.json();+ }, signal);+}++export async function getPublicProjectDescription(+ projectId: string,+ signal?: AbortSignal,+) {+ return loadDescriptionPages(async (offset, version) => {+ const response = await client["public-project"][":id"].description.$get(+ { param: { id: projectId }, query: { offset: String(offset), version } },+ { init: { signal } },+ );+ if (!response.ok)+ throw new HttpError(+ response.status,+ "Failed to load project description",+ );+ return response.json();+ }, signal);+}diff --git a/apps/web/src/fetchers/task/get-tasks.ts b/apps/web/src/fetchers/task/get-tasks.tsindex b9c3700c0..0f4a1c4e8 100644--- a/apps/web/src/fetchers/task/get-tasks.ts+++ b/apps/web/src/fetchers/task/get-tasks.ts@@ -1,20 +1,23 @@import { client } from "@kaneo/libs";import { HttpError } from "@/lib/http-error";+import { loadBoardPages } from "./load-board-pages";-async function getTasks(projectId: string) {- const response = await client.task.tasks[":projectId"].$get({- param: { projectId },- // No filters: the route returns the whole board on a single page.- query: {},- });-- if (!response.ok) {- throw new HttpError(response.status, "Failed to fetch tasks");- }-- const json = await response.json();-- return json.data;+async function getTasks(projectId: string, signal?: AbortSignal) {+ return loadBoardPages(async (page, relatedPage) => {+ const response = await client.task.tasks[":projectId"].$get(+ {+ param: { projectId },+ query: {+ page: String(page),+ limit: "100",+ ...(relatedPage ? { relatedPage: String(relatedPage) } : {}),+ },+ },+ { init: { signal } },+ );+ if (!response.ok)+ throw new HttpError(response.status, "Failed to fetch tasks");+ return response.json();+ }, signal);}-export default getTasks;diff --git a/apps/web/src/fetchers/task/load-board-pages.test.ts b/apps/web/src/fetchers/task/load-board-pages.test.tsnew file mode 100644index 000000000..6144c9ce7--- /dev/null+++ b/apps/web/src/fetchers/task/load-board-pages.test.ts@@ -0,0 +1,195 @@+import { describe, expect, it, vi } from "vitest";+import type { ProjectWithTasks } from "@/types/project";+import type Task from "@/types/task";+import { loadBoardPages } from "./load-board-pages";++function task(id: string, status = "to-do"): Task {+ return {+ id,+ title: id,+ description: `${id} searchable description`,+ number: 1,+ status,+ priority: "low",+ startDate: null,+ dueDate: null,+ position: 1,+ createdAt: "2020-01-01T00:00:00Z",+ userId: null,+ assigneeId: null,+ assigneeName: null,+ projectId: "project",+ labels: [{ id: `label-${id}`, name: id, color: "red" }],+ externalLinks: [],+ };+}+function board(id: string): ProjectWithTasks {+ return {+ id: "project",+ name: "Project",+ slug: "project",+ icon: null,+ description: null,+ isPublic: false,+ workspaceId: "workspace",+ columns: [+ {+ id: "to-do",+ slug: "to-do",+ name: "To do",+ icon: null,+ isFinal: false,+ tasks: [task(id)],+ },+ ],+ plannedTasks: [task(`planned-${id}`, "planned")],+ archivedTasks: [task(`archived-${id}`, "archived")],+ };+}+function page(number: number, totalPages = 3) {+ return {+ data: board(String(number)),+ pagination: {+ page: number,+ pageSize: 3,+ totalPages,+ total: totalPages * 3,+ },+ };+}+describe("complete board loading through bounded pages", () => {+ it("loads sequentially and merges every column, planned and archived task with its complete fields", async () => {+ let active = 0;+ let peak = 0;+ const load = vi.fn(async (number: number) => {+ active++;+ peak = Math.max(peak, active);+ await Promise.resolve();+ active--;+ return page(number);+ });+ const result = await loadBoardPages(load);+ expect(load.mock.calls).toEqual([[1], [2], [3]]);+ expect(peak).toBe(1);+ expect(result.columns[0].tasks.map((task) => task.id)).toEqual([+ "1",+ "2",+ "3",+ ]);+ expect(result.plannedTasks.map((task) => task.id)).toEqual([+ "planned-1",+ "planned-2",+ "planned-3",+ ]);+ expect(result.archivedTasks).toHaveLength(3);+ expect(result.columns[0].tasks[2]).toMatchObject({+ description: "3 searchable description",+ labels: [{ id: "label-3" }],+ });+ });+ it("collects all related pages without dropping or duplicating labels, links or late columns", async () => {+ const load = vi.fn(async (number: number, relatedPage = 1) => {+ const response = page(number, 2);+ response.data.columns[0].position = 200;+ response.data.columns[0].tasks[0].labels = [+ { id: `label-${number}-${relatedPage}`, name: "Label", color: "red" },+ ];+ response.data.columns[0].tasks[0].externalLinks = [+ {+ id: `link-${number}-${relatedPage}`,+ taskId: String(number),+ integrationId: "integration",+ resourceType: "issue",+ externalId: "1",+ url: "https://example.com",+ title: null,+ metadata: null,+ },+ ];+ response.data.columns.push({+ id: `column-${relatedPage}`,+ slug: `column-${relatedPage}`,+ name: "Column",+ icon: null,+ isFinal: false,+ position: relatedPage,+ tasks: [],+ });+ return {+ ...response,+ pagination: {+ ...response.pagination,+ relatedTotalPages: relatedPage === 1 ? 3 : 999,+ },+ };+ });+ const result = await loadBoardPages(load);+ expect(load.mock.calls).toEqual([[1], [1, 2], [1, 3], [2], [2, 2], [2, 3]]);+ expect(result.columns.map((column) => column.id)).toEqual([+ "column-1",+ "column-2",+ "column-3",+ "to-do",+ ]);+ for (const [index, value] of result.columns[3].tasks.entries()) {+ expect(value.labels?.map((label) => label.id)).toEqual(+ [1, 2, 3].map((n) => `label-${index + 1}-${n}`),+ );+ expect(value.externalLinks).toHaveLength(3);+ }+ expect(result.plannedTasks).toHaveLength(2);+ expect(result.archivedTasks).toHaveLength(2);+ });+ it("rejects a failed related continuation instead of exposing a partially hydrated board", async () => {+ const first = page(1, 1);+ const load = vi+ .fn()+ .mockResolvedValueOnce({+ ...first,+ pagination: { ...first.pagination, relatedTotalPages: 2 },+ })+ .mockRejectedValueOnce(new Error("related failed"));+ await expect(loadBoardPages(load)).rejects.toThrow("related failed");+ });+ it("does not expose an incomplete board as success when a later page fails", async () => {+ const load = vi+ .fn()+ .mockResolvedValueOnce(page(1))+ .mockRejectedValueOnce(new Error("permission revoked"));+ await expect(loadBoardPages(load)).rejects.toThrow("permission revoked");+ expect(load).toHaveBeenCalledTimes(2);+ });+ it("honors cancellation and stops scheduling pages after the active request", async () => {+ const controller = new AbortController();+ const load = vi.fn(async (number: number) => {+ if (number === 2) controller.abort();+ return page(number);+ });+ await expect(loadBoardPages(load, controller.signal)).rejects.toThrow();+ expect(load).toHaveBeenCalledTimes(2);+ });+ it("uses the first page's work boundary and deduplicates tasks moved across pages", async () => {+ const load = vi.fn(async (number: number) =>+ page(1, number === 1 ? 2 : 100000),+ );+ const result = await loadBoardPages(load);+ expect(load).toHaveBeenCalledTimes(2);+ expect(result.columns[0].tasks).toHaveLength(1);+ });+ it("includes newly encountered columns instead of dropping their tasks", async () => {+ const load = vi.fn(async (number: number) => {+ const next = page(number, 2);+ if (number === 2)+ next.data.columns[0] = {+ ...next.data.columns[0],+ id: "new",+ slug: "new",+ tasks: [task("late", "new")],+ };+ return next;+ });+ const result = await loadBoardPages(load);+ expect(result.columns.map((column) => column.id)).toEqual(["to-do", "new"]);+ expect(result.columns[1].tasks[0].id).toBe("late");+ });+});diff --git a/apps/web/src/fetchers/task/load-board-pages.ts b/apps/web/src/fetchers/task/load-board-pages.tsnew file mode 100644index 000000000..563944139--- /dev/null+++ b/apps/web/src/fetchers/task/load-board-pages.ts@@ -0,0 +1,91 @@+import type { ProjectWithTasks } from "@/types/project";++export type BoardPage<T extends ProjectWithTasks> = {+ data: T;+ pagination: {+ page: number;+ pageSize: number;+ totalPages: number;+ total: number;+ relatedTotalPages?: number;+ };+};++/** Keep the existing board cache shape, but fetch one bounded page at a time. */+export async function loadBoardPages<T extends ProjectWithTasks>(+ load: (page: number, relatedPage?: number) => Promise<BoardPage<T>>,+ signal?: AbortSignal,+): Promise<T> {+ signal?.throwIfAborted();+ const first = await load(1);+ const result = first.data;+ const columns = new Map(result.columns.map((column) => [column.id, column]));+ const seen = new Map(+ [+ ...result.columns.flatMap((column) => column.tasks),+ ...result.archivedTasks,+ ...result.plannedTasks,+ ].map((task) => [task.id, task]),+ );+ const mergeById = <U extends { id: string }>(+ left: U[] = [],+ right: U[] = [],+ ) =>+ Array.from(+ new Map([...left, ...right].map((value) => [value.id, value])).values(),+ );+ const append = (+ target: ProjectWithTasks["plannedTasks"],+ tasks: ProjectWithTasks["plannedTasks"],+ ) => {+ for (const task of tasks) {+ if (!seen.has(task.id)) {+ seen.set(task.id, task);+ target.push(task);+ } else {+ const existing = seen.get(task.id);+ if (existing) {+ existing.labels = mergeById(existing.labels, task.labels);+ existing.externalLinks = mergeById(+ existing.externalLinks,+ task.externalLinks,+ );+ }+ }+ }+ };+ const merge = (next: BoardPage<T>) => {+ for (const column of next.data.columns) {+ let target = columns.get(column.id);+ if (!target) {+ target = { ...column, tasks: [] };+ columns.set(column.id, target);+ result.columns.push(target);+ }+ append(target.tasks, column.tasks);+ }+ append(result.archivedTasks, next.data.archivedTasks);+ append(result.plannedTasks, next.data.plannedTasks);+ };+ const loadRelated = async (page: number, initial: BoardPage<T>) => {+ // Each collection uses its initial count; live additions cannot indefinitely+ // extend a refresh. The next refresh sees changes made during pagination.+ const total = initial.pagination.relatedTotalPages ?? 1;+ for (let relatedPage = 2; relatedPage <= total; relatedPage++) {+ signal?.throwIfAborted();+ merge(await load(page, relatedPage));+ }+ };+ await loadRelated(1, first);+ for (let page = 2; page <= first.pagination.totalPages; page++) {+ signal?.throwIfAborted();+ const next = await load(page);+ merge(next);+ await loadRelated(page, next);+ }+ result.columns.sort(+ (left, right) => (left.position ?? 0) - (right.position ?? 0),+ );+ signal?.throwIfAborted();+ return result;+}diff --git a/apps/web/src/fetchers/task/update-task.ts b/apps/web/src/fetchers/task/update-task.tsindex c0b1a7bce..f3ab12b02 100644--- a/apps/web/src/fetchers/task/update-task.ts+++ b/apps/web/src/fetchers/task/update-task.ts@@ -13,7 +13,9 @@ async function updateTask(taskId: string, task: Task) {json: {userId: task.userId || "",title: task.title,- description: task.description || "",+ description: task.descriptionDeferred+ ? undefined+ : task.description || "",status: task.status,// The API validates priority against a picklist that has no empty// member, so a task carrying no priority has to be sent as the explicitdiff --git a/apps/web/src/hooks/filter-storage-failure.test.tsx b/apps/web/src/hooks/filter-storage-failure.test.tsxnew file mode 100644index 000000000..e55d21bbf--- /dev/null+++ b/apps/web/src/hooks/filter-storage-failure.test.tsx@@ -0,0 +1,47 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, renderHook } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useTaskFilters } from "./use-task-filters";+import { useTaskFiltersWithLabelsSupport } from "./use-task-filters-with-labels-support";++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe.each([+ ["basic filters", useTaskFilters],+ ["label filters", useTaskFiltersWithLabelsSupport],+] as const)("%s with unavailable storage", (_name, useFilters) => {+ it.each(["SecurityError", "QuotaExceededError", "storage getter"])(+ "keeps in-memory filtering usable after %s",+ (failure) => {+ if (failure === "storage getter") {+ vi.spyOn(window, "localStorage", "get").mockImplementation(() => {+ throw new DOMException("Storage blocked", "SecurityError");+ });+ } else {+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {+ throw new DOMException("Storage unavailable", failure);+ });+ }+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const { result } = renderHook(() => useFilters(undefined, "project-a"), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ ),+ });+ act(() => result.current.updateFilter("priority", ["urgent"]));+ expect(result.current.filters.priority).toEqual(["urgent"]);+ expect(result.current.hasActiveFilters).toBe(true);+ act(() => result.current.clearFilters());+ expect(result.current.filters.priority).toBeNull();+ expect(result.current.hasActiveFilters).toBe(false);+ },+ );+});diff --git a/apps/web/src/hooks/mutations/github-integration/use-import-github-issues.test.tsx b/apps/web/src/hooks/mutations/github-integration/use-import-github-issues.test.tsxnew file mode 100644index 000000000..517e3b160--- /dev/null+++ b/apps/web/src/hooks/mutations/github-integration/use-import-github-issues.test.tsx@@ -0,0 +1,60 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import queryClient from "@/query-client";+import useImportGithubIssues from "./use-import-github-issues";++const { run } = vi.hoisted(() => ({ run: vi.fn() }));+vi.mock("@/fetchers/github-integration/import-github-issues", () => ({+ default: run,+}));+afterEach(() => {+ cleanup();+ queryClient.clear();+});+beforeEach(() => {+ run.mockReset();+});+describe("GitHub import cache refresh", () => {+ it.each(["success", "failure"])(+ "refreshes tasks, labels and saved progress after %s",+ async (outcome) => {+ const client = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ const keys = [+ ["tasks", "project"],+ ["labels", "workspace"],+ ["github-integration", "project"],+ ];+ for (const key of keys) queryClient.setQueryData(key, {});+ if (outcome === "success")+ run.mockResolvedValue({+ pending: false,+ imported: 4,+ updated: 0,+ skipped: 0,+ });+ else+ run.mockRejectedValue(+ new Error("connection lost after persisted page"),+ );+ const { result } = renderHook(useImportGithubIssues, { wrapper });+ act(() => result.current.mutate({ projectId: "project" }));+ await waitFor(() =>+ expect(+ outcome === "success"+ ? result.current.isSuccess+ : result.current.isError,+ ).toBe(true),+ );+ for (const key of keys)+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true);+ client.clear();+ },+ );+});diff --git a/apps/web/src/hooks/mutations/github-integration/use-import-github-issues.ts b/apps/web/src/hooks/mutations/github-integration/use-import-github-issues.tsindex 612a7cbd6..b79023be5 100644--- a/apps/web/src/hooks/mutations/github-integration/use-import-github-issues.ts+++ b/apps/web/src/hooks/mutations/github-integration/use-import-github-issues.ts@@ -5,8 +5,15 @@ import queryClient from "@/query-client";function useImportGithubIssues() {return useMutation({mutationFn: importGithubIssues,- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ["tasks"] });+ onSettled: async (_data, _error, variables) => {+ // A failed request can follow successfully persisted pages.+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["tasks"] }),+ queryClient.invalidateQueries({ queryKey: ["labels"] }),+ queryClient.invalidateQueries({+ queryKey: ["github-integration", variables.projectId],+ }),+ ]);},});}diff --git a/apps/web/src/hooks/mutations/label/sync-task-labels-cache.ts b/apps/web/src/hooks/mutations/label/sync-task-labels-cache.tsindex 4d88bb986..2859a7fb8 100644--- a/apps/web/src/hooks/mutations/label/sync-task-labels-cache.ts+++ b/apps/web/src/hooks/mutations/label/sync-task-labels-cache.ts@@ -50,6 +50,7 @@ export function syncTaskLabelsInTasksCache(queryClient.setQueriesData<ProjectWithTasks | undefined>({queryKey: ["tasks"],+ predicate: (query) => query.queryKey.length === 2,},(existingProject) =>existingProjectdiff --git a/apps/web/src/hooks/mutations/label/use-delete-label.test.tsx b/apps/web/src/hooks/mutations/label/use-delete-label.test.tsxnew file mode 100644index 000000000..2f8328754--- /dev/null+++ b/apps/web/src/hooks/mutations/label/use-delete-label.test.tsx@@ -0,0 +1,67 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import useDeleteLabel from "./use-delete-label";++const { remove } = vi.hoisted(() => ({ remove: vi.fn() }));+vi.mock("@/fetchers/label/delete-label", () => ({ default: remove }));+afterEach(cleanup);+beforeEach(() => {+ remove.mockReset();+});+const root = {+ id: "label",+ workspaceId: "workspace",+ taskId: null,+ name: "bug",+};+function setup() {+ const client = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ client.setQueryData(["labels", "workspace"], [root]);+ client.setQueryData(["tasks", "project"], { id: "project" });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ return { client, ...renderHook(useDeleteLabel, { wrapper }) };+}+describe("label deletion cache state", () => {+ it("retains the root while batches are running and removes it only on completion", async () => {+ let finish!: (label: typeof root) => void;+ remove.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const { client, result } = setup();+ act(() => result.current.mutate({ id: root.id }));+ await waitFor(() => expect(result.current.isPending).toBe(true));+ expect(client.getQueryData(["labels", "workspace"])).toEqual([root]);+ await act(async () => {+ finish(root);+ });+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(client.getQueryData(["labels", "workspace"])).toEqual([]);+ expect(client.getQueryState(["tasks", "project"])?.isInvalidated).toBe(+ true,+ );+ client.clear();+ });+ it("refreshes both labels and tasks after a partial operation fails", async () => {+ remove.mockRejectedValue(new Error("connection lost after a batch"));+ const { client, result } = setup();+ act(() => result.current.mutate({ id: root.id }));+ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(client.getQueryData(["labels", "workspace"])).toEqual([root]);+ expect(client.getQueryState(["labels", "workspace"])?.isInvalidated).toBe(+ true,+ );+ expect(client.getQueryState(["tasks", "project"])?.isInvalidated).toBe(+ true,+ );+ client.clear();+ });+});diff --git a/apps/web/src/hooks/mutations/label/use-delete-label.ts b/apps/web/src/hooks/mutations/label/use-delete-label.tsindex 4f1796950..68565e8f7 100644--- a/apps/web/src/hooks/mutations/label/use-delete-label.ts+++ b/apps/web/src/hooks/mutations/label/use-delete-label.ts@@ -7,6 +7,11 @@ function useDeleteLabel() {return useMutation({mutationFn: deleteLabel,+ onError: () => {+ // A preceding batch may have succeeded before the connection failed.+ void queryClient.invalidateQueries({ queryKey: ["labels"] });+ void queryClient.invalidateQueries({ queryKey: ["tasks"] });+ },onSuccess: (deletedLabel) => {queryClient.setQueryData(["labels", deletedLabel.workspaceId],diff --git a/apps/web/src/hooks/queries/project/use-get-public-project.ts b/apps/web/src/hooks/queries/project/use-get-public-project.tsindex a52ee4ce2..182c06a79 100644--- a/apps/web/src/hooks/queries/project/use-get-public-project.ts+++ b/apps/web/src/hooks/queries/project/use-get-public-project.ts@@ -4,7 +4,7 @@ import getPublicProject from "@/fetchers/project/get-public-project";function useGetPublicProject(id: string) {return useQuery({queryKey: ["public-project", id],- queryFn: () => getPublicProject({ id }),+ queryFn: ({ signal }) => getPublicProject({ id }, signal),});}diff --git a/apps/web/src/hooks/queries/task/use-description-matches.test.tsx b/apps/web/src/hooks/queries/task/use-description-matches.test.tsxnew file mode 100644index 000000000..d7f9cebac--- /dev/null+++ b/apps/web/src/hooks/queries/task/use-description-matches.test.tsx@@ -0,0 +1,169 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { getDescriptionMatches } from "@/fetchers/task/get-description-matches";+import type { ProjectWithTasks } from "@/types/project";+import type Task from "@/types/task";+import { addLabelToTaskInTasksCache } from "../../mutations/label/sync-task-labels-cache";+import { useTaskFiltersWithLabelsSupport } from "../../use-task-filters-with-labels-support";+import { useDescriptionMatches } from "./use-description-matches";++vi.mock("@/fetchers/task/get-description-matches", () => ({+ getDescriptionMatches: vi.fn(),+}));+const task: Task = {+ id: "deferred",+ projectId: "project",+ title: "Other title",+ number: 1,+ description: null,+ descriptionDeferred: true,+ status: "to-do",+ priority: "high",+ startDate: null,+ dueDate: null,+ position: 0,+ createdAt: "2026-01-01T00:00:00Z",+ userId: null,+ assigneeId: null,+ assigneeName: null,+};+const project: ProjectWithTasks = {+ id: "project",+ name: "Project",+ slug: "PRJ",+ icon: null,+ description: null,+ isPublic: false,+ workspaceId: "workspace",+ columns: [+ {+ id: "to-do",+ slug: "to-do",+ name: "To do",+ icon: null,+ isFinal: false,+ tasks: [+ task,+ {+ ...task,+ id: "local",+ descriptionDeferred: false,+ description: "needle",+ },+ ],+ },+ ],+ plannedTasks: [],+ archivedTasks: [],+};+let client: QueryClient;+function Wrapper({ children }: { children: ReactNode }) {+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;+}+beforeEach(() => {+ vi.clearAllMocks();+ window.localStorage.clear();+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+});+afterEach(() => {+ cleanup();+ client.clear();+});++describe("deferred description search", () => {+ it("combines full-text matches with local matches while preserving other filters", async () => {+ vi.mocked(getDescriptionMatches).mockResolvedValue(["deferred"]);+ const { result } = renderHook(+ () => {+ const matches = useDescriptionMatches("project", project, "needle");+ return useTaskFiltersWithLabelsSupport(+ project,+ "project",+ "needle",+ matches.ids,+ );+ },+ { wrapper: Wrapper },+ );+ await waitFor(() =>+ expect(result.current.filteredProject?.columns[0].tasks).toHaveLength(2),+ );+ act(() => result.current.updateFilter("priority", ["low"]));+ expect(result.current.filteredProject?.columns[0].tasks).toHaveLength(0);+ });+ it("refreshes matches on the existing board invalidation prefix", async () => {+ vi.mocked(getDescriptionMatches)+ .mockResolvedValueOnce(["deferred"])+ .mockResolvedValueOnce([]);+ const { result } = renderHook(+ () => useDescriptionMatches("project", project, "needle"),+ { wrapper: Wrapper },+ );+ await waitFor(() => expect(result.current.ids.has("deferred")).toBe(true));+ await act(async () => {+ await client.invalidateQueries({ queryKey: ["tasks", "project"] });+ });+ await waitFor(() => expect(result.current.ids.size).toBe(0));+ expect(getDescriptionMatches).toHaveBeenCalledTimes(2);+ });+ it("does not reuse another query's IDs, exposes search errors and supports retry", async () => {+ vi.mocked(getDescriptionMatches)+ .mockResolvedValueOnce(["deferred"])+ .mockRejectedValueOnce(new Error("failed"))+ .mockResolvedValueOnce([]);+ const { result, rerender } = renderHook(+ ({ text }) => useDescriptionMatches("project", project, text),+ { initialProps: { text: "needle" }, wrapper: Wrapper },+ );+ await waitFor(() => expect(result.current.ids.size).toBe(1));+ rerender({ text: "other" });+ expect(result.current.ids.size).toBe(0);+ expect(result.current.isLoading).toBe(true);+ await waitFor(() => expect(result.current.isError).toBe(true));+ await act(async () => {+ await result.current.retry();+ });+ await waitFor(() => expect(result.current.isError).toBe(false));+ });+ it("keeps search caches separate when labels are updated optimistically", () => {+ client.setQueryData(["tasks", "project"], project);+ client.setQueryData(+ ["tasks", "project", "description-matches", "needle"],+ ["deferred"],+ );+ addLabelToTaskInTasksCache(client, "deferred", {+ id: "label",+ name: "Label",+ color: "red",+ });+ expect(+ client.getQueryData([+ "tasks",+ "project",+ "description-matches",+ "needle",+ ]),+ ).toEqual(["deferred"]);+ expect(+ client.getQueryData<ProjectWithTasks>(["tasks", "project"])?.columns[0]+ .tasks[0].labels,+ ).toEqual([{ id: "label", name: "Label", color: "red" }]);+ });+ it("does not search empty queries, ordinary-only boards or stale project stores", () => {+ renderHook(() => useDescriptionMatches("project", project, " "), {+ wrapper: Wrapper,+ });+ renderHook(+ () => useDescriptionMatches("other-project", project, "needle"),+ { wrapper: Wrapper },+ );+ renderHook(+ () =>+ useDescriptionMatches("project", { ...project, columns: [] }, "needle"),+ { wrapper: Wrapper },+ );+ expect(getDescriptionMatches).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/hooks/queries/task/use-description-matches.ts b/apps/web/src/hooks/queries/task/use-description-matches.tsnew file mode 100644index 000000000..010207df0--- /dev/null+++ b/apps/web/src/hooks/queries/task/use-description-matches.ts@@ -0,0 +1,42 @@+import { useQuery } from "@tanstack/react-query";+import { useEffect, useMemo, useState } from "react";+import { getDescriptionMatches } from "@/fetchers/task/get-description-matches";+import type { ProjectWithTasks } from "@/types/project";++export function useDescriptionMatches(+ projectId: string,+ project: ProjectWithTasks | null | undefined,+ textQuery: string,+) {+ const query = textQuery.trim().toLowerCase();+ const [debouncedQuery, setDebouncedQuery] = useState(query);+ useEffect(() => {+ const timeout = setTimeout(() => setDebouncedQuery(query), 250);+ return () => clearTimeout(timeout);+ }, [query]);+ const needed =+ project?.id === projectId &&+ !!query &&+ project.columns.some((column) =>+ column.tasks.some((task) => task.descriptionDeferred),+ );+ const result = useQuery({+ // Board mutations already invalidate this project prefix, including edits,+ // imports and websocket events whose omitted text is unchanged in the cache.+ queryKey: ["tasks", projectId, "description-matches", query],+ queryFn: ({ signal }) => getDescriptionMatches(projectId, query, signal),+ enabled: needed && query === debouncedQuery,+ retry: false,+ refetchInterval: needed && query === debouncedQuery ? 30000 : false,+ });+ const ids = useMemo(+ () => new Set(needed ? result.data : []),+ [needed, result.data],+ );+ return {+ ids,+ isLoading: needed && (query !== debouncedQuery || result.isFetching),+ isError: needed && result.isError,+ retry: result.refetch,+ };+}diff --git a/apps/web/src/hooks/queries/task/use-get-tasks.ts b/apps/web/src/hooks/queries/task/use-get-tasks.tsindex e4eb590a9..370cd2453 100644--- a/apps/web/src/hooks/queries/task/use-get-tasks.ts+++ b/apps/web/src/hooks/queries/task/use-get-tasks.ts@@ -5,7 +5,7 @@ import { isUnauthorizedError } from "@/lib/http-error";export function useGetTasks(projectId: string) {return useQuery({queryKey: ["tasks", projectId],- queryFn: () => getTasks(projectId),+ queryFn: ({ signal }) => getTasks(projectId, signal),refetchInterval: (query) =>isUnauthorizedError(query.state.error) ? false : 30000,enabled: !!projectId,diff --git a/apps/web/src/hooks/queries/task/use-public-task-description.ts b/apps/web/src/hooks/queries/task/use-public-task-description.tsnew file mode 100644index 000000000..1a2e1904f--- /dev/null+++ b/apps/web/src/hooks/queries/task/use-public-task-description.ts@@ -0,0 +1,18 @@+import { useQuery } from "@tanstack/react-query";+import { getPublicTaskDescription } from "@/fetchers/task/get-description-pages";+import type Task from "@/types/task";++export function usePublicTaskDescription(task: Task | null, open: boolean) {+ return useQuery({+ queryKey: ["public-task-description", task?.projectId, task?.id],+ queryFn: ({ signal }) => {+ if (!task) throw new Error("No task selected");+ return getPublicTaskDescription(task.projectId, task.id, signal);+ },+ enabled: open && !!task?.descriptionDeferred,+ refetchOnMount: "always",+ staleTime: 0,+ gcTime: 0,+ retry: false,+ });+}diff --git a/apps/web/src/hooks/use-keyboard-shortcuts.test.tsx b/apps/web/src/hooks/use-keyboard-shortcuts.test.tsxnew file mode 100644index 000000000..57b646a5b--- /dev/null+++ b/apps/web/src/hooks/use-keyboard-shortcuts.test.tsx@@ -0,0 +1,54 @@+import { act, cleanup, fireEvent, renderHook } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ KeyboardShortcutsProvider,+ useKeyboardShortcuts,+} from "./use-keyboard-shortcuts";++afterEach(cleanup);++describe("shortcut key normalization", () => {+ it("dispatches and unregisters mixed-case Enter registrations", () => {+ const handler = vi.fn();+ const { result } = renderHook(useKeyboardShortcuts, {+ wrapper: KeyboardShortcutsProvider,+ });+ act(() => result.current.registerShortcut("Enter", handler));+ fireEvent.keyDown(document.body, { key: "Enter" });+ expect(handler).toHaveBeenCalledOnce();+ act(() => result.current.unregisterShortcut("Enter"));+ fireEvent.keyDown(document.body, { key: "Enter" });+ expect(handler).toHaveBeenCalledOnce();+ });++ it("normalizes sequential shortcuts during registration and cleanup", () => {+ const handler = vi.fn();+ const { result } = renderHook(useKeyboardShortcuts, {+ wrapper: KeyboardShortcutsProvider,+ });+ act(() => result.current.registerSequentialShortcut("G", "Enter", handler));+ fireEvent.keyDown(document.body, { key: "g" });+ fireEvent.keyDown(document.body, { key: "Enter" });+ expect(handler).toHaveBeenCalledOnce();+ act(() => result.current.unregisterSequentialShortcut("G", "Enter"));+ fireEvent.keyDown(document.body, { key: "g" });+ fireEvent.keyDown(document.body, { key: "Enter" });+ expect(handler).toHaveBeenCalledOnce();+ });++ it("does not take Enter away from text inputs", () => {+ const handler = vi.fn();+ const { result } = renderHook(useKeyboardShortcuts, {+ wrapper: KeyboardShortcutsProvider,+ });+ act(() => result.current.registerShortcut("Enter", handler));+ const input = document.createElement("input");+ document.body.append(input);+ try {+ fireEvent.keyDown(input, { key: "Enter" });+ } finally {+ input.remove();+ }+ expect(handler).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/hooks/use-keyboard-shortcuts.ts b/apps/web/src/hooks/use-keyboard-shortcuts.tsindex 2e4edec7b..58789ea54 100644--- a/apps/web/src/hooks/use-keyboard-shortcuts.ts+++ b/apps/web/src/hooks/use-keyboard-shortcuts.ts@@ -92,13 +92,15 @@ export function KeyboardShortcutsProvider({const registerShortcut = useCallback((key: string, handler: ShortcutHandler) => {- setShortcuts((prev) => new Map(prev).set(key, handler));+ setShortcuts((prev) => new Map(prev).set(key.toLowerCase(), handler));},[],);const registerSequentialShortcut = useCallback(- (prefix: string, key: string, handler: ShortcutHandler) => {+ (inputPrefix: string, inputKey: string, handler: ShortcutHandler) => {+ const prefix = inputPrefix.toLowerCase();+ const key = inputKey.toLowerCase();setSequentialShortcuts((prev) => {const newMap = new Map(prev);if (!newMap.has(prefix)) {@@ -125,13 +127,15 @@ export function KeyboardShortcutsProvider({const unregisterShortcut = useCallback((key: string) => {setShortcuts((prev) => {const newMap = new Map(prev);- newMap.delete(key);+ newMap.delete(key.toLowerCase());return newMap;});}, []);const unregisterSequentialShortcut = useCallback(- (prefix: string, key: string) => {+ (inputPrefix: string, inputKey: string) => {+ const prefix = inputPrefix.toLowerCase();+ const key = inputKey.toLowerCase();setSequentialShortcuts((prev) => {const newMap = new Map(prev);if (newMap.has(prefix)) {diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsxnew file mode 100644index 000000000..5f3abec8d--- /dev/null+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx@@ -0,0 +1,139 @@+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useProjectWebSocket } from "./use-project-websocket";++const { client, auth } = vi.hoisted(() => ({+ client: { invalidateQueries: vi.fn() },+ auth: { userId: "user-a" as string | null },+}));+vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));+vi.mock("@/lib/auth-client", () => ({+ authClient: {+ useSession: () => ({+ data: auth.userId ? { user: { id: auth.userId } } : null,+ }),+ },+}));+vi.mock("@kaneo/libs", () => ({ windowId: "local-test" }));++class TestSocket {+ static OPEN = 1;+ static instances: TestSocket[] = [];+ readyState = 0;+ onopen: (() => void) | null = null;+ onclose: (() => void) | null = null;+ onmessage: ((event: { data: string }) => void) | null = null;+ send = vi.fn();+ // Deliberately delay close events to reproduce the project-switch race.+ close = vi.fn(() => {+ this.readyState = 3;+ });+ constructor(public url: string) {+ TestSocket.instances.push(this);+ }+ open() {+ this.readyState = 1;+ this.onopen?.();+ }+}++describe("project WebSocket lifecycle", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal("WebSocket", TestSocket);+ vi.stubEnv("VITE_API_URL", "http://localhost:1337");+ TestSocket.instances = [];+ auth.userId = "user-a";+ client.invalidateQueries.mockClear();+ });+ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ });++ it("ignores late old-project events without stopping the new project's keepalive", () => {+ const { rerender, unmount } = renderHook(+ ({ id }) => useProjectWebSocket(id),+ { initialProps: { id: "project-a" } },+ );+ const old = TestSocket.instances[0];+ act(() => old.open());+ rerender({ id: "project-b" });+ const current = TestSocket.instances[1];+ act(() => {+ current.open();+ old.onclose?.();+ old.onopen?.();+ old.onmessage?.({+ data: JSON.stringify({+ type: "TASK_UPDATED",+ projectId: "project-a",+ taskId: "old-task",+ }),+ });+ vi.advanceTimersByTime(30_000);+ });+ expect(+ TestSocket.instances.map((socket) => new URL(socket.url).pathname),+ ).toEqual(["/api/ws/project-a", "/api/ws/project-b"]);+ expect(old.close).toHaveBeenCalledOnce();+ expect(old.send).not.toHaveBeenCalled();+ expect(current.send).toHaveBeenCalledWith('{"type":"ping"}');+ expect(client.invalidateQueries).not.toHaveBeenCalled();+ unmount();+ act(() => current.onclose?.());+ expect(current.close).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("cancels scheduled reconnects on logout and starts a fresh connection on login", () => {+ const { rerender, unmount } = renderHook(() =>+ useProjectWebSocket("project-a"),+ );+ act(() => TestSocket.instances[0].onclose?.());+ expect(vi.getTimerCount()).toBe(1);+ auth.userId = null;+ rerender();+ act(() => vi.advanceTimersByTime(60_000));+ expect(TestSocket.instances).toHaveLength(1);+ auth.userId = "user-b";+ rerender();+ expect(TestSocket.instances).toHaveLength(2);+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("preserves bounded exponential reconnects and active message invalidation", () => {+ const { unmount } = renderHook(() => useProjectWebSocket("project-a"));+ for (let retry = 0; retry < 5; retry++) {+ act(() => {+ TestSocket.instances.at(-1)?.onclose?.();+ vi.advanceTimersByTime(1000 * 2 ** retry);+ });+ expect(TestSocket.instances).toHaveLength(retry + 2);+ }+ const last = TestSocket.instances.at(-1);+ act(() => {+ last?.onmessage?.({+ data: JSON.stringify({+ type: "TASK_UPDATED",+ projectId: "project-a",+ taskId: "task-a",+ }),+ });+ last?.onclose?.();+ vi.advanceTimersByTime(60_000);+ });+ expect(TestSocket.instances).toHaveLength(6);+ expect(client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["tasks", "project-a"],+ });+ expect(client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["task", "task-a"],+ });+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsindex 8b41317ac..da36d792d 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -1,6 +1,6 @@import { windowId } from "@kaneo/libs";import { useQueryClient } from "@tanstack/react-query";-import { useEffect, useRef } from "react";+import { useEffect } from "react";import { getApiUrl } from "@/fetchers/get-api-url";import { authClient } from "@/lib/auth-client";@@ -20,33 +20,38 @@ const WS_PING_INTERVAL_MS = 30_000;export function useProjectWebSocket(projectId: string) {const queryClient = useQueryClient();const { data: session } = authClient.useSession();- const wsRef = useRef<WebSocket | null>(null);- const retriesRef = useRef(0);- const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);useEffect(() => {if (!projectId || !session?.user?.id) return;- retriesRef.current = 0;+ // Each effect owns its sockets and timers. Late events from an old project+ // or session must not alter the next effect's connection or reconnect it.+ let disposed = false;+ let activeSocket: WebSocket | null = null;+ let retries = 0;+ let retryTimeout: ReturnType<typeof setTimeout> | null = null;+ let pingInterval: ReturnType<typeof setInterval> | null = null;function clearPing() {- if (pingIntervalRef.current) {- clearInterval(pingIntervalRef.current);- pingIntervalRef.current = null;+ if (pingInterval !== null) {+ clearInterval(pingInterval);+ pingInterval = null;}}function connect() {+ if (disposed) return;+ retryTimeout = null;const url = getWsUrl(projectId);const ws = new WebSocket(url);- wsRef.current = ws;+ activeSocket = ws;ws.onopen = () => {- retriesRef.current = 0; // Reset retries on successful connection+ if (disposed || activeSocket !== ws) return;+ retries = 0; // Reset retries on successful connection// Start keepalive pings to prevent Cloudflare idle timeout (100s)clearPing();- pingIntervalRef.current = setInterval(() => {+ pingInterval = setInterval(() => {if (ws.readyState === WebSocket.OPEN) {ws.send(JSON.stringify({ type: "ping" }));}@@ -54,6 +59,7 @@ export function useProjectWebSocket(projectId: string) {};ws.onmessage = (event) => {+ if (disposed || activeSocket !== ws) return;try {const message = JSON.parse(event.data);if (@@ -118,25 +124,26 @@ export function useProjectWebSocket(projectId: string) {};ws.onclose = () => {+ if (disposed || activeSocket !== ws) return;clearPing();- wsRef.current = null;+ activeSocket = null;- if (retriesRef.current < MAX_RETRIES) {- const delay = BASE_DELAY * 2 ** retriesRef.current; // 1s, 2s, 4s, 8s, 16s- retriesRef.current += 1;- timeoutRef.current = setTimeout(connect, delay);+ if (retries < MAX_RETRIES) {+ const delay = BASE_DELAY * 2 ** retries; // 1s, 2s, 4s, 8s, 16s+ retries += 1;+ retryTimeout = setTimeout(connect, delay);}};}connect();return () => {- retriesRef.current = MAX_RETRIES; // Prevent reconnect after unmount+ disposed = true;clearPing();- if (timeoutRef.current) {- clearTimeout(timeoutRef.current);+ if (retryTimeout !== null) {+ clearTimeout(retryTimeout);}- wsRef.current?.close();+ activeSocket?.close();};}, [projectId, session?.user?.id, queryClient]);}diff --git a/apps/web/src/hooks/use-task-filters-with-labels-support.ts b/apps/web/src/hooks/use-task-filters-with-labels-support.tsindex 1a3a01e4b..c1ede7365 100644--- a/apps/web/src/hooks/use-task-filters-with-labels-support.ts+++ b/apps/web/src/hooks/use-task-filters-with-labels-support.ts@@ -65,6 +65,7 @@ export function useTaskFiltersWithLabelsSupport(project: ProjectWithTasks | null | undefined,projectId?: string,textQuery?: string,+ descriptionMatches?: ReadonlySet<string>,) {const weekStartsOn = useUserPreferencesStore((state) => state.weekStartsOn);const storageKey = projectId ? `kaneo:board-filters:${projectId}` : null;@@ -90,7 +91,11 @@ export function useTaskFiltersWithLabelsSupport(useEffect(() => {if (!storageKey || typeof window === "undefined") return;- window.localStorage.setItem(storageKey, JSON.stringify(filters));+ try {+ window.localStorage.setItem(storageKey, JSON.stringify(filters));+ } catch {+ // Storage may be unavailable or full; keep filters working in memory.+ }}, [filters, storageKey]);const filterTasks = useCallback(@@ -108,6 +113,7 @@ export function useTaskFiltersWithLabelsSupport(: "";const taskShortIdentifier = taskNumber ? `#${taskNumber}` : "";const matchesText =+ descriptionMatches?.has(task.id) ||title.includes(normalizedTextQuery) ||description.includes(normalizedTextQuery) ||taskNumber.includes(normalizedTextQuery) ||@@ -233,7 +239,14 @@ export function useTaskFiltersWithLabelsSupport(return true;});},- [filters, project?.slug, textQuery, weekStartsOn, getValuesForTask],+ [+ filters,+ project?.slug,+ textQuery,+ weekStartsOn,+ getValuesForTask,+ descriptionMatches,+ ],);const filteredProject = useMemo(() => {diff --git a/apps/web/src/hooks/use-task-filters.ts b/apps/web/src/hooks/use-task-filters.tsindex c6abf513d..bbd352ca2 100644--- a/apps/web/src/hooks/use-task-filters.ts+++ b/apps/web/src/hooks/use-task-filters.ts@@ -90,7 +90,11 @@ export function useTaskFilters(useEffect(() => {if (!storageKey || typeof window === "undefined") return;- window.localStorage.setItem(storageKey, JSON.stringify(filters));+ try {+ window.localStorage.setItem(storageKey, JSON.stringify(filters));+ } catch {+ // Storage may be unavailable or full; keep filters working in memory.+ }}, [filters, storageKey]);const filterTasks = (tasks: Task[]): Task[] => {diff --git a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsxnew file mode 100644index 000000000..6d8c447ab--- /dev/null+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx@@ -0,0 +1,126 @@+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useUserWebSocket } from "./use-user-websocket";++const { client, auth } = vi.hoisted(() => ({+ client: { invalidateQueries: vi.fn() },+ auth: { userId: "user-a" as string | null },+}));+vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));+vi.mock("@/lib/auth-client", () => ({+ authClient: {+ useSession: () => ({+ data: auth.userId ? { user: { id: auth.userId } } : null,+ }),+ },+}));+vi.mock("@kaneo/libs", () => ({ windowId: "local-test" }));+class TestSocket {+ static OPEN = 1;+ static instances: TestSocket[] = [];+ readyState = 0;+ onopen: (() => void) | null = null;+ onclose: (() => void) | null = null;+ onmessage: ((event: { data: string }) => void) | null = null;+ send = vi.fn();+ close = vi.fn(() => {+ this.readyState = 3;+ });+ constructor(public url: string) {+ TestSocket.instances.push(this);+ }+ open() {+ this.readyState = 1;+ this.onopen?.();+ }+}+describe("user WebSocket lifecycle", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal("WebSocket", TestSocket);+ vi.stubEnv("VITE_API_URL", "http://localhost:1337");+ TestSocket.instances = [];+ auth.userId = "user-a";+ client.invalidateQueries.mockClear();+ });+ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ });+ it("ignores events from an old account without stopping the new account's keepalive", () => {+ const { rerender, unmount } = renderHook(useUserWebSocket);+ const old = TestSocket.instances[0];+ act(() => old.open());+ auth.userId = "user-b";+ rerender();+ const current = TestSocket.instances[1];+ act(() => {+ current.open();+ old.onclose?.();+ old.onopen?.();+ old.onmessage?.({+ data: JSON.stringify({ type: "NOTIFICATION_CREATED" }),+ });+ vi.advanceTimersByTime(30_000);+ });+ expect(TestSocket.instances).toHaveLength(2);+ expect(old.close).toHaveBeenCalledOnce();+ expect(old.send).not.toHaveBeenCalled();+ expect(current.send).toHaveBeenCalledWith('{"type":"ping"}');+ expect(client.invalidateQueries).not.toHaveBeenCalled();+ act(() =>+ current.onmessage?.({+ data: JSON.stringify({ type: "NOTIFICATION_CREATED" }),+ }),+ );+ expect(client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["notifications"],+ });+ unmount();+ act(() => current.onclose?.());+ expect(current.close).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });+ it("cancels reconnects on logout and rejects stale messages from a closed socket", () => {+ const { rerender, unmount } = renderHook(useUserWebSocket);+ const old = TestSocket.instances[0];+ act(() => {+ old.onclose?.();+ old.onmessage?.({+ data: JSON.stringify({ type: "NOTIFICATION_CREATED" }),+ });+ });+ expect(client.invalidateQueries).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(1);+ auth.userId = null;+ rerender();+ act(() => vi.advanceTimersByTime(60_000));+ expect(TestSocket.instances).toHaveLength(1);+ auth.userId = "user-b";+ rerender();+ expect(TestSocket.instances).toHaveLength(2);+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ });+ it("retains the five-retry limit and does not duplicate retries on repeated close events", () => {+ const { unmount } = renderHook(useUserWebSocket);+ for (let retry = 0; retry < 5; retry++) {+ act(() => {+ const current = TestSocket.instances.at(-1);+ current?.onclose?.();+ current?.onclose?.();+ vi.advanceTimersByTime(1000 * 2 ** retry);+ });+ expect(TestSocket.instances).toHaveLength(retry + 2);+ }+ act(() => {+ TestSocket.instances.at(-1)?.onclose?.();+ vi.advanceTimersByTime(60_000);+ });+ expect(TestSocket.instances).toHaveLength(6);+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.tsindex 2854a892f..1eaf91547 100644--- a/apps/web/src/hooks/use-user-websocket.ts+++ b/apps/web/src/hooks/use-user-websocket.ts@@ -1,6 +1,6 @@import { windowId } from "@kaneo/libs";import { useQueryClient } from "@tanstack/react-query";-import { useEffect, useRef } from "react";+import { useEffect } from "react";import { getApiUrl } from "@/fetchers/get-api-url";import { authClient } from "@/lib/auth-client";@@ -22,32 +22,35 @@ const WS_PING_INTERVAL_MS = 30_000;export function useUserWebSocket() {const queryClient = useQueryClient();const { data: session } = authClient.useSession();- const wsRef = useRef<WebSocket | null>(null);- const retriesRef = useRef(0);- const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);-useEffect(() => {if (!session?.user?.id) return;- retriesRef.current = 0;+ // A previous session's delayed socket events must not control this session.+ let disposed = false;+ let activeSocket: WebSocket | null = null;+ let retries = 0;+ let retryTimeout: ReturnType<typeof setTimeout> | null = null;+ let pingInterval: ReturnType<typeof setInterval> | null = null;function clearPing() {- if (pingIntervalRef.current) {- clearInterval(pingIntervalRef.current);- pingIntervalRef.current = null;+ if (pingInterval !== null) {+ clearInterval(pingInterval);+ pingInterval = null;}}function connect() {+ if (disposed) return;+ retryTimeout = null;const url = getUserWsUrl();const ws = new WebSocket(url);- wsRef.current = ws;+ activeSocket = ws;ws.onopen = () => {- retriesRef.current = 0;+ if (disposed || activeSocket !== ws) return;+ retries = 0;clearPing();- pingIntervalRef.current = setInterval(() => {+ pingInterval = setInterval(() => {if (ws.readyState === WebSocket.OPEN) {ws.send(JSON.stringify({ type: "ping" }));}@@ -55,6 +58,7 @@ export function useUserWebSocket() {};ws.onmessage = (event) => {+ if (disposed || activeSocket !== ws) return;try {const message = JSON.parse(event.data as string) as {type?: string;@@ -68,13 +72,14 @@ export function useUserWebSocket() {};ws.onclose = () => {+ if (disposed || activeSocket !== ws) return;clearPing();- wsRef.current = null;+ activeSocket = null;- if (retriesRef.current < MAX_RETRIES) {- const delay = BASE_DELAY * 2 ** retriesRef.current;- retriesRef.current += 1;- timeoutRef.current = setTimeout(connect, delay);+ if (retries < MAX_RETRIES) {+ const delay = BASE_DELAY * 2 ** retries;+ retries += 1;+ retryTimeout = setTimeout(connect, delay);}};}@@ -82,12 +87,12 @@ export function useUserWebSocket() {connect();return () => {- retriesRef.current = MAX_RETRIES; // prevent reconnect after unmount+ disposed = true;clearPing();- if (timeoutRef.current) {- clearTimeout(timeoutRef.current);+ if (retryTimeout !== null) {+ clearTimeout(retryTimeout);}- wsRef.current?.close();+ activeSocket?.close();};}, [session?.user?.id, queryClient]);}diff --git a/apps/web/src/lib/column.test.tsx b/apps/web/src/lib/column.test.tsxnew file mode 100644index 000000000..45b2ee0d6--- /dev/null+++ b/apps/web/src/lib/column.test.tsx@@ -0,0 +1,26 @@+import { CheckCircle2, Circle, CircleDot } from "lucide-react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { getColumnIcon } from "./column";++describe("stored column icons", () => {+ it.each([+ "__proto__",+ "constructor",+ "toString",+ "hasOwnProperty",+ "unknown-icon",+ ])("uses safe fallbacks for %s", (name) => {+ expect(getColumnIcon("to-do", false, name).type).toBe(Circle);+ expect(getColumnIcon("done", true, name).type).toBe(CheckCircle2);+ expect(getColumnIcon(name, false).type).toBe(Circle);+ expect(() =>+ renderToStaticMarkup(getColumnIcon("to-do", false, name)),+ ).not.toThrow();+ });+ it("keeps selected and default icons", () => {+ expect(getColumnIcon("to-do", false, "CircleDot").type).toBe(CircleDot);+ expect(getColumnIcon("in-progress").type).toBe(CircleDot);+ expect(getColumnIcon("done").type).toBe(CheckCircle2);+ });+});diff --git a/apps/web/src/lib/column.tsx b/apps/web/src/lib/column.tsxindex 9d4602ad2..b9b4b6018 100644--- a/apps/web/src/lib/column.tsx+++ b/apps/web/src/lib/column.tsx@@ -10,11 +10,14 @@ export const getColumnIcon = () => {const resolvedIconName =iconName ||- DEFAULT_COLUMN_ICON_NAMES[- columnId as keyof typeof DEFAULT_COLUMN_ICON_NAMES- ];+ (Object.hasOwn(DEFAULT_COLUMN_ICON_NAMES, columnId)+ ? DEFAULT_COLUMN_ICON_NAMES[+ columnId as keyof typeof DEFAULT_COLUMN_ICON_NAMES+ ]+ : undefined);const Icon =- resolvedIconName &&+ typeof resolvedIconName === "string" &&+ Object.hasOwn(columnIcons, resolvedIconName) &&columnIcons[resolvedIconName as keyof typeof columnIcons];if (Icon) {diff --git a/apps/web/src/lib/external-url.test.ts b/apps/web/src/lib/external-url.test.tsnew file mode 100644index 000000000..0025920f0--- /dev/null+++ b/apps/web/src/lib/external-url.test.ts@@ -0,0 +1,31 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { getExternalWebUrl, openExternalWebUrl } from "./external-url";++afterEach(() => vi.restoreAllMocks());+describe("stored external links", () => {+ it.each([+ "javascript:alert(1)",+ "JaVaScRiPt:alert(1)",+ "\njavascript:alert(1)",+ "java\tscript:alert(1)",+ "data:text/html,<script>alert(1)</script>",+ "file:///etc/passwd",+ "//example.com/pr/1",+ "/pr/1",+ "https://user:[email protected]/pr/1",+ "invalid",+ ])("rejects %s without opening a window", (value) => {+ const open = vi.spyOn(window, "open").mockImplementation(() => null);+ expect(getExternalWebUrl(value)).toBeNull();+ openExternalWebUrl(value);+ expect(open).not.toHaveBeenCalled();+ });+ it.each([+ "https://github.com/owner/repo/pull/1",+ "http://gitea.internal/org/repo/pulls/1",+ ])("opens legitimate provider links without an opener: %s", (value) => {+ const open = vi.spyOn(window, "open").mockImplementation(() => null);+ openExternalWebUrl(value);+ expect(open).toHaveBeenCalledWith(value, "_blank", "noopener,noreferrer");+ });+});diff --git a/apps/web/src/lib/external-url.ts b/apps/web/src/lib/external-url.tsnew file mode 100644index 000000000..0a1fa5625--- /dev/null+++ b/apps/web/src/lib/external-url.ts@@ -0,0 +1,19 @@+export function getExternalWebUrl(value: string): string | null {+ try {+ const url = new URL(value);+ if (+ !["http:", "https:"].includes(url.protocol) ||+ url.username ||+ url.password+ )+ return null;+ return url.href;+ } catch {+ return null;+ }+}++export function openExternalWebUrl(value: string): void {+ const url = getExternalWebUrl(value);+ if (url) window.open(url, "_blank", "noopener,noreferrer");+}diff --git a/apps/web/src/lib/get-task-item-stats.test.ts b/apps/web/src/lib/get-task-item-stats.test.tsindex 1a49817cf..b5f18804e 100644--- a/apps/web/src/lib/get-task-item-stats.test.ts+++ b/apps/web/src/lib/get-task-item-stats.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { getTaskItemStats } from "./get-task-item-stats";+import { getTaskItemStats, MAX_TASK_STATS_CHARS } from "./get-task-item-stats";describe("getTaskItemStats", () => {it("returns zeroes for an empty description", () => {@@ -42,6 +42,22 @@ describe("getTaskItemStats", () => {});});+ it("omits counts for huge stored descriptions rather than reporting partial totals", () => {+ expect(+ getTaskItemStats(`- [x] Real\n${"\n".repeat(10 * 1024 * 1024)}`),+ ).toBeNull();+ expect(getTaskItemStats(" ".repeat(MAX_TASK_STATS_CHARS + 1))).toBeNull();+ });++ it("handles the exact budget and CRLF without allocating a line array", () => {+ const prefix = "- [x] Complete\r\n- [ ] Open\r\n";+ expect(+ getTaskItemStats(+ prefix + "\n".repeat(MAX_TASK_STATS_CHARS - prefix.length),+ ),+ ).toEqual({ total: 2, completed: 1 });+ });+it.each(["```", "~~~"])("keeps a %s fence open when a marker has trailing content",(marker) => {diff --git a/apps/web/src/lib/get-task-item-stats.ts b/apps/web/src/lib/get-task-item-stats.tsindex 94cfde793..95ce62a3e 100644--- a/apps/web/src/lib/get-task-item-stats.ts+++ b/apps/web/src/lib/get-task-item-stats.ts@@ -3,6 +3,9 @@ type TaskItemsStats = {completed: number;};+// Card metadata must not parse unbounded legacy/imported descriptions.+export const MAX_TASK_STATS_CHARS = 64 * 1024;+const TASK_ITEM_PATTERN =/^\s*(?:>\s*)*(?:[-+*]|\d{1,9}[.)])\s+\[([ xX])\](?:\s|$)/;const FENCE_PATTERN = /^\s*(?:>\s*)*(`{3,}|~{3,})/;@@ -19,9 +22,12 @@ const FENCE_PATTERN = /^\s*(?:>\s*)*(`{3,}|~{3,})/;* character and be at least as long as its opening fence.** @param description - Markdown task description, or null when absent.- * @returns The total number of task items and the number marked complete.+ * @returns Exact counts, or null when the description exceeds the card budget.*/-export function getTaskItemStats(description: string | null): TaskItemsStats {+export function getTaskItemStats(+ description: string | null,+): TaskItemsStats | null {+ if (description && description.length > MAX_TASK_STATS_CHARS) return null;if (!description) return { total: 0, completed: 0 };let total = 0;@@ -29,7 +35,12 @@ export function getTaskItemStats(description: string | null): TaskItemsStats {let fenceChar: string | null = null;let fenceLen = 0;- for (const line of description.split(/\r\n|\n/)) {+ let offset = 0;+ while (offset < description.length) {+ const newline = description.indexOf("\n", offset);+ const end = newline === -1 ? description.length : newline;+ const line = description.slice(offset, end).replace(/\r$/, "");+ offset = end + 1;const fenceMatch = FENCE_PATTERN.exec(line);if (fenceMatch) {diff --git a/apps/web/src/lib/get-task-label-options.test.ts b/apps/web/src/lib/get-task-label-options.test.tsindex 26903f2aa..672dc4455 100644--- a/apps/web/src/lib/get-task-label-options.test.ts+++ b/apps/web/src/lib/get-task-label-options.test.ts@@ -2,6 +2,21 @@ import { describe, expect, it } from "vitest";import { getTaskLabelOptions } from "./get-task-label-options";describe("getTaskLabelOptions", () => {+ it("excludes a pending workspace label and its remaining task copy", () => {+ const labels = [+ { id: "copy", name: "Bug", taskId: "task-1" },+ {+ id: "root",+ name: "Bug",+ taskId: null,+ deletionStartedAt: "2026-09-19T12:00:00Z",+ },+ { id: "other", name: "Ready", taskId: null },+ ];+ expect(+ getTaskLabelOptions(labels, "task-1").map((label) => label.id),+ ).toEqual(["other"]);+ });it("excludes labels assigned to other tasks", () => {const labels = [{ id: "workspace", name: "Bug", taskId: null },diff --git a/apps/web/src/lib/get-task-label-options.ts b/apps/web/src/lib/get-task-label-options.tsindex 6c0d3e63e..b14e9d5c3 100644--- a/apps/web/src/lib/get-task-label-options.ts+++ b/apps/web/src/lib/get-task-label-options.ts@@ -1,6 +1,7 @@type TaskScopedLabel = {name: string;taskId: string | null;+ deletionStartedAt?: string | Date | null;};export function getTaskLabelOptions<T extends TaskScopedLabel>(@@ -8,8 +9,14 @@ export function getTaskLabelOptions<T extends TaskScopedLabel>(taskId: string,) {const labelMap = new Map<string, T>();+ const deletingNames = new Set(+ labels+ .filter((label) => label.deletionStartedAt)+ .map((label) => label.name),+ );for (const label of labels) {+ if (deletingNames.has(label.name)) continue;if (label.taskId !== null && label.taskId !== taskId) continue;const existing = labelMap.get(label.name);diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/labels.test.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/labels.test.tsxnew file mode 100644index 000000000..df660d31c--- /dev/null+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/labels.test.tsx@@ -0,0 +1,113 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import type { ComponentType } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Route } from "./labels";++vi.mock("@/lib/i18n", () => ({ i18n: { t: (key: string) => key } }));++const m = vi.hoisted(() => ({+ remove: vi.fn(),+ success: vi.fn(),+ error: vi.fn(),+ pending: false,+}));+vi.mock("@tanstack/react-router", () => ({+ createFileRoute: () => (options: unknown) => ({ options }),+}));+vi.mock("@/components/page-title", () => ({ default: () => null }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, options?: { defaultValue?: string }) =>+ options?.defaultValue ?? key,+ }),+}));+vi.mock("@/hooks/use-workspace-permission", () => ({+ useWorkspacePermission: () => ({+ workspace: { id: "workspace" },+ canCreateLabels: () => true,+ canUpdateLabels: () => true,+ canDeleteLabels: () => true,+ }),+}));+vi.mock("@/hooks/queries/label/use-get-labels-by-workspace", () => ({+ default: () => ({+ data: [+ {+ id: "root",+ name: "bug",+ color: "red",+ taskId: null,+ deletionStartedAt: "2026-09-19T12:00:00Z",+ },+ ],+ }),+}));+vi.mock("@/hooks/mutations/label/use-create-label", () => ({+ default: () => ({}),+}));+vi.mock("@/hooks/mutations/label/use-update-label", () => ({+ default: () => ({}),+}));+vi.mock("@/hooks/mutations/label/use-delete-label", () => ({+ default: () => ({ mutateAsync: m.remove, isPending: m.pending }),+}));+vi.mock("@/lib/toast", () => ({+ toast: { success: m.success, error: m.error },+}));+const Component = Route.options.component as ComponentType;+afterEach(cleanup);+beforeEach(() => {+ vi.clearAllMocks();+ m.pending = false;+});+describe("resuming workspace label deletion", () => {+ it("shows persisted deletion state, prevents editing and resumes after confirmation", async () => {+ m.remove.mockResolvedValue({ id: "root" });+ render(<Component />);+ expect(+ screen.getByText("settings:workspaceLabels.deletionPending"),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Edit Label" })).toBeDisabled();+ fireEvent.click(+ screen.getByRole("button", {+ name: "settings:workspaceLabels.resumeDeletion",+ }),+ );+ const dialog = screen.getByRole("alertdialog");+ fireEvent.click(+ within(dialog).getByRole("button", {+ name: "settings:workspaceLabels.resumeDeletion",+ }),+ );+ await waitFor(() => expect(m.remove).toHaveBeenCalledWith({ id: "root" }));+ await waitFor(() =>+ expect(m.success).toHaveBeenCalledWith("Label deleted"),+ );+ });+ it("keeps the confirmation available and never reports success on another connection failure", async () => {+ m.remove.mockRejectedValue(new Error("Connection lost"));+ render(<Component />);+ fireEvent.click(+ screen.getByRole("button", {+ name: "settings:workspaceLabels.resumeDeletion",+ }),+ );+ fireEvent.click(+ within(screen.getByRole("alertdialog")).getByRole("button", {+ name: "settings:workspaceLabels.resumeDeletion",+ }),+ );+ await waitFor(() =>+ expect(m.error).toHaveBeenCalledWith("Connection lost"),+ );+ expect(screen.getByRole("alertdialog")).toBeInTheDocument();+ expect(m.success).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/labels.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/labels.tsxindex fb036731f..8a075aa23 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/labels.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/labels.tsx@@ -93,6 +93,7 @@ function RouteComponent() {const [deletingLabel, setDeletingLabel] = useState<{id: string;name: string;+ deletionStartedAt?: string | null;} | null>(null);const resetCreate = () => {@@ -186,7 +187,11 @@ function RouteComponent() {}};- const openDelete = (label: { id: string; name: string }) => {+ const openDelete = (label: {+ id: string;+ name: string;+ deletionStartedAt?: string | null;+ }) => {setDeletingLabel(label);setDeleteOpen(true);};@@ -288,6 +293,11 @@ function RouteComponent() {}}/><span className="text-sm truncate">{label.name}</span>+ {label.deletionStartedAt && (+ <span className="text-xs text-muted-foreground">+ {t("settings:workspaceLabels.deletionPending")}+ </span>+ )}</div>{(canUpdate || canDelete) && (<div className="flex items-center gap-1 flex-shrink-0">@@ -300,6 +310,10 @@ function RouteComponent() {{ defaultValue: "Edit Label" },)}className="h-8 w-8"+ disabled={+ !!label.deletionStartedAt ||+ deleteLabel.isPending+ }onClick={() =>openEdit({id: label.id,@@ -315,15 +329,20 @@ function RouteComponent() {<Buttonvariant="ghost"size="icon"- aria-label={t(- "settings:workspaceLabels.deleteLabel",- { defaultValue: "Delete" },- )}+ aria-label={+ label.deletionStartedAt+ ? t("settings:workspaceLabels.resumeDeletion")+ : t("settings:workspaceLabels.deleteLabel", {+ defaultValue: "Delete",+ })+ }+ disabled={deleteLabel.isPending}className="h-8 w-8 text-destructive hover:text-destructive"onClick={() =>openDelete({id: label.id,name: label.name,+ deletionStartedAt: label.deletionStartedAt,})}>@@ -561,9 +580,13 @@ function RouteComponent() {onClick={handleDelete}disabled={deleteLabel.isPending}>- {t("settings:workspaceLabels.deleteLabel", {- defaultValue: "Delete",- })}+ {deleteLabel.isPending+ ? t("common:actions.deleting")+ : deletingLabel?.deletionStartedAt+ ? t("settings:workspaceLabels.resumeDeletion")+ : t("settings:workspaceLabels.deleteLabel", {+ defaultValue: "Delete",+ })}</Button></AlertDialogFooter></AlertDialogContent>diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/roles.test.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/roles.test.tsxnew file mode 100644index 000000000..b3b0c5908--- /dev/null+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/roles.test.tsx@@ -0,0 +1,103 @@+import { defaultRolePayloads } from "@kaneo/permissions";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { CustomRoleEditor, PermissionList } from "./roles";++const m = vi.hoisted(() => ({ update: vi.fn() }));+vi.mock("@tanstack/react-router", () => ({+ createFileRoute: () => (options: unknown) => ({ options }),+}));+vi.mock("@/hooks/mutations/workspace/use-update-workspace-role", () => ({+ default: () => ({ mutateAsync: m.update, isPending: false }),+}));+vi.mock("@/hooks/mutations/workspace/use-create-workspace-role", () => ({+ default: () => ({}),+}));+vi.mock("@/hooks/mutations/workspace/use-delete-workspace-role", () => ({+ default: () => ({}),+}));+vi.mock("@/hooks/queries/workspace/use-workspace-roles", () => ({+ default: () => ({}),+}));+vi.mock("@/hooks/use-workspace-permission", () => ({+ useWorkspacePermission: () => ({}),+}));+vi.mock("@/components/page-title", () => ({ default: () => null }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, options?: { defaultValue?: string }) =>+ options?.defaultValue ?? key,+ }),+}));+vi.mock("@/lib/toast", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));+afterEach(() => cleanup());+beforeEach(() => {+ vi.clearAllMocks();+ m.update.mockResolvedValue({ success: true });+});++describe("workspace role permission editing", () => {+ it("shows role administration, membership and invitations in read-only role details", () => {+ render(<PermissionList permissions={defaultRolePayloads.admin} readOnly />);+ for (const label of [+ "Change role permissions",+ "Change member roles",+ "Invite members",+ "Edit teams",+ ]) {+ expect(screen.getByRole("switch", { name: label })).toBeChecked();+ expect(screen.getByRole("switch", { name: label })).toHaveAttribute(+ "aria-disabled",+ "true",+ );+ }+ });+ it("can remove every permission, including all provider administrative rights", async () => {+ render(+ <CustomRoleEditor+ workspaceId="workspace"+ role={{+ id: "role",+ workspaceId: "workspace",+ role: "admin",+ permission: defaultRolePayloads.admin,+ createdAt: new Date(),+ }}+ isDefault+ onDelete={() => {}}+ />,+ );+ for (const control of screen.getAllByRole("switch", { checked: true }))+ fireEvent.click(control);+ fireEvent.click(+ screen.getByRole("button", {+ name: "settings:workspaceRoles.saveChanges",+ }),+ );+ await waitFor(() =>+ expect(m.update).toHaveBeenCalledWith({+ workspaceId: "workspace",+ roleName: "admin",+ permission: {},+ }),+ );+ });+ it("also exposes unknown stored permission entries instead of silently retaining them", () => {+ render(+ <PermissionList+ permissions={{ extension: ["future-right"] }}+ selected={{ extension: new Set(["future-right"]) }}+ onToggle={() => {}}+ />,+ );+ expect(+ screen.getByRole("switch", { name: "future-right extension" }),+ ).toBeChecked();+ });+});diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/roles.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/roles.tsxindex 5fd45978a..746aa4abd 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/roles.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/workspace/roles.tsx@@ -1,7 +1,7 @@import { DEFAULT_ROLE_NAMES, statement } from "@kaneo/permissions";import { createFileRoute } from "@tanstack/react-router";import { Plus, Shield, Trash2, X } from "lucide-react";-import { useMemo, useState } from "react";+import { useId, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import PageTitle from "@/components/page-title";import {@@ -46,25 +46,14 @@ export const Route = createFileRoute(component: RouteComponent,});-// Resources our app contributes on top of better-auth's defaults-// (organization/member/team/invitation). Derive the list from the shared-// `@kaneo/permissions` statement so adding a new resource there picks it-// up here automatically.-// "ac" is better-auth's meta-resource for managing roles themselves; we don't-// surface it. Organization/member/team/invitation are likewise managed by the-// org plugin, not by our workspace permissions UI.-const BUILT_IN_RESOURCES = new Set([- "organization",- "member",- "team",- "invitation",- "ac",-]);-const CUSTOM_RESOURCES = (- Object.keys(statement) as (keyof typeof statement)[]-).filter((key) => !BUILT_IN_RESOURCES.has(key));-+// Every permission that can be saved must also be visible and removable.+// Include provider-owned resources and persisted unknown entries in the editor.const RESOURCE_LABELS: Record<string, string> = {+ organization: "Workspace administration",+ member: "Members",+ invitation: "Invitations",+ team: "Teams",+ ac: "Roles and permissions",project: "Projects",task: "Tasks",label: "Labels",@@ -75,6 +64,63 @@ const PERMISSION_LABELS: Record<string,{ label: string; description: string }> = {+ "organization:update": {+ label: "Edit workspace administration",+ description: "Change workspace settings through the account service.",+ },+ "organization:delete": {+ label: "Delete workspace",+ description:+ "Permanently delete the workspace through the account service.",+ },+ "member:create": {+ label: "Add members",+ description: "Add users to this workspace.",+ },+ "member:update": {+ label: "Change member roles",+ description: "Change the roles assigned to workspace members.",+ },+ "member:delete": {+ label: "Remove members",+ description: "Remove users from this workspace.",+ },+ "invitation:create": {+ label: "Invite members",+ description: "Send workspace invitations.",+ },+ "invitation:cancel": {+ label: "Cancel invitations",+ description: "Revoke pending workspace invitations.",+ },+ "team:create": {+ label: "Create teams",+ description: "Create teams in this workspace.",+ },+ "team:update": {+ label: "Edit teams",+ description: "Change teams and team membership.",+ },+ "team:delete": {+ label: "Delete teams",+ description: "Delete teams in this workspace.",+ },+ "ac:create": {+ label: "Create roles",+ description: "Create workspace roles and assign their permissions.",+ },+ "ac:read": {+ label: "View roles",+ description: "Read the workspace roles and their permissions.",+ },+ "ac:update": {+ label: "Change role permissions",+ description: "Change role permissions, including administrative access.",+ },+ "ac:delete": {+ label: "Delete roles",+ description: "Delete custom workspace roles.",+ },"project:create": {label: "Create projects",description: "Create new projects in this workspace.",@@ -445,7 +491,7 @@ function RouteComponent() {);}-function PermissionList({+export function PermissionList({permissions,selected,onToggle,@@ -459,17 +505,36 @@ function PermissionList({disabled?: boolean;}) {const { t } = useTranslation();- const groups = useMemo(- () =>- CUSTOM_RESOURCES.map((resource) => ({- resource,- actions: [...(statement[resource] ?? [])] as string[],- })),- [],- );+ const id = useId();+ const groups = useMemo(() => {+ const known = statement as Record<string, readonly string[]>;+ const resources = new Set([+ ...Object.keys(known),+ ...Object.keys(permissions),+ ...Object.keys(selected ?? {}),+ ]);+ return [...resources].map((resource) => ({+ resource,+ actions: [+ ...new Set([+ ...(Object.hasOwn(known, resource) ? (known[resource] ?? []) : []),+ ...(Object.hasOwn(permissions, resource)+ ? (permissions[resource] ?? [])+ : []),+ ...(selected && Object.hasOwn(selected, resource)+ ? (selected[resource] ?? [])+ : []),+ ]),+ ],+ }));+ }, [permissions, selected]);const isChecked = (resource: string, action: string) => {- if (selected) return selected[resource]?.has(action) ?? false;+ if (selected)+ return (+ Object.hasOwn(selected, resource) &&+ (selected[resource]?.has(action) ?? false)+ );return permissions[resource]?.includes(action) ?? false;};@@ -481,9 +546,9 @@ function PermissionList({<div className="space-y-4 p-4"><p className="text-sm font-medium capitalize">{t(`settings:workspaceRoles.resources.${resource}`, {- defaultValue:- RESOURCE_LABELS[resource] ??- resource.charAt(0).toUpperCase() + resource.slice(1),+ defaultValue: Object.hasOwn(RESOURCE_LABELS, resource)+ ? RESOURCE_LABELS[resource]+ : resource.charAt(0).toUpperCase() + resource.slice(1),})}</p><div className="space-y-4">@@ -499,7 +564,10 @@ function PermissionList({{idx > 0 && <Separator className="mb-4" />}<div className="flex items-center justify-between gap-6"><div className="space-y-0.5 flex-1 min-w-0">- <Label className="text-sm font-medium">+ <Label+ className="text-sm font-medium"+ htmlFor={`${id}-${resource}-${action}`}+ >{t(`settings:workspaceRoles.permissions.${labelKey}`,{@@ -519,6 +587,7 @@ function PermissionList({)}</div><Switch+ id={`${id}-${resource}-${action}`}checked={isChecked(resource, action)}onCheckedChange={readOnly || !onToggle@@ -648,7 +717,7 @@ function DraftEditor({);}-function CustomRoleEditor({+export function CustomRoleEditor({workspaceId,role,isDefault,@@ -662,7 +731,7 @@ function CustomRoleEditor({const { t } = useTranslation();const [permissions, setPermissions] = useState<Record<string, Set<string>>>(() => {- const out: Record<string, Set<string>> = {};+ const out: Record<string, Set<string>> = Object.create(null);for (const [r, actions] of Object.entries(role.permission)) {out[r] = new Set(actions);}@@ -672,7 +741,7 @@ function CustomRoleEditor({const { mutateAsync: updateRole, isPending } = useUpdateWorkspaceRole();const currentPermissions = useMemo(() => {- const out: Record<string, string[]> = {};+ const out: Record<string, string[]> = Object.create(null);for (const [r, set] of Object.entries(permissions)) {if (set.size > 0) out[r] = Array.from(set);}@@ -693,10 +762,6 @@ function CustomRoleEditor({};const handleSave = async () => {- if (Object.keys(currentPermissions).length === 0) {- toast.error(t("settings:workspaceRoles.validation.permissionRequired"));- return;- }try {await updateRole({workspaceId,diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsxindex 312757b4d..e96c46286 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/board.tsx@@ -15,6 +15,7 @@ import { shortcuts } from "@/constants/shortcuts";import useGetCustomFieldFilterValues from "@/hooks/queries/custom-field/use-get-custom-field-filter-values";import useGetCustomFieldsByProject from "@/hooks/queries/custom-field/use-get-custom-fields-by-project";import useGetLabelsByWorkspace from "@/hooks/queries/label/use-get-labels-by-workspace";+import { useDescriptionMatches } from "@/hooks/queries/task/use-description-matches";import { useGetTasks } from "@/hooks/queries/task/use-get-tasks";import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";import { useBoardSort } from "@/hooks/use-board-sort";@@ -186,6 +187,12 @@ function RouteComponent() {window.requestAnimationFrame(() => boardSearchInput?.focus());}, [isBoardSearchMounted, boardSearchInput]);+ const descriptionSearch = useDescriptionMatches(+ projectId,+ project,+ boardSearchQuery,+ );+const {filters,updateFilter,@@ -194,7 +201,12 @@ function RouteComponent() {filteredProject,hasActiveFilters,clearFilters,- } = useTaskFiltersWithLabelsSupport(project, projectId, boardSearchQuery);+ } = useTaskFiltersWithLabelsSupport(+ project,+ projectId,+ boardSearchQuery,+ descriptionSearch.ids,+ );const sortedProject = useMemo(() => {if (!filteredProject || sort.field === "position") return filteredProject;@@ -219,6 +231,7 @@ function RouteComponent() {<Inputref={setBoardSearchInput}value={boardSearchQuery}+ maxLength={256}onChange={(event) => setBoardSearchQuery(event.target.value)}onKeyDown={(event) => {if (event.key === "Escape" && !boardSearchQuery.trim()) {@@ -266,6 +279,24 @@ function RouteComponent() {usedCustomFieldValues={usedCustomFieldValues}/>+ {descriptionSearch.isLoading && (+ <p role="status" className="px-4 py-2 text-sm text-muted-foreground">+ {t("tasks:descriptionSearchLoading")}+ </p>+ )}+ {descriptionSearch.isError && (+ <p role="alert" className="px-4 py-2 text-sm text-destructive">+ {t("tasks:descriptionSearchError")}{" "}+ <button+ type="button"+ className="underline"+ onClick={() => void descriptionSearch.retry()}+ >+ {t("tasks:descriptionRetry")}+ </button>+ </p>+ )}+<div className="flex h-full flex-1 overflow-hidden bg-background">{sortedProject ? (viewMode === "board" ? (diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/gantt.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/gantt.tsxindex 40fffb607..56accd6d7 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/gantt.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/gantt.tsx@@ -1,16 +1,5 @@import { createFileRoute, useNavigate } from "@tanstack/react-router";-import {- addDays,- eachDayOfInterval,- endOfWeek,- format,- isSameMonth,- isToday,- isWeekend,- parseISO,- startOfWeek,- subDays,-} from "date-fns";+import { addDays, format, isSameMonth, isToday, isWeekend } from "date-fns";import { Calendar, ChevronLeft, ChevronRight, Search } from "lucide-react";import {useCallback,@@ -23,6 +12,11 @@ import {import { useTranslation } from "react-i18next";import ProjectLayout from "@/components/common/project-layout";import { GanttTaskBar } from "@/components/gantt/gantt-task-bar";+import {+ buildGanttTimeline,+ GANTT_WINDOW_DAYS,+ parseTaskDate,+} from "@/components/gantt/timeline";import PageTitle from "@/components/page-title";import TaskDetailsSheet from "@/components/task/task-details-sheet";import { Button } from "@/components/ui/button";@@ -46,12 +40,6 @@ export const Route = createFileRoute(}),});-function parseTaskDate(value: string | null) {- if (!value) return null;- const parsed = parseISO(value);- return Number.isNaN(parsed.getTime()) ? null : parsed;-}-function RouteComponent() {const { t } = useTranslation();const { projectId, workspaceId } = Route.useParams();@@ -60,6 +48,15 @@ function RouteComponent() {const { data: project } = useGetTasks(projectId);const weekStartsOn = useUserPreferencesStore((state) => state.weekStartsOn);const [searchQuery, setSearchQuery] = useState("");+ const [windowStart, setWindowStart] = useState<{+ projectId: string;+ date: Date;+ } | null>(null);+ const requestedStart =+ windowStart && windowStart.projectId === projectId+ ? windowStart.date+ : null;+ const showDate = (date: Date) => setWindowStart({ projectId, date });const isMobile = useIsMobile();const [isTaskRailOpen, setIsTaskRailOpen] = useState(false);@@ -145,36 +142,16 @@ function RouteComponent() {});}, [parsedTasks, project?.slug, searchQuery]);- const timeline = useMemo(() => {- if (parsedTasks.length === 0) return null;-- const earliest = parsedTasks.reduce(- (current, task) =>- task.scheduleStart < current ? task.scheduleStart : current,- parsedTasks[0].scheduleStart,- );- const latest = parsedTasks.reduce(- (current, task) =>- task.scheduleEnd > current ? task.scheduleEnd : current,- parsedTasks[0].scheduleEnd,- );-- // Week-aligned bounds around task dates, then pad with extra days so bars can- // be resized or moved past the current last task without running out of grid.- const weekStart = startOfWeek(earliest, { weekStartsOn });- const weekEnd = endOfWeek(latest, { weekStartsOn });- const rangeStart = subDays(weekStart, 7);- const rangeEnd = addDays(weekEnd, 28);-- const days = eachDayOfInterval({ start: rangeStart, end: rangeEnd });-- return {- days,- rangeStart,- gridTemplateColumns: `repeat(${days.length}, minmax(${dayColumnWidthRem}rem, ${dayColumnWidthRem}rem))`,- timelineMinWidthRem: days.length * dayColumnWidthRem,- };- }, [parsedTasks, dayColumnWidthRem, weekStartsOn]);+ const timeline = useMemo(+ () =>+ buildGanttTimeline(+ parsedTasks,+ weekStartsOn,+ dayColumnWidthRem,+ requestedStart,+ ),+ [parsedTasks, weekStartsOn, dayColumnWidthRem, requestedStart],+ );// Whether "today" actually falls inside the computed date range. A project// made up entirely of past or far-future tasks has no "today" column to@@ -276,6 +253,48 @@ function RouteComponent() {/></div>+ {timeline && (+ <div className="flex flex-wrap items-center gap-2">+ <Button+ variant="outline"+ size="icon-sm"+ aria-label={t("tasks:gantt.previousPeriod")}+ disabled={!timeline.hasPrevious}+ onClick={() =>+ showDate(addDays(timeline.rangeStart, -GANTT_WINDOW_DAYS))+ }+ >+ <ChevronLeft className="size-4" />+ </Button>+ <input+ type="date"+ aria-label={t("tasks:gantt.periodStart")}+ className="h-9 rounded-md border border-border bg-background px-2 text-sm"+ min={format(timeline.minimumStart, "yyyy-MM-dd")}+ max={format(timeline.maximumStart, "yyyy-MM-dd")}+ value={format(timeline.rangeStart, "yyyy-MM-dd")}+ onChange={(event) => {+ const date = parseTaskDate(event.target.value);+ if (date) showDate(date);+ }}+ />+ <span className="text-xs text-muted-foreground">+ – {format(timeline.rangeEnd, "MMM d, yyyy")}+ </span>+ <Button+ variant="outline"+ size="icon-sm"+ aria-label={t("tasks:gantt.nextPeriod")}+ disabled={!timeline.hasNext}+ onClick={() =>+ showDate(addDays(timeline.rangeStart, GANTT_WINDOW_DAYS))+ }+ >+ <ChevronRight className="size-4" />+ </Button>+ </div>+ )}+<Buttonvariant="outline"size="xs"@@ -452,13 +471,25 @@ function RouteComponent() {{task.title}</p><p className="w-full truncate text-[11px] leading-tight text-muted-foreground">- {format(task.scheduleStart, "MMM d")} -{" "}- {format(task.scheduleEnd, "MMM d")}+ {format(task.scheduleStart, "MMM d, yyyy")} -{" "}+ {format(task.scheduleEnd, "MMM d, yyyy")}{task.assigneeName? ` • ${task.assigneeName}`: ""}</p></button>+ {(task.scheduleEnd < timeline.rangeStart ||+ task.scheduleStart > timeline.rangeEnd) && (+ <button+ type="button"+ className="px-3 pb-2 text-xs text-primary underline"+ onClick={() =>+ showDate(addDays(task.scheduleStart, -7))+ }+ >+ {t("tasks:gantt.showTaskDates")}+ </button>+ )}</div>) : null}diff --git a/apps/web/src/routes/auth/captcha-flow.test.tsx b/apps/web/src/routes/auth/captcha-flow.test.tsxnew file mode 100644index 000000000..64f1954bd--- /dev/null+++ b/apps/web/src/routes/auth/captcha-flow.test.tsx@@ -0,0 +1,107 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import type { ComponentType, ReactNode } from "react";+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";++const m = vi.hoisted(() => ({+ anonymous: vi.fn(),+ social: vi.fn(),+ oauth2: vi.fn(),+ navigate: vi.fn(),+}));+vi.mock("@/lib/auth-client", () => ({+ authClient: { signIn: m, getLastUsedLoginMethod: () => null },+}));+vi.mock("@tanstack/react-router", () => ({+ createFileRoute: () => (options: unknown) => ({ options }),+ useSearch: () => ({}),+ useNavigate: () => m.navigate,+}));+vi.mock("@/hooks/queries/config/use-get-config", () => ({+ default: () => ({+ data: {+ hasGuestAccess: true,+ hasGithubSignIn: true,+ hasCustomOAuth: true,+ customOAuthAutoLogin: true,+ },+ isLoading: false,+ }),+}));+vi.mock("@/hooks/queries/instance/use-instance-status", () => ({+ default: () => ({+ data: { hasUsers: true, hasAdmin: true },+ isLoading: false,+ }),+}));+vi.mock("@/components/auth/layout", () => ({+ AuthLayout: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@/components/auth/sign-up-form", () => ({ SignUpForm: () => null }));+vi.mock("@/components/auth/sign-in-form", () => ({ SignInForm: () => null }));+vi.mock("@/components/auth/toggle", () => ({ AuthToggle: () => null }));+vi.mock("@/components/page-title", () => ({ default: () => null }));+vi.mock("@/components/auth/turnstile", () => ({+ Turnstile: ({ onVerify }: { onVerify: (token: string) => void }) => (+ <button type="button" onClick={() => onVerify("fresh-token")}>+ Solve CAPTCHA+ </button>+ ),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("@/lib/toast", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));++vi.stubEnv("VITE_TURNSTILE_SITE_KEY", "test-sitekey");+const { Route: signin } = await import("./sign-in");+const { Route: signup } = await import("./sign-up");+afterAll(() => vi.unstubAllEnvs());+afterEach(() => cleanup());+beforeEach(() => {+ vi.clearAllMocks();+ for (const mock of [m.anonymous, m.social, m.oauth2])+ mock.mockResolvedValue({ error: { message: "Retry" } });+});+describe.each([+ ["sign-in", signin],+ ["sign-up", signup],+] as const)("%s CAPTCHA submission", (_name, route) => {+ it.each([+ ["auth:signUp.continueAsGuest", "anonymous"],+ ["auth:signIn.continueWithGithub", "social"],+ ["auth:signIn.continueWithOidc", "oauth2"],+ ] as const)(+ "sends the token and requires a fresh one after %s fails",+ async (label, method) => {+ const Page = route.options.component as ComponentType;+ render(<Page />);+ expect(m.oauth2).not.toHaveBeenCalled(); // Auto-login cannot bypass CAPTCHA.+ const button = screen.getByRole("button", { name: label });+ expect(button).toBeDisabled();+ fireEvent.click(screen.getByRole("button", { name: "Solve CAPTCHA" }));+ fireEvent.click(button);+ await waitFor(() => expect(m[method]).toHaveBeenCalledTimes(1));+ expect(m[method].mock.calls[0]?.[1]).toEqual({+ headers: { "x-turnstile-token": "fresh-token" },+ });+ await waitFor(() => expect(button).toBeDisabled());+ expect(+ screen.getByRole("button", { name: "Solve CAPTCHA" }),+ ).toBeInTheDocument();+ },+ );+});diff --git a/apps/web/src/routes/auth/sign-in.tsx b/apps/web/src/routes/auth/sign-in.tsxindex f5037b774..9ba6e695a 100644--- a/apps/web/src/routes/auth/sign-in.tsx+++ b/apps/web/src/routes/auth/sign-in.tsx@@ -49,6 +49,11 @@ function SignIn() {const [isDiscordLoading, setIsDiscordLoading] = useState(false);const [isGuestLoading, setIsGuestLoading] = useState(false);const [turnstileToken, setTurnstileToken] = useState<string | null>(null);+ const [captchaKey, setCaptchaKey] = useState(0);+ const resetCaptcha = useCallback(() => {+ setTurnstileToken(null);+ setCaptchaKey((key) => key + 1);+ }, []);const [autoLoginFailed, setAutoLoginFailed] = useState(false);const lastLoginMethod = authClient.getLastUsedLoginMethod();const { data: config, isLoading: isConfigLoading } = useGetConfig();@@ -112,13 +117,21 @@ function SignIn() {}, [invitationId, getSafeRedirectPath]);const handleCustomOAuth = useCallback(async () => {+ if (captchaPending) return;setIsCustomOAuthLoading(true);try {- const result = await authClient.signIn.oauth2({- providerId: "custom",- callbackURL: getCallbackUrl(),- errorCallbackURL: `${import.meta.env.VITE_CLIENT_URL}/auth/sign-in`,- });+ const result = await authClient.signIn.oauth2(+ {+ providerId: "custom",+ callbackURL: getCallbackUrl(),+ errorCallbackURL: `${import.meta.env.VITE_CLIENT_URL}/auth/sign-in`,+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) {throw new Error(result.error.message);}@@ -129,17 +142,26 @@ function SignIn() {setAutoLoginFailed(true);} finally {setIsCustomOAuthLoading(false);+ resetCaptcha();}- }, [getCallbackUrl, t]);+ }, [getCallbackUrl, t, captchaPending, turnstileToken, resetCaptcha]);const handleSignInGoogle = async () => {+ if (captchaPending) return;setIsGoogleLoading(true);try {- const result = await authClient.signIn.social({- provider: "google",- callbackURL: getCallbackUrl(),- errorCallbackURL: `${import.meta.env.VITE_CLIENT_URL}/auth/sign-in`,- });+ const result = await authClient.signIn.social(+ {+ provider: "google",+ callbackURL: getCallbackUrl(),+ errorCallbackURL: `${import.meta.env.VITE_CLIENT_URL}/auth/sign-in`,+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) {throw new Error(result.error.message);}@@ -149,17 +171,26 @@ function SignIn() {);} finally {setIsGoogleLoading(false);+ resetCaptcha();}};const handleSignInGithub = async () => {+ if (captchaPending) return;setIsGithubLoading(true);try {- const result = await authClient.signIn.social({- provider: "github",- callbackURL: getCallbackUrl(),- errorCallbackURL: `${import.meta.env.VITE_CLIENT_URL}/auth/sign-in`,- });+ const result = await authClient.signIn.social(+ {+ provider: "github",+ callbackURL: getCallbackUrl(),+ errorCallbackURL: `${import.meta.env.VITE_CLIENT_URL}/auth/sign-in`,+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) {throw new Error(result.error.message);}@@ -169,17 +200,26 @@ function SignIn() {);} finally {setIsGithubLoading(false);+ resetCaptcha();}};const handleSignInDiscord = async () => {+ if (captchaPending) return;setIsDiscordLoading(true);try {- const result = await authClient.signIn.social({- provider: "discord",- callbackURL: getCallbackUrl(),- errorCallbackURL: `${import.meta.env.VITE_CLIENT_URL}/auth/sign-in`,- });+ const result = await authClient.signIn.social(+ {+ provider: "discord",+ callbackURL: getCallbackUrl(),+ errorCallbackURL: `${import.meta.env.VITE_CLIENT_URL}/auth/sign-in`,+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) {throw new Error(result.error.message);}@@ -189,6 +229,7 @@ function SignIn() {);} finally {setIsDiscordLoading(false);+ resetCaptcha();}};@@ -207,7 +248,14 @@ function SignIn() {if (captchaPending) return;setIsGuestLoading(true);try {- const result = await authClient.signIn.anonymous();+ const result = await authClient.signIn.anonymous(+ {},+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) {throw new Error(result.error.message);}@@ -219,6 +267,7 @@ function SignIn() {);} finally {setIsGuestLoading(false);+ resetCaptcha();}};@@ -230,6 +279,7 @@ function SignIn() {useEffect(() => {if (+ !captchaConfigured &&config?.customOAuthAutoLogin &&config?.hasCustomOAuth &&!autoLoginTriggered.current &&@@ -238,7 +288,7 @@ function SignIn() {autoLoginTriggered.current = true;handleCustomOAuth();}- }, [config, handleCustomOAuth, search.error]);+ }, [config, handleCustomOAuth, search.error, captchaConfigured]);// Treat "no users yet" as still loading so the skeleton stays visible// while the useEffect above redirects to /auth/sign-up. Otherwise the@@ -247,7 +297,10 @@ function SignIn() {isConfigLoading ||isInstanceStatusLoading ||instanceStatus?.hasUsers === false ||- (config?.customOAuthAutoLogin && config?.hasCustomOAuth && !autoLoginFailed)+ (!captchaConfigured &&+ config?.customOAuthAutoLogin &&+ config?.hasCustomOAuth &&+ !autoLoginFailed)) {return (<>@@ -274,6 +327,15 @@ function SignIn() {}><div className="mt-6">+ {captchaConfigured && TURNSTILE_SITE_KEY && (+ <Turnstile+ key={captchaKey}+ siteKey={TURNSTILE_SITE_KEY}+ onVerify={handleTurnstileVerify}+ onExpire={handleTurnstileExpire}+ onError={handleTurnstileExpire}+ />+ )}{search.error && (<Alert variant="error" className="mb-4"><AlertDescription>@@ -309,7 +371,7 @@ function SignIn() {<Buttonvariant="outline"onClick={handleSignInGoogle}- disabled={isGoogleLoading}+ disabled={isGoogleLoading || captchaPending}className={cn("w-full",lastLoginMethod === "google" && "border-primary/50!",@@ -344,7 +406,7 @@ function SignIn() {<Buttonvariant="outline"onClick={handleSignInGithub}- disabled={isGithubLoading}+ disabled={isGithubLoading || captchaPending}className={cn("w-full",lastLoginMethod === "github" && "border-primary/50!",@@ -368,7 +430,7 @@ function SignIn() {<Buttonvariant="outline"onClick={handleSignInDiscord}- disabled={isDiscordLoading}+ disabled={isDiscordLoading || captchaPending}className={cn("w-full",lastLoginMethod === "discord" && "border-primary/50!",@@ -401,7 +463,7 @@ function SignIn() {<Buttonvariant="outline"onClick={handleCustomOAuth}- disabled={isCustomOAuthLoading}+ disabled={isCustomOAuthLoading || captchaPending}className={cn("w-full",lastLoginMethod === "custom" && "border-primary/50!",@@ -421,27 +483,17 @@ function SignIn() {)}{config?.hasGuestAccess && !invitationId && (- <>- <Button- variant="outline"- onClick={handleGuestAccess}- disabled={isGuestLoading || captchaPending}- className="w-full"- >- <UserCheck className="w-5 h-5 mr-2" />- {isGuestLoading- ? t("auth:signIn.signingIn")- : t("auth:signUp.continueAsGuest")}- </Button>- {captchaConfigured && TURNSTILE_SITE_KEY && (- <Turnstile- siteKey={TURNSTILE_SITE_KEY}- onVerify={handleTurnstileVerify}- onExpire={handleTurnstileExpire}- onError={handleTurnstileExpire}- />- )}- </>+ <Button+ variant="outline"+ onClick={handleGuestAccess}+ disabled={isGuestLoading || captchaPending}+ className="w-full"+ >+ <UserCheck className="w-5 h-5 mr-2" />+ {isGuestLoading+ ? t("auth:signIn.signingIn")+ : t("auth:signUp.continueAsGuest")}+ </Button>)}</div>@@ -462,6 +514,8 @@ function SignIn() {{!config?.disableLoginForm &&(config?.hasSmtp && !config?.disableEmailOtpSignIn ? (<OtpSignInForm+ turnstileToken={captchaConfigured ? turnstileToken : undefined}+ onAttemptComplete={resetCaptcha}invitationId={invitationId}defaultEmail={defaultEmail}redirect={getSafeRedirectPath()}diff --git a/apps/web/src/routes/auth/sign-up.tsx b/apps/web/src/routes/auth/sign-up.tsxindex f877ad637..3012b35e6 100644--- a/apps/web/src/routes/auth/sign-up.tsx+++ b/apps/web/src/routes/auth/sign-up.tsx@@ -40,6 +40,11 @@ function SignUp() {const search = useSearch({ from: "/auth/sign-up" });const [isGuestLoading, setIsGuestLoading] = useState(false);const [turnstileToken, setTurnstileToken] = useState<string | null>(null);+ const [captchaKey, setCaptchaKey] = useState(0);+ const resetCaptcha = useCallback(() => {+ setTurnstileToken(null);+ setCaptchaKey((key) => key + 1);+ }, []);const handleTurnstileVerify = useCallback((token: string) => {setTurnstileToken(token);}, []);@@ -82,7 +87,14 @@ function SignUp() {if (captchaPending) return;setIsGuestLoading(true);try {- const result = await authClient.signIn.anonymous();+ const result = await authClient.signIn.anonymous(+ {},+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) {throw new Error(result.error.message);}@@ -94,6 +106,7 @@ function SignUp() {);} finally {setIsGuestLoading(false);+ resetCaptcha();}};@@ -155,6 +168,8 @@ function SignUp() {callbackURL={callbackURL}errorCallbackURL={errorCallbackURL}disabled={captchaPending}+ turnstileToken={turnstileToken}+ onAttemptComplete={resetCaptcha}/>);// Hide self-service alternatives (guest + SSO) when registration@@ -213,10 +228,12 @@ function SignUp() {invitationId={invitationId}defaultEmail={prefillEmail}turnstileToken={captchaConfigured ? turnstileToken : undefined}+ onAttemptComplete={resetCaptcha}/>)}{captchaConfigured && TURNSTILE_SITE_KEY && (<Turnstile+ key={captchaKey}siteKey={TURNSTILE_SITE_KEY}onVerify={handleTurnstileVerify}onExpire={handleTurnstileExpire}diff --git a/apps/web/src/routes/auth/verify-otp.tsx b/apps/web/src/routes/auth/verify-otp.tsxindex 3a354467b..b87328ab5 100644--- a/apps/web/src/routes/auth/verify-otp.tsx+++ b/apps/web/src/routes/auth/verify-otp.tsx@@ -6,6 +6,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";import { useForm } from "react-hook-form";import { useTranslation } from "react-i18next";import { z } from "zod/v4";+import { Turnstile } from "@/components/auth/turnstile";import PageTitle from "@/components/page-title";import { Alert, AlertDescription } from "@/components/ui/alert";import { Button } from "@/components/ui/button";@@ -42,6 +43,10 @@ function VerifyOtp() {from: "/auth/verify-otp",});const [isPending, setIsPending] = useState(false);+ const siteKey = import.meta.env.VITE_TURNSTILE_SITE_KEY as string | undefined;+ const [turnstileToken, setTurnstileToken] = useState<string | null>(null);+ const [captchaKey, setCaptchaKey] = useState(0);+ const captchaPending = Boolean(siteKey) && !turnstileToken;const verifyOtpSchema = useMemo(() =>@@ -128,12 +133,20 @@ function VerifyOtp() {}, [form, isPending, onSubmit]);const handleResendOtp = async () => {+ if (captchaPending) return;setIsPending(true);try {- const result = await authClient.emailOtp.sendVerificationOtp({- email,- type: "sign-in",- });+ const result = await authClient.emailOtp.sendVerificationOtp(+ {+ email,+ type: "sign-in",+ },+ {+ headers: turnstileToken+ ? { "x-turnstile-token": turnstileToken }+ : undefined,+ },+ );if (result.error) {toast.error(@@ -152,6 +165,8 @@ function VerifyOtp() {);} finally {setIsPending(false);+ setTurnstileToken(null);+ setCaptchaKey((key) => key + 1);}};@@ -163,6 +178,15 @@ function VerifyOtp() {subtitle={t("auth:verifyOtp.subtitle")}><div className="space-y-4">+ {siteKey && (+ <Turnstile+ key={captchaKey}+ siteKey={siteKey}+ onVerify={setTurnstileToken}+ onExpire={() => setTurnstileToken(null)}+ onError={() => setTurnstileToken(null)}+ />+ )}<Alert><AlertDescription className="text-xs">{t("auth:verifyOtp.codeSentTo", { email })}@@ -225,7 +249,7 @@ function VerifyOtp() {type="button"variant="secondary"onClick={handleResendOtp}- disabled={isPending}+ disabled={isPending || captchaPending}className="w-full"><RefreshCcw className="size-4" />diff --git a/apps/web/src/routes/public-project.$projectId.tsx b/apps/web/src/routes/public-project.$projectId.tsxindex 4e6036ce5..6d6ec794b 100644--- a/apps/web/src/routes/public-project.$projectId.tsx+++ b/apps/web/src/routes/public-project.$projectId.tsx@@ -9,6 +9,7 @@ import { PublicKanbanView } from "@/components/public-project/kanban-view";import { KaneoBranding } from "@/components/public-project/kaneo-branding";import { PublicListView } from "@/components/public-project/list-view";import { LoadingSkeleton } from "@/components/public-project/loading-skeleton";+import { PublicProjectDescription } from "@/components/public-project/project-description";import { PublicTaskDetailModal } from "@/components/public-project/task-detail-modal";import { ThemeToggle } from "@/components/public-project/theme-toggle";import { Button } from "@/components/ui/button";@@ -87,11 +88,7 @@ function RouteComponent() {{t("publicProject:badge")}</span></div>- {project.description && (- <p className="text-xs text-muted-foreground truncate">- {project.description}- </p>- )}+ <PublicProjectDescription project={project} /></div></div>diff --git a/apps/web/src/types/task/index.ts b/apps/web/src/types/task/index.tsindex 2705509aa..3c312a366 100644--- a/apps/web/src/types/task/index.ts+++ b/apps/web/src/types/task/index.ts@@ -25,6 +25,7 @@ type Task = {title: string;number: number | null;description: string | null;+ descriptionDeferred?: boolean;status: string;priority: string | null;startDate: string | null;diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex 47952ac1b..358ce1e87 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -10,6 +10,7 @@ import packageJson from "../../package.json";const sentryAuthToken = process.env.SENTRY_AUTH_TOKEN;const sentryOrg = process.env.SENTRY_ORG;const sentryProject = process.env.SENTRY_PROJECT;+const uploadSourceMaps = Boolean(sentryAuthToken && sentryOrg && sentryProject);export default defineConfig({define: {@@ -26,13 +27,14 @@ export default defineConfig({react(),babel({ presets: [reactCompilerPreset()] }),// Hidden when Sentry env vars are absent so local dev does not depend on it.- ...(sentryAuthToken && sentryOrg && sentryProject+ ...(uploadSourceMaps? [sentryVitePlugin({authToken: sentryAuthToken,org: sentryOrg,project: sentryProject,release: { name: packageJson.version },+ sourcemaps: { filesToDeleteAfterUpload: ["./dist/**/*.map"] },}),]: []),@@ -55,11 +57,9 @@ export default defineConfig({},},build: {- // Source maps are required for the Sentry Vite plugin to upload and- // symbolicate stack traces. Hidden so the .map files are not served- // to end users; the Sentry plugin still attaches them to uploaded- // releases.- sourcemap: "hidden",+ // Generate maps only for private symbolication, then delete after upload.+ // "hidden" alone still writes publicly servable .map files.+ sourcemap: uploadSourceMaps ? "hidden" : false,rollupOptions: {},commonjsOptions: {include: [/better-auth/, /node_modules/],diff --git a/charts/kaneo/README.md b/charts/kaneo/README.mdindex 8b3da2317..69f88acdc 100644--- a/charts/kaneo/README.md+++ b/charts/kaneo/README.md@@ -99,9 +99,9 @@ When CPU autoscaling is enabled, set `kaneo.resources.requests.cpu`; Kubernetes| `kaneo.service.port` | Kaneo service port | `5173` || `kaneo.service.targetPort` | Kaneo container port | `5173` || `kaneo.env` | Environment variables for the Kaneo container | See `values.yaml` |-| `kaneo.env.clientUrl` | Public URL of the Kaneo instance. **Required for any non-localhost deployment**; sets `KANEO_CLIENT_URL`. Omitting this causes "invalid origin" errors on login. Note: this key is case-sensitive (`clientUrl`, not `clientURL`). | `""` |+| `kaneo.env.clientUrl` | Public URL of the Kaneo instance. **Required for every deployment**; sets `KANEO_CLIENT_URL`. Helm rejects missing values and URLs with credentials, paths, queries or fragments before creating resources. Note: this key is case-sensitive (`clientUrl`, not `clientURL`). | `""` || `kaneo.env.corsOrigins` | Allowed CORS origins as a comma-separated string or YAML list | `[]` |-| `kaneo.env.authSecret` | Required Better Auth secret (minimum 32 characters), ignored if existingSecret is enabled | `""` |+| `kaneo.env.authSecret` | Required Better Auth secret (minimum 32 characters), stored in a chart-managed Secret; ignored if existingSecret is enabled | `""` || `kaneo.env.existingSecret.enabled` | Whether to use an existing secret for `AUTH_SECRET` | `false` || `kaneo.env.existingSecret.name` | Name of the existing secret containing `AUTH_SECRET` | `""` || `kaneo.env.existingSecret.key` | Key in the existing secret that contains `AUTH_SECRET` | `auth-secret` |@@ -349,7 +349,7 @@ If you're migrating from a previous SQLite-based installation, you'll need to:Contact the Kaneo community on [Discord](https://discord.gg/rU4tSyhXXU) for migration assistance.## Troubleshooting### "invalid origin" error on login-Kaneo's API validates the `Origin` header on every request against `KANEO_CLIENT_URL`. If `clientUrl` is not set (or is set incorrectly), every login attempt fails with this error.+Kaneo's API validates the `Origin` header on every request against `KANEO_CLIENT_URL`. The chart now requires `clientUrl` before rendering. On older deployments, an unset or incorrect value can cause login failures.Set `clientUrl` to the URL users access Kaneo from:```yaml@@ -358,7 +358,7 @@ kaneo:clientUrl: "https://kaneo.your-domain.com"```-> **Note:** The key is `clientUrl` (camelCase). `clientURL` (all-caps) is silently ignored; the env var will be empty and login will fail with no helpful error.+> **Note:** The key is `clientUrl` (camelCase). `clientURL` (all-caps) does not configure this value; Helm reports the missing required `clientUrl`.### Pods crash immediately after upgrading to use `existingSecret`If pods enter `CrashLoopBackOff` after switching to an existing secret for the external database, the connection URI in the secret is likely wrong. Check what the pod is actually using:@@ -432,16 +432,16 @@ For production deployments, consider the following security recommendations:### Pod Security ContextOn clusters with Pod Security Admission enforcement, set the following to satisfy the `restricted` policy:```yaml-kaneo:- podSecurityContext:- runAsNonRoot: true- seccompProfile:- type: RuntimeDefault+podSecurityContext:+ runAsNonRoot: true+ seccompProfile:+ type: RuntimeDefault- securityContext:- allowPrivilegeEscalation: false- capabilities:- drop: ["ALL"]+kaneo:+ securityContext:+ allowPrivilegeEscalation: false+ capabilities:+ drop: ["ALL"]```### Registration ControlBy default, user registration is enabled. To disable new user registration:@@ -451,3 +451,9 @@ kaneo:disableRegistration: true```This will prevent new users from registering while still allowing existing users to log in. The registration option will be hidden from the login page.++### Authentication secret storage++The chart stores `kaneo.env.authSecret` in a Kubernetes Secret and the application Deployment references its `auth-secret` key. Upgrades preserve the supplied value; the chart does not generate a new signing secret. For production, prefer `kaneo.env.existingSecret` so secret material is not supplied in Helm values or retained in Helm release metadata. Limit access to Secrets and Helm release records.++When upgrading from a chart that placed `AUTH_SECRET` directly in the Deployment, consider the old Deployment, ReplicaSets, exported manifests and deployment logs exposed to readers of those resources. If those readers were not authorized to possess the signing secret, rotate it and invalidate affected authentication artifacts as part of the upgrade. Moving the value into a Secret does not revoke earlier copies.diff --git a/charts/kaneo/templates/auth-secret.yaml b/charts/kaneo/templates/auth-secret.yamlnew file mode 100644index 000000000..f077a36ac--- /dev/null+++ b/charts/kaneo/templates/auth-secret.yaml@@ -0,0 +1,11 @@+{{- if not .Values.kaneo.env.existingSecret.enabled }}+apiVersion: v1+kind: Secret+metadata:+ name: {{ include "kaneo.fullname" . }}-auth+ labels:+ {{- include "kaneo.labels" . | nindent 4 }}+type: Opaque+stringData:+ auth-secret: {{ .Values.kaneo.env.authSecret | quote }}+{{- end }}diff --git a/charts/kaneo/templates/deployment.yaml b/charts/kaneo/templates/deployment.yamlindex 7f7c71bad..0bb128d92 100644--- a/charts/kaneo/templates/deployment.yaml+++ b/charts/kaneo/templates/deployment.yaml@@ -5,7 +5,7 @@{{- else if $corsOrigins -}}{{- $corsOriginsValue = $corsOrigins -}}{{- else if .Values.kaneo.env.clientUrl -}}- {{- $corsOriginsValue = .Values.kaneo.env.clientUrl -}}+ {{- $corsOriginsValue = .Values.kaneo.env.clientUrl | trim | trimSuffix "/" -}}{{- end }}apiVersion: apps/v1kind: Deployment@@ -50,7 +50,7 @@ spec:protocol: TCPenv:- name: KANEO_CLIENT_URL- value: "{{ .Values.kaneo.env.clientUrl }}"+ value: {{ .Values.kaneo.env.clientUrl | trim | trimSuffix "/" | quote }}- name: CORS_ORIGINSvalue: {{ $corsOriginsValue | quote }}- name: AUTH_SECRET@@ -60,7 +60,10 @@ spec:name: {{ .Values.kaneo.env.existingSecret.name }}key: {{ .Values.kaneo.env.existingSecret.key }}{{- else }}- value: {{ .Values.kaneo.env.authSecret | quote }}+ valueFrom:+ secretKeyRef:+ name: {{ include "kaneo.fullname" . }}-auth+ key: auth-secret{{- end }}{{- if and (not .Values.kaneo.env.database.external.enabled) .Values.postgresql.auth.existingSecret }}- name: KANEO_POSTGRES_PASSWORDdiff --git a/charts/kaneo/templates/validations.yaml b/charts/kaneo/templates/validations.yamlindex 0b6249de6..3087b9b42 100644--- a/charts/kaneo/templates/validations.yaml+++ b/charts/kaneo/templates/validations.yaml@@ -8,3 +8,15 @@{{- if and .Values.autoscaling.enabled .Values.autoscaling.targetCPUUtilizationPercentage (not (dig "requests" "cpu" "" .Values.kaneo.resources)) -}}{{- fail "kaneo.resources.requests.cpu must be set when autoscaling CPU utilization is enabled" -}}{{- end -}}++{{- if and .Values.kaneo.env.existingSecret.enabled (or (not .Values.kaneo.env.existingSecret.name) (not .Values.kaneo.env.existingSecret.key)) -}}+{{- fail "kaneo.env.existingSecret requires a non-empty name and key" -}}+{{- end -}}+{{- $clientUrl := .Values.kaneo.env.clientUrl | trim -}}+{{- if not $clientUrl -}}+{{- fail "kaneo.env.clientUrl is required: set the public HTTP(S) origin used to access Kaneo (for example https://kaneo.example.com)" -}}+{{- end -}}+{{- $parsedClientUrl := urlParse $clientUrl -}}+{{- if or (not (has $parsedClientUrl.scheme (list "http" "https"))) (not $parsedClientUrl.host) $parsedClientUrl.userinfo $parsedClientUrl.query $parsedClientUrl.fragment (not (has $parsedClientUrl.path (list "" "/"))) -}}+{{- fail "kaneo.env.clientUrl must be an HTTP(S) origin without credentials, a path, a query or a fragment" -}}+{{- end -}}diff --git a/charts/kaneo/values.yaml b/charts/kaneo/values.yamlindex cb0e2a0f7..418192901 100644--- a/charts/kaneo/values.yaml+++ b/charts/kaneo/values.yaml@@ -84,6 +84,7 @@ kaneo:env:# Public URL of this Kaneo instance (e.g. https://kaneo.example.com)+ # Required public HTTP(S) origin, e.g. https://kaneo.example.com.# KANEO_API_URL is derived automatically as clientUrl/api if not setclientUrl: ""# Allowed CORS origins. Accepts a comma-separated string or YAML list.diff --git a/compose.yml b/compose.ymlindex 54ce68b87..0f7180845 100644--- a/compose.yml+++ b/compose.yml@@ -3,13 +3,14 @@ services:image: postgres:16-alpineenv_file:- .env- ports:- - "5432:5432"+ environment:+ POSTGRES_USER: ${POSTGRES_USER:-kaneo}+ POSTGRES_DB: ${POSTGRES_DB:-kaneo}volumes:- postgres_data:/var/lib/postgresql/datarestart: unless-stoppedhealthcheck:- test: ["CMD-SHELL", "pg_isready -U kaneo -d kaneo"]+ test: ["CMD-SHELL", 'pg_isready -U "$${POSTGRES_USER}" -d "$${POSTGRES_DB}"']interval: 10stimeout: 5sretries: 5diff --git a/deploy/kaneo-entrypoint.sh b/deploy/kaneo-entrypoint.shindex 156561a76..873e8c859 100644--- a/deploy/kaneo-entrypoint.sh+++ b/deploy/kaneo-entrypoint.sh@@ -2,7 +2,7 @@set -euurlencode() {- node -e 'const input = process.argv[1]; process.stdout.write(encodeURIComponent(input).replace(/[!\x27()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`));' "$1"+ node -e 'const input = process.argv[1]; process.stdout.write(encodeURIComponent(input).replace(/[!\x27()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`));' -- "$1"}api_pid=""diff --git a/i18n/az-AZ.json b/i18n/az-AZ.jsonindex 954c28c48..4713f1ba1 100644--- a/i18n/az-AZ.json+++ b/i18n/az-AZ.json@@ -678,7 +678,12 @@"project": "Layihələr","task": "Tapşırıqlar","label": "Etiketlər",- "workspace": "İş sahəsi"+ "workspace": "İş sahəsi",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -760,6 +765,72 @@"label": "Parametrləri idarə et","description": "İş sahəsinin parametrlərini idarə edə bilər"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -803,7 +874,9 @@"createError": "Etiketi yaratmaq alınmadı","updateError": "Etiketi yeniləmək alınmadı","deleteError": "Etiketi silmək alınmadı",- "nameRequired": "Etiketin adı tələb olunur"+ "nameRequired": "Etiketin adı tələb olunur",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"projectGeneral": {"pageTitle": "Layihə parametrləri",@@ -974,7 +1047,13 @@"importSectionHint": "GitHub repozitoriyanızdakı mövcud məsələləri tapşırıq kimi idxal edin","importing": "İdxal edilir...","importIssues": "Məsələləri idxal et",- "importDisabledHint": "İdxalı aktivləşdirmək üçün yuxarıdakı repozitoriya parametrlərini tamamlayın"+ "importDisabledHint": "İdxalı aktivləşdirmək üçün yuxarıdakı repozitoriya parametrlərini tamamlayın",+ "accountVerificationHint": "Connect your GitHub account to verify that you administer this repository.",+ "enableGithubSignInHint": "Ask your instance administrator to enable GitHub sign-in.",+ "reverifyHint": "Reconnect this repository to verify access and resume synchronization.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1631,7 +1710,9 @@"mermaid": {"renderFailed": "Mermaid diaqramını göstərmək mümkün olmadı"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1964,7 +2045,11 @@"updateDatesError": "Tapşırıq tarixlərini yeniləmək alınmadı","resizeStart": "Başlama tarixini sürüşdür","resizeDue": "Son tarixi sürüşdür",- "taskAriaLabel": "{{title}}: aç və ya köçürmək üçün sürüklə"+ "taskAriaLabel": "{{title}}: aç və ya köçürmək üçün sürüklə",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Tapşırıq silinsin?",@@ -2063,7 +2148,12 @@"deleteRow": "Sətri sil","deleteTable": "Cədvəli sil"}- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex 6322afafe..9112f1856 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -812,7 +812,13 @@"importSectionHint": "Importiere vorhandene Issues aus deinem GitHub-Repository als Aufgaben","importing": "Wird importiert...","importIssues": "Issues importieren",- "importDisabledHint": "Vervollständige die Repository-Konfiguration oben, um den Import zu aktivieren"+ "importDisabledHint": "Vervollständige die Repository-Konfiguration oben, um den Import zu aktivieren",+ "accountVerificationHint": "Verbinde dein GitHub-Konto, damit deine Administrationsrechte für dieses Repository geprüft werden können.",+ "enableGithubSignInHint": "Bitte die Administration deiner Instanz, die GitHub-Anmeldung zu aktivieren.",+ "reverifyHint": "Verbinde dieses Repository erneut, um den Zugriff zu bestätigen und die Synchronisierung fortzusetzen.",+ "resumeImport": "Import fortsetzen",+ "importPaused": "Der Fortschritt dieses Imports ist gespeichert. Du kannst ihn fortsetzen.",+ "importSummary": "Erstellt: {{imported}} · Aktualisiert: {{updated}} · Übersprungen: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1156,7 +1162,12 @@"project": "Projekte","task": "Aufgaben","label": "Labels",- "workspace": "Workspace"+ "workspace": "Workspace",+ "organization": "Workspace-Verwaltung",+ "member": "Mitglieder",+ "invitation": "Einladungen",+ "team": "Teams",+ "ac": "Rollen und Berechtigungen"},"permissions": {"project": {@@ -1238,6 +1249,72 @@"label": "Einstellungen verwalten","description": "Kann Workspace-Einstellungen verwalten"}+ },+ "organization": {+ "update": {+ "label": "Workspace-Verwaltung bearbeiten",+ "description": "Workspace-Einstellungen über den Kontodienst ändern."+ },+ "delete": {+ "label": "Workspace löschen",+ "description": "Den Workspace über den Kontodienst dauerhaft löschen."+ }+ },+ "member": {+ "create": {+ "label": "Mitglieder hinzufügen",+ "description": "Benutzer zu diesem Workspace hinzufügen."+ },+ "update": {+ "label": "Mitgliederrollen ändern",+ "description": "Die zugewiesenen Rollen von Workspace-Mitgliedern ändern."+ },+ "delete": {+ "label": "Mitglieder entfernen",+ "description": "Benutzer aus diesem Workspace entfernen."+ }+ },+ "invitation": {+ "create": {+ "label": "Mitglieder einladen",+ "description": "Einladungen zu diesem Workspace senden."+ },+ "cancel": {+ "label": "Einladungen widerrufen",+ "description": "Ausstehende Workspace-Einladungen widerrufen."+ }+ },+ "team": {+ "create": {+ "label": "Teams erstellen",+ "description": "Teams in diesem Workspace erstellen."+ },+ "update": {+ "label": "Teams bearbeiten",+ "description": "Teams und Teammitgliedschaften ändern."+ },+ "delete": {+ "label": "Teams löschen",+ "description": "Teams in diesem Workspace löschen."+ }+ },+ "ac": {+ "create": {+ "label": "Rollen erstellen",+ "description": "Workspace-Rollen erstellen und ihnen Berechtigungen zuweisen."+ },+ "read": {+ "label": "Rollen anzeigen",+ "description": "Workspace-Rollen und ihre Berechtigungen anzeigen."+ },+ "update": {+ "label": "Rollenberechtigungen ändern",+ "description": "Rollenberechtigungen einschließlich administrativer Rechte ändern."+ },+ "delete": {+ "label": "Rollen löschen",+ "description": "Benutzerdefinierte Workspace-Rollen löschen."+ }}},"validation": {@@ -1281,7 +1358,9 @@"createError": "Label konnte nicht erstellt werden","updateError": "Label konnte nicht aktualisiert werden","deleteError": "Label konnte nicht gelöscht werden",- "nameRequired": "Label-Name ist erforderlich"+ "nameRequired": "Label-Name ist erforderlich",+ "deletionPending": "Löschung ausstehend",+ "resumeDeletion": "Löschung fortsetzen"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1631,7 +1710,9 @@"mermaid": {"renderFailed": "Mermaid-Diagramm konnte nicht gerendert werden"}- }+ },+ "importedFrom": "Importiert aus {{source}}",+ "importedBy": "Importiert von {{name}}"}},"tasks": {@@ -1951,7 +2032,11 @@"resizeStart": "Startdatum anpassen","resizeDue": "Fälligkeitsdatum anpassen","taskAriaLabel": "{{title}}: öffnen oder ziehen zum Verschieben",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Vorheriger Zeitraum",+ "nextPeriod": "Nächster Zeitraum",+ "periodStart": "Startdatum der Zeitleiste",+ "showTaskDates": "Aufgabendaten anzeigen"},"delete": {"title": "Aufgabe löschen?",@@ -2063,7 +2148,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Vollständige Beschreibungen werden durchsucht…",+ "descriptionSearchError": "Die Suche in Beschreibungen ist fehlgeschlagen. Ergebnisse sind möglicherweise unvollständig.",+ "descriptionRetry": "Erneut versuchen",+ "descriptionLoading": "Beschreibung wird geladen…",+ "descriptionLoadError": "Die Beschreibung konnte nicht geladen werden. Versuche es erneut, um die aktuelle Version zu laden."},"invitations": {"email": {diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex 12a6d5c2f..74f71a5d5 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -812,7 +812,13 @@"importSectionHint": "Εισαγάγετε υπάρχοντα issues από το αποθετήριο GitHub ως εργασίες","importing": "Γίνεται εισαγωγή...","importIssues": "Εισαγωγή issues",- "importDisabledHint": "Ολοκληρώστε τη ρύθμιση του αποθετηρίου παραπάνω για να ενεργοποιήσετε την εισαγωγή"+ "importDisabledHint": "Ολοκληρώστε τη ρύθμιση του αποθετηρίου παραπάνω για να ενεργοποιήσετε την εισαγωγή",+ "accountVerificationHint": "Συνδέστε τον λογαριασμό σας στο GitHub για να επαληθεύσετε ότι διαχειρίζεστε αυτό το αποθετήριο.",+ "enableGithubSignInHint": "Ζητήστε από τον διαχειριστή της εγκατάστασής σας να ενεργοποιήσει τη σύνδεση μέσω GitHub.",+ "reverifyHint": "Συνδέστε ξανά αυτό το αποθετήριο για να επαληθεύσετε την πρόσβαση και να συνεχίσετε τον συγχρονισμό.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1156,7 +1162,12 @@"project": "Έργα","task": "Εργασίες","label": "Ετικέτες",- "workspace": "Χώρος εργασίας"+ "workspace": "Χώρος εργασίας",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1238,6 +1249,72 @@"label": "Διαχείριση ρυθμίσεων","description": "Μπορεί να διαχειρίζεται τις ρυθμίσεις του χώρου εργασίας"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1281,7 +1358,9 @@"createError": "Αποτυχία δημιουργίας ετικέτας","updateError": "Αποτυχία ενημέρωσης ετικέτας","deleteError": "Αποτυχία διαγραφής ετικέτας",- "nameRequired": "Το όνομα ετικέτας είναι υποχρεωτικό"+ "nameRequired": "Το όνομα ετικέτας είναι υποχρεωτικό",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1631,7 +1710,9 @@"mermaid": {"renderFailed": "Δεν ήταν δυνατή η απόδοση του διαγράμματος Mermaid"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1951,7 +2032,11 @@"resizeStart": "Αλλαγή μεγέθους ημερομηνίας έναρξης","resizeDue": "Αλλαγή μεγέθους ημερομηνίας λήξης","taskAriaLabel": "{{title}}: άνοιγμα ή σύρσιμο για μετακίνηση",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Διαγραφή εργασίας;",@@ -2063,7 +2148,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex 0f7545e58..2a407c15b 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -678,7 +678,12 @@"project": "Projects","task": "Tasks","label": "Labels",- "workspace": "Workspace"+ "workspace": "Workspace",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -760,6 +765,72 @@"label": "Manage Settings","description": "Can manage workspace settings"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -803,7 +874,9 @@"createError": "Failed to create label","updateError": "Failed to update label","deleteError": "Failed to delete label",- "nameRequired": "Label name is required"+ "nameRequired": "Label name is required",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"projectGeneral": {"pageTitle": "Project Settings",@@ -1000,7 +1073,13 @@"importSectionHint": "Import existing issues from your GitHub repository as tasks","importing": "Importing...","importIssues": "Import Issues",- "importDisabledHint": "Complete the repository configuration above to enable importing"+ "importDisabledHint": "Complete the repository configuration above to enable importing",+ "accountVerificationHint": "Connect your GitHub account to verify that you administer this repository.",+ "enableGithubSignInHint": "Ask your instance administrator to enable GitHub sign-in.",+ "reverifyHint": "Reconnect this repository to verify access and resume synchronization.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1631,7 +1710,9 @@"mermaid": {"renderFailed": "Mermaid diagram couldn't be rendered"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1964,7 +2045,11 @@"updateDatesError": "Failed to update task dates","resizeStart": "Resize start date","resizeDue": "Resize due date",- "taskAriaLabel": "{{title}}: open or drag to move"+ "taskAriaLabel": "{{title}}: open or drag to move",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Delete Task?",@@ -2063,7 +2148,12 @@"deleteRow": "Delete row","deleteTable": "Delete table"}- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex 285042f93..05abfe7ee 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -709,7 +709,13 @@"importSectionHint": "Importar issues existentes de GitHub como tareas","importing": "Importando...","importIssues": "Importar Issues",- "importDisabledHint": "Completa la configuración del repositorio para activar la importación"+ "importDisabledHint": "Completa la configuración del repositorio para activar la importación",+ "accountVerificationHint": "Conecta tu cuenta de GitHub para verificar que administras este repositorio.",+ "enableGithubSignInHint": "Pide al administrador de tu instancia que habilite el inicio de sesión con GitHub.",+ "reverifyHint": "Vuelve a conectar este repositorio para verificar el acceso y reanudar la sincronización.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"slackIntegration": {"validation": {@@ -1034,7 +1040,12 @@"project": "Proyectos","task": "Tareas","label": "Etiquetas",- "workspace": "Espacio de trabajo"+ "workspace": "Espacio de trabajo",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1116,6 +1127,72 @@"label": "Gestionar ajustes","description": "Puede gestionar los ajustes del espacio de trabajo"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1160,7 +1237,9 @@"createError": "Error al crear etiqueta","updateError": "Error al actualizar etiqueta","deleteError": "Error al eliminar etiqueta",- "nameRequired": "El nombre de la etiqueta es obligatorio"+ "nameRequired": "El nombre de la etiqueta es obligatorio",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"giteaIntegration": {"validation": {@@ -1636,7 +1715,9 @@"mermaid": {"renderFailed": "No se pudo renderizar el diagrama de Mermaid"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1945,7 +2026,11 @@"resizeStart": "Cambiar la fecha de comienzo","resizeDue": "Cambiar la fecha de vencimiento","taskAriaLabel": "{{title}}: abrir o arrastrar para mover",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "¿Eliminar tarea?",@@ -2069,7 +2154,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex 1b323a883..4233f3666 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -812,7 +812,13 @@"importSectionHint": "Importer les problèmes existants de votre dépôt GitHub en tant que tâches","importing": "Importation...","importIssues": "Importer les problèmes",- "importDisabledHint": "Complétez la configuration du dépôt ci-dessus pour activer l'importation"+ "importDisabledHint": "Complétez la configuration du dépôt ci-dessus pour activer l'importation",+ "accountVerificationHint": "Connectez votre compte GitHub pour vérifier que vous administrez ce dépôt.",+ "enableGithubSignInHint": "Demandez à l’administrateur de votre instance d’activer la connexion avec GitHub.",+ "reverifyHint": "Reconnectez ce dépôt pour vérifier les accès et reprendre la synchronisation.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1156,7 +1162,12 @@"project": "Projets","task": "Tâches","label": "Labels",- "workspace": "Espace de travail"+ "workspace": "Espace de travail",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1238,6 +1249,72 @@"label": "Gérer les paramètres","description": "Peut gérer les paramètres de l'espace de travail"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1282,7 +1359,9 @@"createError": "Échec de la création du label","updateError": "Échec de la mise à jour du label","deleteError": "Échec de la suppression du label",- "nameRequired": "Le nom du label est requis"+ "nameRequired": "Le nom du label est requis",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1636,7 +1715,9 @@"mermaid": {"renderFailed": "Impossible d'afficher le diagramme Mermaid"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1956,7 +2037,11 @@"resizeStart": "Redimensionner la date de début","resizeDue": "Redimensionner la date d'échéance","taskAriaLabel": "{{title}} : ouvrir ou déplacer",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Supprimer la tâche ?",@@ -2069,7 +2154,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/hi-IN.json b/i18n/hi-IN.jsonindex 5dc6ef274..ca46cd93c 100644--- a/i18n/hi-IN.json+++ b/i18n/hi-IN.json@@ -678,7 +678,12 @@"project": "प्रोजेक्ट","task": "कार्य","label": "लेबल",- "workspace": "वर्कस्पेस"+ "workspace": "वर्कस्पेस",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -760,6 +765,72 @@"label": "सेटिंग प्रबंधित करें","description": "वर्कस्पेस सेटिंग प्रबंधित कर सकते हैं"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -803,7 +874,9 @@"createError": "लेबल बनाने में विफल","updateError": "लेबल अपडेट करने में विफल","deleteError": "लेबल हटाने में विफल",- "nameRequired": "लेबल का नाम आवश्यक है"+ "nameRequired": "लेबल का नाम आवश्यक है",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"projectGeneral": {"pageTitle": "प्रोजेक्ट सेटिंग",@@ -974,7 +1047,13 @@"importSectionHint": "अपनी GitHub रिपॉज़िटरी से मौजूदा issues को कार्यों के रूप में आयात करें","importing": "आयात हो रहा है...","importIssues": "Issues आयात करें",- "importDisabledHint": "आयात सक्षम करने के लिए ऊपर रिपॉज़िटरी कॉन्फ़िगरेशन पूरा करें"+ "importDisabledHint": "आयात सक्षम करने के लिए ऊपर रिपॉज़िटरी कॉन्फ़िगरेशन पूरा करें",+ "accountVerificationHint": "इस रिपॉज़िटरी पर अपने व्यवस्थापक अधिकार सत्यापित करने के लिए अपना GitHub खाता कनेक्ट करें।",+ "enableGithubSignInHint": "अपने इंस्टेंस के व्यवस्थापक से GitHub साइन-इन सक्षम करने को कहें।",+ "reverifyHint": "पहुँच सत्यापित करने और सिंक्रोनाइज़ेशन फिर से शुरू करने के लिए इस रिपॉज़िटरी को दोबारा कनेक्ट करें।",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1631,7 +1710,9 @@"mermaid": {"renderFailed": "Mermaid डायग्राम प्रस्तुत नहीं किया जा सका"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1951,7 +2032,11 @@"resizeStart": "शुरू तारीख बदलें","resizeDue": "नियत तारीख बदलें","taskAriaLabel": "{{title}}: खोलें या ले जाने के लिए खींचें",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "कार्य हटाएँ?",@@ -2063,7 +2148,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/id-ID.json b/i18n/id-ID.jsonindex 5fbd11418..f4da34f89 100644--- a/i18n/id-ID.json+++ b/i18n/id-ID.json@@ -812,7 +812,13 @@"importSectionHint": "Impor issue yang ada dari repositori GitHub Anda sebagai tugas","importing": "Mengimpor...","importIssues": "Impor Issue",- "importDisabledHint": "Lengkapi konfigurasi repositori di atas untuk mengaktifkan impor"+ "importDisabledHint": "Lengkapi konfigurasi repositori di atas untuk mengaktifkan impor",+ "accountVerificationHint": "Hubungkan akun GitHub Anda untuk memverifikasi bahwa Anda mengelola repositori ini.",+ "enableGithubSignInHint": "Minta administrator instans Anda mengaktifkan masuk dengan GitHub.",+ "reverifyHint": "Hubungkan kembali repositori ini untuk memverifikasi akses dan melanjutkan sinkronisasi.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1155,7 +1161,12 @@"project": "Proyek","task": "Tugas","label": "Label",- "workspace": "Ruang kerja"+ "workspace": "Ruang kerja",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1237,6 +1248,72 @@"label": "Kelola pengaturan","description": "Atur integrasi, aturan notifikasi, dan preferensi ruang kerja."}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1280,7 +1357,9 @@"createError": "Gagal membuat label","updateError": "Gagal memperbarui label","deleteError": "Gagal menghapus label",- "nameRequired": "Nama label wajib diisi"+ "nameRequired": "Nama label wajib diisi",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1626,7 +1705,9 @@"mermaid": {"renderFailed": "Diagram Mermaid tidak dapat dirender"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1946,7 +2027,11 @@"resizeStart": "Ubah ukuran tanggal mulai","resizeDue": "Ubah ukuran tenggat","taskAriaLabel": "{{title}}: buka atau seret untuk memindahkan",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Hapus Tugas?",@@ -2057,7 +2142,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/it-IT.json b/i18n/it-IT.jsonindex 8701ae041..19888bffa 100644--- a/i18n/it-IT.json+++ b/i18n/it-IT.json@@ -678,7 +678,12 @@"project": "Progetti","task": "Attività","label": "Etichette",- "workspace": "Workspace"+ "workspace": "Workspace",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -760,6 +765,72 @@"label": "Gestire Impostazioni","description": "Può gestire le impostazioni del workspace"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -804,7 +875,9 @@"createError": "Creazione etichetta fallita","updateError": "Aggiornamento etichetta fallito","deleteError": "Eliminazione etichetta fallita",- "nameRequired": "Il nome dell'etichetta è obbligatorio"+ "nameRequired": "Il nome dell'etichetta è obbligatorio",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"projectGeneral": {"pageTitle": "Impostazioni Progetto",@@ -975,7 +1048,13 @@"importSectionHint": "Importa issue esistenti dal tuo repository GitHub come attività","importing": "Importazione in corso...","importIssues": "Importa Issue",- "importDisabledHint": "Completa la configurazione del repository sopra per abilitare l'importazione"+ "importDisabledHint": "Completa la configurazione del repository sopra per abilitare l'importazione",+ "accountVerificationHint": "Collega il tuo account GitHub per verificare che amministri questo repository.",+ "enableGithubSignInHint": "Chiedi all’amministratore della tua istanza di abilitare l’accesso con GitHub.",+ "reverifyHint": "Ricollega questo repository per verificare l’accesso e riprendere la sincronizzazione.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1636,7 +1715,9 @@"mermaid": {"renderFailed": "Impossibile eseguire il rendering del diagramma Mermaid"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1956,7 +2037,11 @@"resizeStart": "Ridimensiona data inizio","resizeDue": "Ridimensiona data scadenza","taskAriaLabel": "{{title}}: apri o trascina per spostare",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Eliminare l'Attività?",@@ -2069,7 +2154,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/ja-JP.json b/i18n/ja-JP.jsonindex 4b6baa09d..96c8f7211 100644--- a/i18n/ja-JP.json+++ b/i18n/ja-JP.json@@ -677,7 +677,12 @@"project": "プロジェクト","task": "タスク","label": "ラベル",- "workspace": "ワークスペース"+ "workspace": "ワークスペース",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -759,6 +764,72 @@"label": "設定の管理","description": "ワークスペース設定を管理できます"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -802,7 +873,9 @@"createError": "ラベルの作成に失敗しました","updateError": "ラベルの更新に失敗しました","deleteError": "ラベルの削除に失敗しました",- "nameRequired": "ラベル名は必須です"+ "nameRequired": "ラベル名は必須です",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"projectGeneral": {"pageTitle": "プロジェクト設定",@@ -973,7 +1046,13 @@"importSectionHint": "GitHub リポジトリの既存の Issue をタスクとしてインポートします","importing": "インポート中...","importIssues": "Issue をインポート",- "importDisabledHint": "インポートを有効にするには、上記のリポジトリ設定を完了してください"+ "importDisabledHint": "インポートを有効にするには、上記のリポジトリ設定を完了してください",+ "accountVerificationHint": "Connect your GitHub account to verify that you administer this repository.",+ "enableGithubSignInHint": "Ask your instance administrator to enable GitHub sign-in.",+ "reverifyHint": "Reconnect this repository to verify access and resume synchronization.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1626,7 +1705,9 @@"mermaid": {"renderFailed": "Mermaid ダイアグラムを描画できませんでした"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1959,7 +2040,11 @@"resizeStart": "開始日を変更","resizeDue": "期限を変更","taskAriaLabel": "{{title}}: 開く、またはドラッグして移動",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "タスクを削除しますか?",@@ -2057,7 +2142,12 @@"deleteRow": "行を削除","deleteTable": "表を削除"}- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/ko-KR.json b/i18n/ko-KR.jsonindex 63c76b82a..1d64c745e 100644--- a/i18n/ko-KR.json+++ b/i18n/ko-KR.json@@ -812,7 +812,13 @@"importSectionHint": "GitHub 저장소의 기존 이슈를 작업으로 가져옵니다","importing": "가져오는 중...","importIssues": "이슈 가져오기",- "importDisabledHint": "가져오기를 활성화하려면 위의 저장소 구성을 완료하세요"+ "importDisabledHint": "가져오기를 활성화하려면 위의 저장소 구성을 완료하세요",+ "accountVerificationHint": "이 저장소의 관리자 권한을 확인하려면 GitHub 계정을 연결하세요.",+ "enableGithubSignInHint": "인스턴스 관리자에게 GitHub 로그인을 활성화해 달라고 요청하세요.",+ "reverifyHint": "접근 권한을 확인하고 동기화를 재개하려면 이 저장소를 다시 연결하세요.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1155,7 +1161,12 @@"project": "프로젝트","task": "작업","label": "라벨",- "workspace": "워크스페이스"+ "workspace": "워크스페이스",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1237,6 +1248,72 @@"label": "설정 관리","description": "워크스페이스 설정을 관리할 수 있습니다"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1280,7 +1357,9 @@"createError": "라벨 생성에 실패했습니다","updateError": "라벨 업데이트에 실패했습니다","deleteError": "라벨 삭제에 실패했습니다",- "nameRequired": "라벨 이름은 필수입니다"+ "nameRequired": "라벨 이름은 필수입니다",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1626,7 +1705,9 @@"mermaid": {"renderFailed": "Mermaid 다이어그램을 렌더링할 수 없습니다"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1959,7 +2040,11 @@"resizeStart": "시작일 크기 조정","resizeDue": "마감일 크기 조정","taskAriaLabel": "{{title}}: 열거나 드래그하여 이동",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "작업을 삭제하시겠습니까?",@@ -2057,7 +2142,12 @@"deleteRow": "행 삭제","deleteTable": "표 삭제"}- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex 303b29527..492110481 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -812,7 +812,13 @@"importSectionHint": "Увези постоечки issues од твојот GitHub репозиториум како задачи","importing": "Се увезува...","importIssues": "Увези Issues",- "importDisabledHint": "Заврши ја конфигурацијата на репозиториумот погоре за да овозможиш увоз"+ "importDisabledHint": "Заврши ја конфигурацијата на репозиториумот погоре за да овозможиш увоз",+ "accountVerificationHint": "Поврзете ја вашата сметка на GitHub за да потврдите дека сте администратор на ова складиште.",+ "enableGithubSignInHint": "Побарајте од администраторот на вашата инстанца да овозможи најава преку GitHub.",+ "reverifyHint": "Поврзете го складиштето повторно за да го потврдите пристапот и да ја продолжите синхронизацијата.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1156,7 +1162,12 @@"project": "Проекти","task": "Задачи","label": "Ознаки",- "workspace": "Работен простор"+ "workspace": "Работен простор",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1238,6 +1249,72 @@"label": "Управување со поставки","description": "Може да управува со поставките на работниот простор"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1281,7 +1358,9 @@"createError": "Неуспешно креирање на ознака","updateError": "Неуспешно ажурирање на ознака","deleteError": "Неуспешно бришење на ознака",- "nameRequired": "Името на ознаката е задолжително"+ "nameRequired": "Името на ознаката е задолжително",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1631,7 +1710,9 @@"mermaid": {"renderFailed": "Mermaid дијаграмот не можеше да се прикаже"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1951,7 +2032,11 @@"resizeStart": "Промени почетен датум","resizeDue": "Промени краен рок","taskAriaLabel": "{{title}}: отвори или повлечи за преместување",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Избриши задача?",@@ -2063,7 +2148,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex 9f176638b..36c5d9bf4 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -709,7 +709,13 @@"importSectionHint": "Importeer bestaande issues van GitHub als taken","importing": "Importeren...","importIssues": "Issues importeren",- "importDisabledHint": "Voltooi de configuratie hierboven om importeren mogelijk te maken"+ "importDisabledHint": "Voltooi de configuratie hierboven om importeren mogelijk te maken",+ "accountVerificationHint": "Koppel je GitHub-account om te controleren of je deze repository beheert.",+ "enableGithubSignInHint": "Vraag de beheerder van je instantie om aanmelden via GitHub in te schakelen.",+ "reverifyHint": "Koppel deze repository opnieuw om de toegang te controleren en de synchronisatie te hervatten.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"slackIntegration": {"validation": {@@ -1034,7 +1040,12 @@"project": "Projecten","task": "Taken","label": "Labels",- "workspace": "Werkruimte"+ "workspace": "Werkruimte",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1116,6 +1127,72 @@"label": "Instellingen beheren","description": "Kan werkruimte-instellingen beheren"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1159,7 +1236,9 @@"createError": "Aanmaken label mislukt","updateError": "Bijwerken label mislukt","deleteError": "Verwijderen label mislukt",- "nameRequired": "Labelnaam is verplicht"+ "nameRequired": "Labelnaam is verplicht",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"giteaIntegration": {"validation": {@@ -1631,7 +1710,9 @@"mermaid": {"renderFailed": "Mermaid-diagram kon niet worden weergegeven"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1940,7 +2021,11 @@"resizeStart": "Startdatum wijzigen","resizeDue": "Einddatum wijzigen","taskAriaLabel": "{{title}}: openen of slepen om te verplaatsen",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Taak verwijderen?",@@ -2063,7 +2148,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/pl-PL.json b/i18n/pl-PL.jsonindex 9cd3533c3..191597860 100644--- a/i18n/pl-PL.json+++ b/i18n/pl-PL.json@@ -810,7 +810,9 @@"save": "Zapisz","submitShortcut": "Wyślij komentarz","updated": "Zaktualizowano komentarz",- "viewGithubProfile": "Wyświetl profil GitHub"+ "viewGithubProfile": "Wyświetl profil GitHub",+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"},"created": "utworzył(a) to zadanie","githubUser": "Użytkownik GitHub",@@ -1136,7 +1138,13 @@"ownerInvalid": "Nieprawidłowy format nazwy właściciela repozytorium","ownerRequired": "Właściciel repozytorium jest wymagany"},- "verify": "Zweryfikuj"+ "verify": "Zweryfikuj",+ "accountVerificationHint": "Connect your GitHub account to verify that you administer this repository.",+ "enableGithubSignInHint": "Ask your instance administrator to enable GitHub sign-in.",+ "reverifyHint": "Reconnect this repository to verify access and resume synchronization.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"information": "Informacje","informationPage": {@@ -1620,7 +1628,9 @@"subtitle": "Twórz, edytuj i usuwaj etykiety na poziomie obszaru roboczego.","title": "Etykiety","updateError": "Nie udało się zaktualizować etykiety",- "updateSuccess": "Zaktualizowano etykietę"+ "updateSuccess": "Zaktualizowano etykietę",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"workspaceRoles": {"allChangesSaved": "Wszystkie zmiany zostały zapisane",@@ -1732,13 +1742,84 @@"description": "Może aktualizować ustawienia obszaru roboczego","label": "Zaktualizuj"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"resources": {"label": "Etykiety","project": "Projekty","task": "Zadania",- "workspace": "Obszar roboczy"+ "workspace": "Obszar roboczy",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"saveChanges": "Zapisz zmiany","sectionSubtitle": "Edytuj role domyślne lub dodaj własną. Członkowie zachowują przypisaną nazwę roli podczas edycji.",@@ -2099,7 +2180,11 @@"taskAriaLabel": "{{title}}: otwórz lub przeciągnij, aby przenieść","taskHeader": "Zadanie","title": "Oś czasu Gantta",- "updateDatesError": "Nie udało się zaktualizować dat zadania"+ "updateDatesError": "Nie udało się zaktualizować dat zadania",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"kanban": {"addTask": "Dodaj zadanie"@@ -2257,6 +2342,11 @@"view": {"board": "Tablica","list": "Lista"- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."}}diff --git a/i18n/pt-BR.json b/i18n/pt-BR.jsonindex 6baab1d8b..c248358b6 100644--- a/i18n/pt-BR.json+++ b/i18n/pt-BR.json@@ -678,7 +678,12 @@"project": "Projetos","task": "Tarefas","label": "Etiquetas",- "workspace": "Espaço de trabalho"+ "workspace": "Espaço de trabalho",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -760,6 +765,72 @@"label": "Gerenciar configurações","description": "Pode gerenciar configurações do espaço de trabalho"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -804,7 +875,9 @@"createError": "Falha ao criar etiqueta","updateError": "Falha ao atualizar etiqueta","deleteError": "Falha ao excluir etiqueta",- "nameRequired": "O nome da etiqueta é obrigatório"+ "nameRequired": "O nome da etiqueta é obrigatório",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"projectGeneral": {"pageTitle": "Configurações do projeto",@@ -975,7 +1048,13 @@"importSectionHint": "Importe issues existentes do seu repositório do GitHub como tarefas","importing": "Importando...","importIssues": "Importar issues",- "importDisabledHint": "Conclua a configuração do repositório acima para ativar a importação"+ "importDisabledHint": "Conclua a configuração do repositório acima para ativar a importação",+ "accountVerificationHint": "Conecte sua conta do GitHub para verificar se você administra este repositório.",+ "enableGithubSignInHint": "Peça ao administrador da sua instância para habilitar o login com GitHub.",+ "reverifyHint": "Reconecte este repositório para verificar o acesso e retomar a sincronização.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1636,7 +1715,9 @@"mermaid": {"renderFailed": "Mermaid diagram couldn't be rendered"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1956,7 +2037,11 @@"resizeStart": "Redimensionar data de início","resizeDue": "Redimensionar data de vencimento","taskAriaLabel": "{{title}}: abrir ou arrastar para mover",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Excluir tarefa?",@@ -2069,7 +2154,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/ru-RU.json b/i18n/ru-RU.jsonindex b27cfa609..b1a4491ff 100644--- a/i18n/ru-RU.json+++ b/i18n/ru-RU.json@@ -812,7 +812,13 @@"importSectionHint": "Импортируйте существующие issues из вашего GitHub-репозитория как задачи","importing": "Импорт...","importIssues": "Импортировать Issues",- "importDisabledHint": "Завершите настройку репозитория выше, чтобы включить импорт"+ "importDisabledHint": "Завершите настройку репозитория выше, чтобы включить импорт",+ "accountVerificationHint": "Подключите аккаунт GitHub, чтобы подтвердить права администратора этого репозитория.",+ "enableGithubSignInHint": "Попросите администратора вашего сервера включить вход через GitHub.",+ "reverifyHint": "Подключите репозиторий повторно, чтобы подтвердить доступ и возобновить синхронизацию.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1166,7 +1172,12 @@"project": "Проекты","task": "Задачи","label": "Метки",- "workspace": "Рабочая область"+ "workspace": "Рабочая область",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1248,6 +1259,72 @@"label": "Управление настройками","description": "Может управлять настройками рабочей области"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1291,7 +1368,9 @@"createError": "Не удалось создать метку","updateError": "Не удалось обновить метку","deleteError": "Не удалось удалить метку",- "nameRequired": "Название метки обязательно"+ "nameRequired": "Название метки обязательно",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1647,7 +1726,9 @@"mermaid": {"renderFailed": "Не удалось отобразить диаграмму Mermaid"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"},"moved": "переместил задачу из «{{from}}» в «{{to}}»","created": "создал эту задачу"@@ -1977,7 +2058,11 @@"resizeStart": "Изменить дату начала","resizeDue": "Изменить срок выполнения","taskAriaLabel": "{{title}}: откройте или перетащите для перемещения",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Удалить задачу?",@@ -2131,7 +2216,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/schema.json b/i18n/schema.jsonindex 93a83e5d5..58c7049b4 100644--- a/i18n/schema.json+++ b/i18n/schema.json@@ -138,6 +138,25 @@},"required": ["label", "more"]},+ "boolean": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "true": {+ "type": "string"+ },+ "false": {+ "type": "string"+ },+ "undefined": {+ "type": "string"+ },+ "notSet": {+ "type": "string"+ }+ },+ "required": ["true", "false", "undefined", "notSet"]+ },"language": {"type": "object","additionalProperties": false,@@ -621,6 +640,7 @@"empty","pagination","breadcrumb",+ "boolean","language","people","error",@@ -2658,9 +2678,34 @@},"workspace": {"type": "string"+ },+ "organization": {+ "type": "string"+ },+ "member": {+ "type": "string"+ },+ "invitation": {+ "type": "string"+ },+ "team": {+ "type": "string"+ },+ "ac": {+ "type": "string"}},- "required": ["project", "task", "label", "workspace"]+ "required": [+ "project",+ "task",+ "label",+ "workspace",+ "organization",+ "member",+ "invitation",+ "team",+ "ac"+ ]},"permissions": {"type": "object",@@ -2927,9 +2972,236 @@}},"required": ["read", "update", "delete", "manage_settings"]+ },+ "organization": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "update": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "delete": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ }+ },+ "required": ["update", "delete"]+ },+ "member": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "create": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "update": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "delete": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ }+ },+ "required": ["create", "update", "delete"]+ },+ "invitation": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "create": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "cancel": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ }+ },+ "required": ["create", "cancel"]+ },+ "team": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "create": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "update": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "delete": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ }+ },+ "required": ["create", "update", "delete"]+ },+ "ac": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "create": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "read": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "update": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ },+ "delete": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": ["label", "description"]+ }+ },+ "required": ["create", "read", "update", "delete"]}},- "required": ["project", "task", "label", "workspace"]+ "required": [+ "project",+ "task",+ "label",+ "workspace",+ "organization",+ "member",+ "invitation",+ "team",+ "ac"+ ]},"validation": {"type": "object",@@ -3097,6 +3369,12 @@},"nameRequired": {"type": "string"+ },+ "deletionPending": {+ "type": "string"+ },+ "resumeDeletion": {+ "type": "string"}},"required": [@@ -3122,7 +3400,9 @@"createError","updateError","deleteError",- "nameRequired"+ "nameRequired",+ "deletionPending",+ "resumeDeletion"]},"projectGeneral": {@@ -3325,6 +3605,12 @@"slackSectionSubtitle": {"type": "string"},+ "mattermostSectionTitle": {+ "type": "string"+ },+ "mattermostSectionSubtitle": {+ "type": "string"+ },"telegramSectionTitle": {"type": "string"},@@ -3346,6 +3632,8 @@"genericWebhookSectionSubtitle","slackSectionTitle","slackSectionSubtitle",+ "mattermostSectionTitle",+ "mattermostSectionSubtitle","telegramSectionTitle","telegramSectionSubtitle"]@@ -3429,6 +3717,12 @@"columnsDescription": {"type": "string"},+ "customFieldsTitle": {+ "type": "string"+ },+ "customFieldsDescription": {+ "type": "string"+ },"automationTitle": {"type": "string"},@@ -3442,6 +3736,8 @@"subtitle","columnsTitle","columnsDescription",+ "customFieldsTitle",+ "customFieldsDescription","automationTitle","automationDescription"]@@ -3525,26 +3821,125 @@}},"required": [- "toastCreated",- "toastCreateError",- "toastRenamed",- "toastRenameError",- "toastFinalOn",- "toastFinalOff",- "toastUpdateError",- "toastIconUpdated",- "toastDeleted",- "toastDeleteError",+ "toastCreated",+ "toastCreateError",+ "toastRenamed",+ "toastRenameError",+ "toastFinalOn",+ "toastFinalOff",+ "toastUpdateError",+ "toastIconUpdated",+ "toastDeleted",+ "toastDeleteError",+ "loading",+ "pickIconTitle",+ "searchIconsPlaceholder",+ "doneColumnTooltip",+ "doneColumn",+ "markDoneAria",+ "on",+ "off",+ "newColumnPlaceholder",+ "add"+ ]+ },+ "customFields": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "namePlaceholder": {+ "type": "string"+ },+ "typePlaceholder": {+ "type": "string"+ },+ "noOptionsPlaceholder": {+ "type": "string"+ },+ "defaultValuePlaceholder": {+ "type": "string"+ },+ "optionsPlaceholder": {+ "type": "string"+ },+ "required": {+ "type": "string"+ },+ "addButton": {+ "type": "string"+ },+ "creating": {+ "type": "string"+ },+ "loading": {+ "type": "string"+ },+ "empty": {+ "type": "string"+ },+ "defaultLabel": {+ "type": "string"+ },+ "createSuccess": {+ "type": "string"+ },+ "createError": {+ "type": "string"+ },+ "deleteButton": {+ "type": "string"+ },+ "deleting": {+ "type": "string"+ },+ "deleteSuccess": {+ "type": "string"+ },+ "deleteError": {+ "type": "string"+ },+ "types": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "text": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "date": {+ "type": "string"+ },+ "dropdown": {+ "type": "string"+ },+ "boolean": {+ "type": "string"+ }+ },+ "required": ["text", "number", "date", "dropdown", "boolean"]+ }+ },+ "required": [+ "namePlaceholder",+ "typePlaceholder",+ "noOptionsPlaceholder",+ "defaultValuePlaceholder",+ "optionsPlaceholder",+ "required",+ "addButton",+ "creating","loading",- "pickIconTitle",- "searchIconsPlaceholder",- "doneColumnTooltip",- "doneColumn",- "markDoneAria",- "on",- "off",- "newColumnPlaceholder",- "add"+ "empty",+ "defaultLabel",+ "createSuccess",+ "createError",+ "deleteButton",+ "deleting",+ "deleteSuccess",+ "deleteError",+ "types"]},"githubIntegration": {@@ -3751,6 +4146,24 @@},"importDisabledHint": {"type": "string"+ },+ "accountVerificationHint": {+ "type": "string"+ },+ "enableGithubSignInHint": {+ "type": "string"+ },+ "reverifyHint": {+ "type": "string"+ },+ "resumeImport": {+ "type": "string"+ },+ "importPaused": {+ "type": "string"+ },+ "importSummary": {+ "type": "string"}},"required": [@@ -3790,7 +4203,13 @@"importSectionHint","importing","importIssues",- "importDisabledHint"+ "importDisabledHint",+ "accountVerificationHint",+ "enableGithubSignInHint",+ "reverifyHint",+ "resumeImport",+ "importPaused",+ "importSummary"]},"giteaIntegration": {@@ -4405,6 +4824,159 @@"disconnect"]},+ "mattermostIntegration": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "validation": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "webhookInvalid": {+ "type": "string"+ }+ },+ "required": ["webhookInvalid"]+ },+ "toast": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "saved": {+ "type": "string"+ },+ "saveError": {+ "type": "string"+ },+ "enabled": {+ "type": "string"+ },+ "disabled": {+ "type": "string"+ },+ "updateError": {+ "type": "string"+ },+ "removed": {+ "type": "string"+ },+ "removeError": {+ "type": "string"+ }+ },+ "required": [+ "saved",+ "saveError",+ "enabled",+ "disabled",+ "updateError",+ "removed",+ "removeError"+ ]+ },+ "connectionTitle": {+ "type": "string"+ },+ "connectionHint": {+ "type": "string"+ },+ "connected": {+ "type": "string"+ },+ "paused": {+ "type": "string"+ },+ "webhookLabel": {+ "type": "string"+ },+ "webhookPlaceholder": {+ "type": "string"+ },+ "webhookHint": {+ "type": "string"+ },+ "channelLabel": {+ "type": "string"+ },+ "channelPlaceholder": {+ "type": "string"+ },+ "channelHint": {+ "type": "string"+ },+ "eventsTitle": {+ "type": "string"+ },+ "eventsHint": {+ "type": "string"+ },+ "events": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "taskCreated": {+ "type": "string"+ },+ "taskStatusChanged": {+ "type": "string"+ },+ "taskPriorityChanged": {+ "type": "string"+ },+ "taskTitleChanged": {+ "type": "string"+ },+ "taskDescriptionChanged": {+ "type": "string"+ },+ "taskCommentCreated": {+ "type": "string"+ }+ },+ "required": [+ "taskCreated",+ "taskStatusChanged",+ "taskPriorityChanged",+ "taskTitleChanged",+ "taskDescriptionChanged",+ "taskCommentCreated"+ ]+ },+ "connect": {+ "type": "string"+ },+ "saveChanges": {+ "type": "string"+ },+ "update": {+ "type": "string"+ },+ "disconnect": {+ "type": "string"+ }+ },+ "required": [+ "validation",+ "toast",+ "connectionTitle",+ "connectionHint",+ "connected",+ "paused",+ "webhookLabel",+ "webhookPlaceholder",+ "webhookHint",+ "channelLabel",+ "channelPlaceholder",+ "channelHint",+ "eventsTitle",+ "eventsHint",+ "events",+ "connect",+ "saveChanges",+ "update",+ "disconnect"+ ]+ },"genericWebhookIntegration": {"type": "object","additionalProperties": false,@@ -5137,10 +5709,12 @@"projectWorkflow","projectSwitcher","columnEditor",+ "customFields","githubIntegration","giteaIntegration","slackIntegration","discordIntegration",+ "mattermostIntegration","genericWebhookIntegration","telegramIntegration","repositoryBrowser",@@ -6280,6 +6854,12 @@"table","mermaid"]+ },+ "importedFrom": {+ "type": "string"+ },+ "importedBy": {+ "type": "string"}},"required": [@@ -6298,7 +6878,9 @@"leavePlaceholder","attachFile","submitShortcut",- "editor"+ "editor",+ "importedFrom",+ "importedBy"]}},@@ -6322,6 +6904,9 @@"type": "object","additionalProperties": false,"properties": {+ "title": {+ "type": "string"+ },"status": {"type": "object","additionalProperties": false,@@ -6421,13 +7006,17 @@},"taskNotFoundDescription": {"type": "string"+ },+ "customFields": {+ "type": "string"}},"required": ["selectTask","loadingTask","taskNotFound",- "taskNotFoundDescription"+ "taskNotFoundDescription",+ "customFields"]},"detail": {@@ -6437,6 +7026,12 @@"subtaskOf": {"type": "string"},+ "customFieldUpdated": {+ "type": "string"+ },+ "selectOption": {+ "type": "string"+ },"activity": {"type": "string"},@@ -6838,6 +7433,8 @@},"required": ["subtaskOf",+ "customFieldUpdated",+ "selectOption","activity","noActivity","openInFullPage",@@ -7445,6 +8042,15 @@"allLabels": {"type": "string"},+ "noValuesUsedYet": {+ "type": "string"+ },+ "noCustomFieldValues": {+ "type": "string"+ },+ "allCustomFieldValues": {+ "type": "string"+ },"selectedCount": {"type": "string"},@@ -7466,6 +8072,9 @@"selectedCount_other": {"type": "string"},+ "all": {+ "type": "string"+ },"subjects": {"type": "object","additionalProperties": false,@@ -7515,6 +8124,10 @@"allAssignees","allDueDates","allLabels",+ "noValuesUsedYet",+ "noCustomFieldValues",+ "allCustomFieldValues",+ "all","subjects","operators"]@@ -7598,10 +8211,10 @@"title": {"type": "string"},- "searchPlaceholder": {+ "jumpToToday": {"type": "string"},- "jumpToToday": {+ "searchPlaceholder": {"type": "string"},"hideTasks": {@@ -7636,13 +8249,25 @@},"taskAriaLabel": {"type": "string"+ },+ "previousPeriod": {+ "type": "string"+ },+ "nextPeriod": {+ "type": "string"+ },+ "periodStart": {+ "type": "string"+ },+ "showTaskDates": {+ "type": "string"}},"required": ["pageTitle","title",- "searchPlaceholder","jumpToToday",+ "searchPlaceholder","hideTasks","showTasks","noTasks",@@ -7653,7 +8278,11 @@"updateDatesError","resizeStart","resizeDue",- "taskAriaLabel"+ "taskAriaLabel",+ "previousPeriod",+ "nextPeriod",+ "periodStart",+ "showTaskDates"]},"delete": {@@ -8192,9 +8821,25 @@}},"required": ["table"]+ },+ "descriptionSearchLoading": {+ "type": "string"+ },+ "descriptionSearchError": {+ "type": "string"+ },+ "descriptionRetry": {+ "type": "string"+ },+ "descriptionLoading": {+ "type": "string"+ },+ "descriptionLoadError": {+ "type": "string"}},"required": [+ "title","status","priority","boardSearchPlaceholder",@@ -8224,7 +8869,12 @@"contextMenu","actions","bulk",- "editor"+ "editor",+ "descriptionSearchLoading",+ "descriptionSearchError",+ "descriptionRetry",+ "descriptionLoading",+ "descriptionLoadError"]},"invitations": {diff --git a/i18n/tr-TR.json b/i18n/tr-TR.jsonindex ed1033c7c..274ff7b43 100644--- a/i18n/tr-TR.json+++ b/i18n/tr-TR.json@@ -812,7 +812,13 @@"importSectionHint": "GitHub deponuzdan mevcut sorunları talep olarak içe aktarın","importing": "İçe aktarılıyor...","importIssues": "Sorunları İçe Aktar",- "importDisabledHint": "İçe aktarmayı etkinleştirmek için yukarıdaki depo yapılandırmasını tamamlayın"+ "importDisabledHint": "İçe aktarmayı etkinleştirmek için yukarıdaki depo yapılandırmasını tamamlayın",+ "accountVerificationHint": "Bu depoyu yönettiğinizi doğrulamak için GitHub hesabınızı bağlayın.",+ "enableGithubSignInHint": "Örnek yöneticinizden GitHub ile oturum açmayı etkinleştirmesini isteyin.",+ "reverifyHint": "Erişimi doğrulamak ve eşitlemeyi sürdürmek için bu depoyu yeniden bağlayın.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1156,7 +1162,12 @@"project": "Projeler","task": "Talepler","label": "Etiketler",- "workspace": "Çalışma alanı"+ "workspace": "Çalışma alanı",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1238,6 +1249,72 @@"label": "Ayarları Yönetme","description": "Çalışma alanı ayarlarını yönetebilir"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1281,7 +1358,9 @@"createError": "Etiket oluşturulamadı","updateError": "Etiket güncellenemedi","deleteError": "Etiket silinemedi",- "nameRequired": "Etiket adı gereklidir"+ "nameRequired": "Etiket adı gereklidir",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1631,7 +1710,9 @@"mermaid": {"renderFailed": "Mermaid diyagramı oluşturulamadı"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1951,7 +2032,11 @@"resizeStart": "Başlangıç tarihini yeniden boyutlandır","resizeDue": "Bitiş tarihini yeniden boyutlandır","taskAriaLabel": "{{title}}: açmak veya taşımak için sürükleyin",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Talep Silinsin mi?",@@ -2063,7 +2148,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"pageTitle": "Davetler",diff --git a/i18n/uk-UA.json b/i18n/uk-UA.jsonindex 9eabd2326..22b844258 100644--- a/i18n/uk-UA.json+++ b/i18n/uk-UA.json@@ -812,7 +812,13 @@"importSectionHint": "Імпортуйте наявні issues з вашого GitHub-репозиторію як завдання","importing": "Імпорт...","importIssues": "Імпортувати Issues",- "importDisabledHint": "Завершіть налаштування репозиторію вище, щоб увімкнути імпорт"+ "importDisabledHint": "Завершіть налаштування репозиторію вище, щоб увімкнути імпорт",+ "accountVerificationHint": "Підключіть обліковий запис GitHub, щоб підтвердити права адміністратора цього репозиторію.",+ "enableGithubSignInHint": "Попросіть адміністратора вашого сервера ввімкнути вхід через GitHub.",+ "reverifyHint": "Підключіть репозиторій повторно, щоб підтвердити доступ і відновити синхронізацію.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1158,7 +1164,12 @@"project": "Проєкти","task": "Завдання","label": "Мітки",- "workspace": "Робочий простір"+ "workspace": "Робочий простір",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -1240,6 +1251,72 @@"label": "Керування налаштуваннями","description": "Може керувати налаштуваннями робочого простору"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -1283,7 +1360,9 @@"createError": "Не вдалося створити мітку","updateError": "Не вдалося оновити мітку","deleteError": "Не вдалося видалити мітку",- "nameRequired": "Назва мітки є обов'язковою"+ "nameRequired": "Назва мітки є обов'язковою",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"mattermostIntegration": {"channelHint": "Optional label for your reference. Mattermost controls the actual destination channel from the webhook setup.",@@ -1639,7 +1718,9 @@"mermaid": {"renderFailed": "Не вдалося відобразити діаграму Mermaid"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"},"moved": "перемістив завдання з «{{from}}» до «{{to}}»","created": "створив це завдання"@@ -1961,7 +2042,11 @@"resizeStart": "Змінити дату початку","resizeDue": "Змінити дату завершення","taskAriaLabel": "{{title}}: відкрити або перетягнути для переміщення",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Видалити завдання?",@@ -2075,7 +2160,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/vi-VN.json b/i18n/vi-VN.jsonindex 4f7c8bac9..68b86617b 100644--- a/i18n/vi-VN.json+++ b/i18n/vi-VN.json@@ -677,7 +677,12 @@"project": "Dự án","task": "Công việc","label": "Nhãn",- "workspace": "Không gian làm việc"+ "workspace": "Không gian làm việc",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -759,6 +764,72 @@"label": "Quản lý cài đặt","description": "Có thể quản lý cài đặt không gian làm việc"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -802,7 +873,9 @@"createError": "Không thể tạo nhãn","updateError": "Không thể cập nhật nhãn","deleteError": "Không thể xóa nhãn",- "nameRequired": "Cần có tên nhãn"+ "nameRequired": "Cần có tên nhãn",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"projectGeneral": {"pageTitle": "Cài đặt dự án",@@ -973,7 +1046,13 @@"importSectionHint": "Nhập các issue hiện có từ kho lưu trữ GitHub của bạn thành công việc","importing": "Đang nhập...","importIssues": "Nhập issue",- "importDisabledHint": "Hoàn tất cấu hình kho lưu trữ ở trên để bật tính năng nhập"+ "importDisabledHint": "Hoàn tất cấu hình kho lưu trữ ở trên để bật tính năng nhập",+ "accountVerificationHint": "Kết nối tài khoản GitHub để xác minh bạn có quyền quản trị kho lưu trữ này.",+ "enableGithubSignInHint": "Yêu cầu quản trị viên hệ thống bật đăng nhập bằng GitHub.",+ "reverifyHint": "Kết nối lại kho lưu trữ này để xác minh quyền truy cập và tiếp tục đồng bộ hóa.",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1626,7 +1705,9 @@"mermaid": {"renderFailed": "Mermaid diagram couldn't be rendered"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1946,7 +2027,11 @@"resizeStart": "Thay đổi kích thước ngày bắt đầu","resizeDue": "Thay đổi kích thước ngày đến hạn","taskAriaLabel": "{{title}}: mở hoặc kéo để di chuyển",- "jumpToToday": "Jump to today"+ "jumpToToday": "Jump to today",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "Xóa công việc?",@@ -2057,7 +2142,12 @@"title": "Calendar","today": "Today","loadError": "Failed to load tasks."- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/i18n/zh-CN.json b/i18n/zh-CN.jsonindex 11ac88111..b0c147c8a 100644--- a/i18n/zh-CN.json+++ b/i18n/zh-CN.json@@ -677,7 +677,12 @@"project": "项目","task": "任务","label": "标签",- "workspace": "工作区"+ "workspace": "工作区",+ "organization": "Workspace administration",+ "member": "Members",+ "invitation": "Invitations",+ "team": "Teams",+ "ac": "Roles and permissions"},"permissions": {"project": {@@ -759,6 +764,72 @@"label": "管理设置","description": "可以管理工作区设置"}+ },+ "organization": {+ "update": {+ "label": "Edit workspace administration",+ "description": "Change workspace settings through the account service."+ },+ "delete": {+ "label": "Delete workspace",+ "description": "Permanently delete the workspace through the account service."+ }+ },+ "member": {+ "create": {+ "label": "Add members",+ "description": "Add users to this workspace."+ },+ "update": {+ "label": "Change member roles",+ "description": "Change the roles assigned to workspace members."+ },+ "delete": {+ "label": "Remove members",+ "description": "Remove users from this workspace."+ }+ },+ "invitation": {+ "create": {+ "label": "Invite members",+ "description": "Send workspace invitations."+ },+ "cancel": {+ "label": "Cancel invitations",+ "description": "Revoke pending workspace invitations."+ }+ },+ "team": {+ "create": {+ "label": "Create teams",+ "description": "Create teams in this workspace."+ },+ "update": {+ "label": "Edit teams",+ "description": "Change teams and team membership."+ },+ "delete": {+ "label": "Delete teams",+ "description": "Delete teams in this workspace."+ }+ },+ "ac": {+ "create": {+ "label": "Create roles",+ "description": "Create workspace roles and assign their permissions."+ },+ "read": {+ "label": "View roles",+ "description": "Read the workspace roles and their permissions."+ },+ "update": {+ "label": "Change role permissions",+ "description": "Change role permissions, including administrative access."+ },+ "delete": {+ "label": "Delete roles",+ "description": "Delete custom workspace roles."+ }}},"validation": {@@ -802,7 +873,9 @@"createError": "创建标签失败","updateError": "更新标签失败","deleteError": "删除标签失败",- "nameRequired": "标签名称不能为空"+ "nameRequired": "标签名称不能为空",+ "deletionPending": "Deletion pending",+ "resumeDeletion": "Resume deletion"},"projectGeneral": {"pageTitle": "项目设置",@@ -973,7 +1046,13 @@"importSectionHint": "将 GitHub 仓库中已有的 Issue 导入为任务","importing": "导入中…","importIssues": "导入 Issues",- "importDisabledHint": "完成上方仓库配置后即可启用导入"+ "importDisabledHint": "完成上方仓库配置后即可启用导入",+ "accountVerificationHint": "连接你的 GitHub 账户,以验证你拥有此仓库的管理员权限。",+ "enableGithubSignInHint": "请联系实例管理员启用 GitHub 登录。",+ "reverifyHint": "重新连接此仓库,以验证访问权限并恢复同步。",+ "resumeImport": "Resume import",+ "importPaused": "This import has saved progress. You can resume it.",+ "importSummary": "Created: {{imported}} · Updated: {{updated}} · Skipped: {{skipped}}"},"giteaIntegration": {"validation": {@@ -1626,7 +1705,9 @@"mermaid": {"renderFailed": "Mermaid 图渲染失败"}- }+ },+ "importedFrom": "Imported from {{source}}",+ "importedBy": "Imported by {{name}}"}},"tasks": {@@ -1959,7 +2040,11 @@"updateDatesError": "更新任务日期失败","resizeStart": "调整开始日期","resizeDue": "调整截止日期",- "taskAriaLabel": "{{title}}:打开或拖动以移动"+ "taskAriaLabel": "{{title}}:打开或拖动以移动",+ "previousPeriod": "Previous period",+ "nextPeriod": "Next period",+ "periodStart": "Timeline start date",+ "showTaskDates": "Show task dates"},"delete": {"title": "删除任务?",@@ -2057,7 +2142,12 @@"deleteRow": "删除行","deleteTable": "删除表格"}- }+ },+ "descriptionSearchLoading": "Searching full descriptions…",+ "descriptionSearchError": "Description search failed. Results may be incomplete.",+ "descriptionRetry": "Retry",+ "descriptionLoading": "Loading description…",+ "descriptionLoadError": "The description could not be loaded. Retry to load the current version."},"invitations": {"email": {diff --git a/packages/email/src/index.tsx b/packages/email/src/index.tsxindex bcae63203..896f6a269 100644--- a/packages/email/src/index.tsx+++ b/packages/email/src/index.tsx@@ -1,3 +1,4 @@+export { OTP_EXPIRY_SECONDS } from "./otp-expiry";export {sendMagicLinkEmail,sendNotificationEmail,diff --git a/packages/email/src/otp-expiry.ts b/packages/email/src/otp-expiry.tsnew file mode 100644index 000000000..f627de044--- /dev/null+++ b/packages/email/src/otp-expiry.ts@@ -0,0 +1,2 @@+/** Shared by the authentication server and the email copy. */+export const OTP_EXPIRY_SECONDS = 5 * 60;diff --git a/packages/email/src/smtp-config.test.ts b/packages/email/src/smtp-config.test.tsindex d7e7fd765..e3bceef15 100644--- a/packages/email/src/smtp-config.test.ts+++ b/packages/email/src/smtp-config.test.ts@@ -46,16 +46,33 @@ describe("getSmtpTransportOptions", () => {expect(options.port).toBeUndefined();});- it("defaults to a secure connection and honours the TLS flags", () => {+ it("defaults to encrypted delivery and keeps certificate validation enabled", () => {expect(getSmtpTransportOptions({ SMTP_HOST: "h" }).secure).toBe(true);- expect(- getSmtpTransportOptions({ SMTP_HOST: "h", SMTP_REQUIRE_TLS: "true" })- .requireTLS,- ).toBe(true);- expect(- getSmtpTransportOptions({ SMTP_HOST: "h", SMTP_IGNORE_TLS: "true" })- .ignoreTLS,- ).toBe(true);+ const options = getSmtpTransportOptions({ SMTP_SECURE: "false" });+ expect(options.requireTLS).toBe(true);+ expect(options.ignoreTLS).toBe(false);+ expect(options.tls?.rejectUnauthorized).not.toBe(false);+ });++ it("rejects the formerly misleading flag instead of disabling STARTTLS", () => {+ for (const secure of ["true", "false"]) {+ expect(() =>+ getSmtpTransportOptions({+ SMTP_SECURE: secure,+ SMTP_IGNORE_TLS: "true",+ }),+ ).toThrow("SMTP_IGNORE_TLS=true is no longer supported");+ }+ });++ it("requires an explicit opt-out for relays without TLS", () => {+ const options = getSmtpTransportOptions({+ SMTP_SECURE: "false",+ SMTP_REQUIRE_TLS: "false",+ SMTP_IGNORE_TLS: "false",+ });+ expect(options.requireTLS).toBe(false);+ expect(options.ignoreTLS).toBe(false);});});diff --git a/packages/email/src/smtp-config.ts b/packages/email/src/smtp-config.tsindex dcb486917..6e64f290c 100644--- a/packages/email/src/smtp-config.ts+++ b/packages/email/src/smtp-config.ts@@ -14,11 +14,17 @@ type SmtpEnv = Record<string, string | undefined>;export function getSmtpTransportOptions(env: SmtpEnv = process.env,): SMTPTransport.Options {+ if (env.SMTP_IGNORE_TLS === "true") {+ throw new Error(+ "SMTP_IGNORE_TLS=true is no longer supported: it disables STARTTLS, not certificate validation. Remove it and trust your SMTP CA using NODE_EXTRA_CA_CERTS. For an intentionally unencrypted local relay, set SMTP_SECURE=false and SMTP_REQUIRE_TLS=false explicitly.",+ );+ }+const options: SMTPTransport.Options = {host: env.SMTP_HOST,secure: env.SMTP_SECURE !== "false",- requireTLS: env.SMTP_REQUIRE_TLS === "true",- ignoreTLS: env.SMTP_IGNORE_TLS === "true",+ requireTLS: env.SMTP_REQUIRE_TLS !== "false",+ ignoreTLS: false,};if (env.SMTP_PORT) {diff --git a/packages/email/src/smtp-transport.test.ts b/packages/email/src/smtp-transport.test.tsnew file mode 100644index 000000000..9cffa33ba--- /dev/null+++ b/packages/email/src/smtp-transport.test.ts@@ -0,0 +1,110 @@+import { once } from "node:events";+import { createServer, type Socket } from "node:net";+import * as nodemailer from "nodemailer";+import { describe, expect, it } from "vitest";+import { getSmtpTransportOptions } from "./smtp-config";++// A loopback-only SMTP sink: never forwards mail or connects to a real provider.+async function createPlaintextRelay() {+ const commands: string[] = [];+ const sockets = new Set<Socket>();+ const server = createServer((socket) => {+ sockets.add(socket);+ socket.on("close", () => sockets.delete(socket));+ socket.write("220 localhost test relay\r\n");+ let pending = "";+ let inData = false;+ socket.on("data", (chunk) => {+ pending += chunk.toString();+ let end = pending.indexOf("\r\n");+ while (end >= 0) {+ const line = pending.slice(0, end);+ pending = pending.slice(end + 2);+ if (inData) {+ if (line === ".") {+ inData = false;+ socket.write("250 accepted\r\n");+ }+ } else {+ commands.push(line);+ if (line.startsWith("EHLO")) {+ socket.write("250-localhost\r\n250 AUTH PLAIN\r\n");+ } else if (line === "STARTTLS") {+ socket.write("502 TLS unavailable\r\n");+ } else if (line.startsWith("AUTH")) {+ socket.write("235 authenticated\r\n");+ } else if (line === "DATA") {+ inData = true;+ socket.write("354 start mail\r\n");+ } else if (line === "QUIT") {+ socket.end("221 bye\r\n");+ } else {+ socket.write("250 OK\r\n");+ }+ }+ end = pending.indexOf("\r\n");+ }+ });+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("No relay port");+ return {+ commands,+ port: address.port,+ async close() {+ for (const socket of sockets) socket.destroy();+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ },+ };+}++describe("SMTP transport encryption", () => {+ it.each([false, true])(+ "only sends credentials and mail to a plaintext relay with explicit opt-out=%s",+ async (allowPlaintext) => {+ const relay = await createPlaintextRelay();+ const transport = nodemailer.createTransport({+ ...getSmtpTransportOptions({+ SMTP_HOST: "127.0.0.1",+ SMTP_PORT: String(relay.port),+ SMTP_SECURE: "false",+ SMTP_USER: "test-user",+ SMTP_PASSWORD: "test-password",+ ...(allowPlaintext ? { SMTP_REQUIRE_TLS: "false" } : {}),+ }),+ connectionTimeout: 1000,+ greetingTimeout: 1000,+ socketTimeout: 1000,+ });+ try {+ const result = transport.sendMail({+ from: "[email protected]",+ to: "[email protected]",+ text: "local test token",+ });+ if (allowPlaintext) {+ await expect(result).resolves.toMatchObject({+ accepted: ["[email protected]"],+ });+ expect(relay.commands.some((line) => line.startsWith("AUTH "))).toBe(+ true,+ );+ expect(relay.commands).toContain("DATA");+ } else {+ await expect(result).rejects.toMatchObject({ code: "ETLS" });+ expect(relay.commands).toContain("STARTTLS");+ expect(+ relay.commands.some((line) => /^(AUTH|MAIL|RCPT|DATA)/.test(line)),+ ).toBe(false);+ }+ } finally {+ transport.close();+ await relay.close();+ }+ },+ );+});diff --git a/packages/email/src/templates/otp.test.ts b/packages/email/src/templates/otp.test.tsindex 1fcb72531..b64044151 100644--- a/packages/email/src/templates/otp.test.ts+++ b/packages/email/src/templates/otp.test.ts@@ -1,6 +1,7 @@import { render } from "@react-email/render";import { createElement } from "react";import { describe, expect, it } from "vitest";+import { OTP_EXPIRY_SECONDS } from "../otp-expiry";import OtpEmail from "./otp";describe("OtpEmail", () => {@@ -10,6 +11,19 @@ describe("OtpEmail", () => {expect(html).toContain("verification code");});+ it.each([+ ["en-US", "This code expires in 5 minutes."],+ ["de-DE", "Dieser Code läuft in 5 Minuten ab."],+ ["vi-VN", "Mã này sẽ hết hạn sau 5 phút."],+ ["ja-JP", "このコードの有効期限は5分です。"],+ ])("describes the server expiry in %s", async (locale, expiry) => {+ expect(OTP_EXPIRY_SECONDS).toBe(300);+ const html = await render(+ createElement(OtpEmail, { otp: "123456", locale }),+ );+ expect(html).toContain(expiry);+ expect(html).not.toContain("15 minute");+ });it("renders Japanese copy for a Japanese locale", async () => {const html = await render(createElement(OtpEmail, { otp: "123456", locale: "ja-JP" }),diff --git a/packages/email/src/templates/otp.tsx b/packages/email/src/templates/otp.tsxindex cec02a1b8..acd79e03c 100644--- a/packages/email/src/templates/otp.tsx+++ b/packages/email/src/templates/otp.tsx@@ -1,5 +1,6 @@import { Section, Text } from "@react-email/components";import React from "react";+import { OTP_EXPIRY_SECONDS } from "../otp-expiry";import { resolveEmailLocale } from "./resolve-locale";import { EmailShell, styles } from "./shell";@@ -16,16 +17,16 @@ const messages = {title: "Your verification code",subtitle: "Enter this one-time code to finish signing in.",code: "is your Kaneo verification code.",- expiry: "This code expires in 15 minutes.",+ expiry: `This code expires in ${OTP_EXPIRY_SECONDS / 60} minutes.`,ignore: "If you didn't request this, you can ignore this email.",footer: "Kaneo security email",},de: {- preview: "Dein Kaneo Bestaetigungscode",- title: "Dein Bestaetigungscode",- subtitle: "Gib diesen Einmalcode ein, um die Anmeldung abzuschliessen.",- code: "ist dein Kaneo Bestaetigungscode.",- expiry: "Dieser Code laeuft in 15 Minuten ab.",+ preview: "Dein Kaneo Bestätigungscode",+ title: "Dein Bestätigungscode",+ subtitle: "Gib diesen Einmalcode ein, um die Anmeldung abzuschließen.",+ code: "ist dein Kaneo Bestätigungscode.",+ expiry: `Dieser Code läuft in ${OTP_EXPIRY_SECONDS / 60} Minuten ab.`,ignore:"Wenn du das nicht angefordert hast, kannst du diese E-Mail ignorieren.",footer: "Kaneo Sicherheits-E-Mail",@@ -35,7 +36,7 @@ const messages = {title: "Mã xác minh của bạn",subtitle: "Nhập mã dùng một lần này để hoàn tất đăng nhập.",code: "là mã xác minh Kaneo của bạn.",- expiry: "Mã này sẽ hết hạn sau 15 phút.",+ expiry: `Mã này sẽ hết hạn sau ${OTP_EXPIRY_SECONDS / 60} phút.`,ignore: "Nếu bạn không yêu cầu điều này, bạn có thể bỏ qua email này.",footer: "Email bảo mật Kaneo",},@@ -45,7 +46,7 @@ const messages = {subtitle:"サインインを完了するには、このワンタイムコードを入力してください。",code: "はあなたの Kaneo 確認コードです。",- expiry: "このコードの有効期限は15分です。",+ expiry: `このコードの有効期限は${OTP_EXPIRY_SECONDS / 60}分です。`,ignore: "心当たりがない場合は、このメールを無視してかまいません。",footer: "Kaneo セキュリティメール",},diff --git a/packages/mcp/src/tools/register.test.ts b/packages/mcp/src/tools/register.test.tsindex c63f1c051..369509e17 100644--- a/packages/mcp/src/tools/register.test.ts+++ b/packages/mcp/src/tools/register.test.ts@@ -61,11 +61,12 @@ describe("registerTools", () => {projectId: "project 1",status: "open",page: 2,+ relatedPage: 3,sortOrder: "desc",});expect(client.json).toHaveBeenCalledWith(- "/api/task/tasks/project%201?status=open&page=2&sortOrder=desc",+ "/api/task/tasks/project%201?status=open&page=2&relatedPage=3&sortOrder=desc",{ method: "GET" },);expect(result).toEqual({diff --git a/packages/mcp/src/tools/register.ts b/packages/mcp/src/tools/register.tsindex 3131b9331..bc8b58f9b 100644--- a/packages/mcp/src/tools/register.ts+++ b/packages/mcp/src/tools/register.ts@@ -190,8 +190,9 @@ export function registerTools(status: optionalNonEmptyString,priority: prioritySchema.optional(),assigneeId: optionalNonEmptyString,- page: z.number().int().positive().optional(),- limit: z.number().int().positive().optional(),+ page: z.number().int().min(1).max(1_000_000).optional(),+ relatedPage: z.number().int().min(1).max(1_000_000).optional(),+ limit: z.number().int().min(1).max(100).optional(),sortBy: z.enum(["createdAt", "priority", "dueDate", "position", "title", "number"]).optional(),@@ -203,7 +204,8 @@ export function registerTools(server.registerTool("list_tasks",{- description: "List tasks for a project (optionally filtered/sorted).",+ description:+ "List a bounded page of tasks for a project (50 by default, maximum 100). Use pagination.totalPages and page to retrieve the rest; filters and sorting apply before pagination. For every task page, also follow relatedPage through pagination.relatedTotalPages for complete labels, links and column metadata.",inputSchema: listTasksSchema,},async (args) => {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0e1f3e435..7c96edb5d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -12,7 +12,7 @@ overrides:esbuild: 0.28.1express-rate-limit: 8.2.2hono: '>=4.12.25'- lodash: 4.18.0+ lodash: 4.18.1markdown-it: 14.1.1minimatch: 10.2.3rollup: 4.59.0@@ -6689,8 +6689,8 @@ packages:resolution: {integrity: sha512-e/zcLx6CSbmaEgFHCA7BnoQKyCtKMxnuWrJygbwPs/AIn+IMKl66L8/s+wBUn5LRw2pZx3bUHibiV1b6aTWIww==}- resolution: {integrity: sha512-l1mfj2atMqndAHI3ls7XqPxEjV2J9ZkcNyHpoZA3r2T1LLwDB69jgkMWh71YKwhBbK0G2f4WSn05ahmQXVxupA==}+ resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}resolution: {integrity: sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==}@@ -9426,13 +9426,13 @@ snapshots:dependencies:'@chevrotain/gast': 10.5.0'@chevrotain/types': 10.5.0- lodash: 4.18.0+ lodash: 4.18.1optional: true'@chevrotain/[email protected]':dependencies:'@chevrotain/types': 10.5.0- lodash: 4.18.0+ lodash: 4.18.1optional: true'@chevrotain/[email protected]':@@ -11510,7 +11510,7 @@ snapshots:'@semantic-release/error': 3.0.0aggregate-error: 3.1.0fs-extra: 11.3.3- lodash: 4.18.0+ lodash: 4.18.1semantic-release: 24.2.9([email protected])@@ -11550,7 +11550,7 @@ snapshots:debug: 4.4.3dir-glob: 3.0.1execa: 5.1.1- lodash: 4.18.0+ lodash: 4.18.1micromatch: 4.0.8p-reduce: 2.1.0semantic-release: 24.2.9([email protected])@@ -13047,7 +13047,7 @@ snapshots:'@chevrotain/gast': 10.5.0'@chevrotain/types': 10.5.0'@chevrotain/utils': 10.5.0- lodash: 4.18.0+ lodash: 4.18.1regexp-to-ast: 0.5.0optional: true@@ -14645,7 +14645,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}dependencies:diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 82d1f3402..05c49e4b2 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -9,7 +9,7 @@ overrides:esbuild: 0.28.1express-rate-limit: 8.2.2hono: '>=4.12.25'- lodash: 4.18.0+ lodash: 4.18.1markdown-it: 14.1.1minimatch: 10.2.3rollup: 4.59.0diff --git a/scripts/release/apply-version.mjs b/scripts/release/apply-version.mjsindex b69e4051c..a1d6be629 100644--- a/scripts/release/apply-version.mjs+++ b/scripts/release/apply-version.mjs@@ -7,7 +7,9 @@ import { fileURLToPath } from "node:url";const version = process.argv[2] ?? "";-if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {+const versionPattern =+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?$/;+if (version.length > 128 || versionPattern.exec(version)?.[0] !== version) {console.error(`apply-version: expected a semver version, received ${JSON.stringify(version)}`,);diff --git a/scripts/release/emit-version.mjs b/scripts/release/emit-version.mjsindex 202bd3242..10bbc6db9 100644--- a/scripts/release/emit-version.mjs+++ b/scripts/release/emit-version.mjs@@ -1,8 +1,19 @@#!/usr/bin/env node+import { execFileSync } from "node:child_process";// Runs in semantic-release's verifyRelease step, which a dry run still executes.import { appendFileSync } from "node:fs";const version = process.argv[2] ?? "";+execFileSync(+ process.execPath,+ ["scripts/security/validate-release-version.mjs", version, "--new-version"],+ { stdio: "inherit" },+);+if (process.env.PLANNED_VERSION && process.env.PLANNED_VERSION !== version) {+ throw new Error(+ "Release version changed after image planning; refusing to create a mismatched release",+ );+}console.log(`Next release version: ${version}`);diff --git a/scripts/security/check-helm-secrets.rb b/scripts/security/check-helm-secrets.rbnew file mode 100644index 000000000..da5042709--- /dev/null+++ b/scripts/security/check-helm-secrets.rb@@ -0,0 +1,56 @@+require 'yaml'+require 'open3'++def render(*args)+ stdout, stderr, status = Open3.capture3('helm', 'template', 'security-test', 'charts/kaneo', *args)+ raise stderr unless status.success?+ YAML.load_stream(stdout).compact+end++def verify(condition, message)+ raise message unless condition+end++def app_env(docs)+ deployment = docs.find { |d| d['kind'] == 'Deployment' && !d['metadata']['name'].end_with?('-postgresql') }+ deployment.fetch('spec').fetch('template').fetch('spec').fetch('containers').first.fetch('env')+end++secret = 'test-auth-secret-at-least-32-characters'+args = ['--set', "kaneo.env.authSecret=#{secret}", '--set', 'kaneo.env.clientUrl=https://kaneo.example.com']+first = render(*args)+second = render(*args, '--is-upgrade')+[first, second].each do |docs|+ env = app_env(docs).find { |e| e['name'] == 'AUTH_SECRET' }+ verify(!env.key?('value'), 'AUTH_SECRET must not be a literal in the Deployment')+ ref = env.fetch('valueFrom').fetch('secretKeyRef')+ resource = docs.find { |d| d['kind'] == 'Secret' && d['metadata']['name'] == ref['name'] }+ verify(resource.fetch('stringData').fetch(ref['key']) == secret, 'Secret value must be preserved on install and upgrade')+ docs.select { |d| d['kind'] == 'Deployment' }.each do |deployment|+ verify(!deployment.to_s.include?(secret), 'Secret material leaked into a Deployment')+ end+end++external = render('--set', 'kaneo.env.clientUrl=https://kaneo.example.com', '--set', 'kaneo.env.existingSecret.enabled=true', '--set', 'kaneo.env.existingSecret.name=operator-secret')+ref = app_env(external).find { |e| e['name'] == 'AUTH_SECRET' }.fetch('valueFrom').fetch('secretKeyRef')+verify(ref == { 'name' => 'operator-secret', 'key' => 'auth-secret' }, 'Existing secret reference changed')+verify(external.none? { |d| d['kind'] == 'Secret' && d['metadata']['name'].end_with?('-auth') }, 'Existing secret must not be overwritten')+_, _, status = Open3.capture3('helm', 'template', 'security-test', 'charts/kaneo', '--set', 'kaneo.env.existingSecret.enabled=true')+verify(!status.success?, 'Missing external secret name must reject the configuration')++secured = render(*args, '--set', 'podSecurityContext.runAsNonRoot=true', '--set', 'podSecurityContext.seccompProfile.type=RuntimeDefault')+deployment = secured.find { |d| d['kind'] == 'Deployment' && !d['metadata']['name'].end_with?('-postgresql') }+context = deployment['spec']['template']['spec']['securityContext']+verify(context['runAsNonRoot'] && context.dig('seccompProfile', 'type') == 'RuntimeDefault', 'Documented pod security settings are not applied')+puts 'Helm secret, upgrade, external-secret validation and pod security checks passed'++['', ' ', 'ftp://example.com', 'https://user:[email protected]', 'https://example.com/path', 'https://example.com?x=1', 'https://example.com#fragment'].each do |url|+ _, stderr, status = Open3.capture3('helm', 'template', 'security-test', 'charts/kaneo', '--set', "kaneo.env.authSecret=#{secret}", '--set-string', "kaneo.env.clientUrl=#{url}")+ verify(!status.success? && stderr.include?('kaneo.env.clientUrl'), "Invalid clientUrl must produce an actionable error: #{url.inspect}")+end+['https://kaneo.example.com', 'http://localhost:8080', 'http://[::1]:8080/', ' https://kaneo.example.com/ '].each do |url|+ docs = render(*args, '--set-string', "kaneo.env.clientUrl=#{url}")+ client = app_env(docs).find { |env| env['name'] == 'KANEO_CLIENT_URL' }+ verify(client['value'] == url.strip.sub(%r{/$}, ''), 'Public origin must be trimmed and safe for API URL derivation')+end+puts 'Helm required-origin validation and URL rendering checks passed'diff --git a/scripts/security/deployment.test.mjs b/scripts/security/deployment.test.mjsnew file mode 100644index 000000000..81dde07f6--- /dev/null+++ b/scripts/security/deployment.test.mjs@@ -0,0 +1,75 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { test } from "node:test";++const root = path.resolve(import.meta.dirname, "../..");+const entrypoint = readFileSync(+ path.join(root, "deploy/kaneo-entrypoint.sh"),+ "utf8",+);+const encoder = entrypoint.slice(+ entrypoint.indexOf("urlencode()"),+ entrypoint.indexOf('api_pid=""'),+);+for (const value of [+ "-password",+ "--require=bad",+ "-p",+ "space &/#%!'",+ "äöü",+]) {+ test(`database credentials preserve ${JSON.stringify(value)}`, () => {+ const result = spawnSync(+ "sh",+ ["-c", `${encoder}\nurlencode "$1"`, "test", value],+ { encoding: "utf8" },+ );+ assert.equal(result.status, 0, result.stderr);+ assert.equal(decodeURIComponent(result.stdout), value);+ });+}++test("minimal Compose configuration uses matching DB defaults without a published DB port", () => {+ const dir = mkdtempSync(path.join(tmpdir(), "kaneo-compose-test-"));+ try {+ writeFileSync(+ path.join(dir, "compose.yml"),+ readFileSync(path.join(root, "compose.yml")),+ );+ writeFileSync(+ path.join(dir, ".env"),+ "KANEO_CLIENT_URL=http://localhost:5173\nPOSTGRES_PASSWORD=test-password\nAUTH_SECRET=test-secret-at-least-thirty-two-characters\n",+ );+ const result = spawnSync(+ "docker",+ [+ "compose",+ "--env-file",+ path.join(dir, ".env"),+ "-f",+ path.join(dir, "compose.yml"),+ "config",+ "--format",+ "json",+ ],+ {+ encoding: "utf8",+ env: {+ PATH: "/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin",+ HOME: process.env.HOME,+ },+ },+ );+ assert.equal(result.status, 0, result.stderr);+ const config = JSON.parse(result.stdout);+ assert.equal(config.services.postgres.environment.POSTGRES_USER, "kaneo");+ assert.equal(config.services.postgres.environment.POSTGRES_DB, "kaneo");+ assert.equal(config.services.postgres.ports, undefined);+ assert.match(config.services.postgres.healthcheck.test[1], /POSTGRES_USER/);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/scripts/security/release-inputs.test.mjs b/scripts/security/release-inputs.test.mjsnew file mode 100644index 000000000..dd61944f2--- /dev/null+++ b/scripts/security/release-inputs.test.mjs@@ -0,0 +1,77 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { resolve } from "node:path";+import test from "node:test";++const root = resolve(import.meta.dirname, "../..");+const workflow = readFileSync(+ resolve(root, ".github/workflows/build-images.yml"),+ "utf8",+);+const command = workflow.match(+ /run: (node scripts\/release\/apply-version\.mjs[^\n]*)/,+)[1];++for (const version of [+ "1.2.3",+ "$(touch injected)1.2.3",+ "`touch injected`1.2.3",+ '1.2.3"; touch injected; #',+ "1.2.3\nOTHER=value",+ "1.2.3\n",+ "01.2.3",+ "1.2.3-01",+ "1.2.3-",+ "1.2.3-rc.1",+]) {+ test(`image stamp treats ${JSON.stringify(version)} as data`, () => {+ const fixture = mkdtempSync(resolve(tmpdir(), "kaneo-release-input-"));+ try {+ mkdirSync(resolve(fixture, "scripts/release"), { recursive: true });+ mkdirSync(resolve(fixture, "charts/kaneo"), { recursive: true });+ copyFileSync(+ resolve(root, "scripts/release/apply-version.mjs"),+ resolve(fixture, "scripts/release/apply-version.mjs"),+ );+ const originalPackage = '{\n "version": "0.0.0"\n}\n';+ const originalChart = 'version: 0.0.0\nappVersion: "0.0.0"\n';+ writeFileSync(resolve(fixture, "package.json"), originalPackage);+ writeFileSync(resolve(fixture, "charts/kaneo/Chart.yaml"), originalChart);+ const result = spawnSync("sh", ["-c", command], {+ cwd: fixture,+ env: { ...process.env, RELEASE_VERSION: version },+ encoding: "utf8",+ });+ assert.equal(existsSync(resolve(fixture, "injected")), false);+ if (["1.2.3", "1.2.3-rc.1"].includes(version)) {+ assert.equal(result.status, 0, result.stderr);+ assert.equal(+ JSON.parse(readFileSync(resolve(fixture, "package.json"))).version,+ version,+ );+ } else {+ assert.notEqual(result.status, 0);+ assert.equal(+ readFileSync(resolve(fixture, "package.json"), "utf8"),+ originalPackage,+ );+ assert.equal(+ readFileSync(resolve(fixture, "charts/kaneo/Chart.yaml"), "utf8"),+ originalChart,+ );+ }+ } finally {+ rmSync(fixture, { recursive: true, force: true });+ }+ });+}diff --git a/scripts/security/release-source.test.mjs b/scripts/security/release-source.test.mjsnew file mode 100644index 000000000..c356cfd2e--- /dev/null+++ b/scripts/security/release-source.test.mjs@@ -0,0 +1,208 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { resolve } from "node:path";+import test from "node:test";++const root = resolve(import.meta.dirname, "../..");+function fixture(run) {+ const dir = mkdtempSync(resolve(tmpdir(), "kaneo-source-test-"));+ const git = (...args) => {+ const result = spawnSync(+ "git",+ [+ "-c",+ "user.name=Test",+ "-c",+ "[email protected]",+ "-c",+ "commit.gpgsign=false",+ "-c",+ "core.hooksPath=/dev/null",+ ...args,+ ],+ { cwd: dir, encoding: "utf8" },+ );+ assert.equal(result.status, 0, result.stderr);+ return result.stdout.trim();+ };+ const versions = (pkg = "1.2.3", chart = pkg) => {+ writeFileSync(+ resolve(dir, "package.json"),+ JSON.stringify({ version: pkg, type: "module" }),+ );+ writeFileSync(+ resolve(dir, "charts/kaneo/Chart.yaml"),+ `name: kaneo\nversion: ${chart}\nappVersion: "${pkg}"\n`,+ );+ };+ const commit = () => {+ git("add", ".");+ git("commit", "--allow-empty", "-m", "fixture");+ return git("rev-parse", "HEAD");+ };+ try {+ mkdirSync(resolve(dir, "charts/kaneo"), { recursive: true });+ mkdirSync(resolve(dir, "scripts/security"), { recursive: true });+ mkdirSync(resolve(dir, "scripts/release"), { recursive: true });+ for (const file of [+ "scripts/security/verify-release-source.mjs",+ "scripts/security/validate-release-version.mjs",+ "scripts/release/emit-version.mjs",+ ])+ copyFileSync(resolve(root, file), resolve(dir, file));+ versions();+ git("init", "-b", "main");+ const first = commit();+ git("update-ref", "refs/remotes/origin/main", first);+ const verify = (mode, version, extra = {}) => {+ const output = resolve(dir, "output");+ rmSync(output, { force: true });+ const result = spawnSync(+ process.execPath,+ ["scripts/security/verify-release-source.mjs", mode, version],+ {+ cwd: dir,+ encoding: "utf8",+ env: {+ PATH: process.env.PATH,+ GITHUB_REF: "refs/heads/main",+ GITHUB_SHA: git("rev-parse", "HEAD"),+ GITHUB_OUTPUT: output,+ ...extra,+ },+ },+ );+ return {+ ...result,+ output: existsSync(output) ? readFileSync(output, "utf8") : "",+ };+ };+ run({ dir, git, commit, first, versions, verify });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++test("an existing release resolves its reviewed tag, not newer main", () =>+ fixture(({ git, first, commit, versions, verify }) => {+ git("tag", "v1.2.3");+ versions("1.2.4");+ const latest = commit();+ git("update-ref", "refs/remotes/origin/main", latest);+ const result = verify("released", "1.2.3");+ assert.equal(result.status, 0, result.stderr);+ assert.equal(result.output, `source_sha=${first}\n`);+ }));+test("tags outside reviewed main history cannot publish", () =>+ fixture(({ git, commit, verify }) => {+ git("checkout", "-b", "unreviewed");+ commit();+ git("tag", "v1.2.3");+ git("checkout", "main");+ assert.notEqual(verify("released", "1.2.3").status, 0);+ }));+test("a nonexistent tag cannot be manufactured by version stamping", () =>+ fixture(({ verify }) => {+ assert.notEqual(verify("released", "1.2.3").status, 0);+ }));+test("tag and package version must match", () =>+ fixture(({ git, verify }) => {+ git("tag", "v9.0.0");+ assert.notEqual(verify("released", "9.0.0").status, 0);+ }));+test("tag and chart version must match", () =>+ fixture(({ git, commit, versions, verify }) => {+ versions("1.2.3", "9.0.0");+ const sha = commit();+ git("update-ref", "refs/remotes/origin/main", sha);+ git("tag", "v1.2.3");+ assert.notEqual(verify("released", "1.2.3").status, 0);+ }));+test("publication requires a main workflow and the exact workflow checkout", () =>+ fixture(({ first, verify }) => {+ assert.notEqual(+ verify("planned", "1.2.4", { GITHUB_REF: "refs/heads/unreviewed" })+ .status,+ 0,+ );+ assert.notEqual(+ verify("planned", "1.2.4", { GITHUB_SHA: "0".repeat(40) }).status,+ 0,+ );+ assert.equal(verify("planned", "1.2.4", { GITHUB_SHA: first }).status, 0);+ }));+test("planned release cannot silently follow a moving main branch", () =>+ fixture(({ first, git, commit, verify }) => {+ const latest = commit();+ git("update-ref", "refs/remotes/origin/main", latest);+ git("checkout", "--detach", first);+ assert.notEqual(verify("planned", "1.2.4").status, 0);+ }));+test("planned release refuses an existing version tag", () =>+ fixture(({ git, verify }) => {+ git("tag", "v1.2.4");+ assert.notEqual(verify("planned", "1.2.4").status, 0);+ }));+test("a new planned release and unversioned nightly retain the workflow SHA", () =>+ fixture(({ first, verify }) => {+ for (const [mode, version] of [+ ["planned", "1.2.4"],+ ["nightly", ""],+ ]) {+ const result = verify(mode, version);+ assert.equal(result.status, 0, result.stderr);+ assert.equal(result.output, `source_sha=${first}\n`);+ }+ assert.notEqual(verify("nightly", "1.2.3").status, 0);+ assert.notEqual(verify("unknown", "1.2.3").status, 0);+ }));+test("malformed release inputs cannot execute code or produce workflow outputs", () =>+ fixture(({ dir, verify }) => {+ for (const version of [+ "1.2.3\nSOURCE=bad",+ "$(touch injected)",+ "1.2.3\n",+ "--help",+ ]) {+ const result = verify("released", version);+ assert.notEqual(result.status, 0);+ assert.equal(result.output, "");+ assert.equal(existsSync(resolve(dir, "injected")), false);+ }+ }));+test("semantic-release rejects version drift at verifyRelease before emitting output", () =>+ fixture(({ dir }) => {+ for (const version of ["1.2.4", "1.2.5"]) {+ const output = resolve(dir, `verify-${version}`);+ const result = spawnSync(+ process.execPath,+ ["scripts/release/emit-version.mjs", version],+ {+ cwd: dir,+ encoding: "utf8",+ env: {+ PATH: process.env.PATH,+ PLANNED_VERSION: "1.2.4",+ GITHUB_OUTPUT: output,+ },+ },+ );+ if (version === "1.2.4") {+ assert.equal(result.status, 0, result.stderr);+ assert.equal(readFileSync(output, "utf8"), "version=1.2.4\n");+ } else {+ assert.notEqual(result.status, 0);+ assert.equal(existsSync(output), false);+ }+ }+ }));diff --git a/scripts/security/source-maps.test.mjs b/scripts/security/source-maps.test.mjsnew file mode 100644index 000000000..94622d59c--- /dev/null+++ b/scripts/security/source-maps.test.mjs@@ -0,0 +1,87 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import {+ chmodSync,+ copyFileSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { resolve } from "node:path";+import test from "node:test";++const root = resolve(import.meta.dirname, "../..");+for (const config of ["nginx.conf", "nginx.kaneo.conf"]) {+ test(`${config} refuses existing source maps and still serves the application`, () => {+ const fixture = mkdtempSync(resolve(tmpdir(), "kaneo-map-test-"));+ try {+ chmodSync(fixture, 0o777);+ mkdirSync(resolve(fixture, "assets"));+ writeFileSync(+ resolve(fixture, "assets/app.js"),+ "globalThis.ready = true;",+ );+ writeFileSync(+ resolve(fixture, "assets/app.js.map"),+ '{"sourcesContent":["private-source-marker"]}',+ );+ writeFileSync(+ resolve(fixture, "assets/app.JS.MAP"),+ '{"sourcesContent":["private-source-marker"]}',+ );+ writeFileSync(resolve(fixture, "index.html"), "application-shell");+ copyFileSync(+ resolve(root, "apps/web", config),+ resolve(fixture, "server.conf"),+ );+ writeFileSync(+ resolve(fixture, "nginx.conf"),+ "pid /tmp/nginx.pid; error_log /tmp/nginx-error.log; events {} http { access_log off; client_body_temp_path /tmp/client; proxy_temp_path /tmp/proxy; fastcgi_temp_path /tmp/fastcgi; uwsgi_temp_path /tmp/uwsgi; scgi_temp_path /tmp/scgi; include /usr/share/nginx/html/server.conf; }",+ );+ const result = spawnSync(+ "docker",+ [+ "run",+ "--rm",+ "--pull=never",+ "--network=none",+ "--user=1001:1001",+ "--mount",+ `type=bind,source=${fixture},target=/usr/share/nginx/html`,+ "--entrypoint",+ "sh",+ "nginx:1.29.5-alpine",+ "-eu",+ "-c",+ `+nginx -t -c /usr/share/nginx/html/nginx.conf+nginx -c /usr/share/nginx/html/nginx.conf+trap 'nginx -s quit -c /usr/share/nginx/html/nginx.conf' EXIT+for path in assets/app.js.map assets/app.JS.MAP assets/app.js%2emap; do+ if wget -S -O /tmp/map-body "http://127.0.0.1:5173/$path" 2>/tmp/map-headers; then exit 1; fi+ grep -q '404 Not Found' /tmp/map-headers+ if grep -q private-source-marker /tmp/map-body; then exit 1; fi+done+wget -qO /usr/share/nginx/html/js-response http://127.0.0.1:5173/assets/app.js+wget -qO /usr/share/nginx/html/page-response http://127.0.0.1:5173/dashboard+`,+ ],+ { encoding: "utf8", timeout: 30_000 },+ );+ assert.equal(result.status, 0, result.stderr);+ assert.equal(+ readFileSync(resolve(fixture, "js-response"), "utf8"),+ "globalThis.ready = true;",+ );+ assert.equal(+ readFileSync(resolve(fixture, "page-response"), "utf8"),+ "application-shell",+ );+ } finally {+ rmSync(fixture, { recursive: true, force: true });+ }+ });+}diff --git a/scripts/security/validate-release-version.mjs b/scripts/security/validate-release-version.mjsnew file mode 100644index 000000000..5328fd323--- /dev/null+++ b/scripts/security/validate-release-version.mjs@@ -0,0 +1,15 @@+import { readFileSync } from "node:fs";++const version = process.argv[2];+const expected = JSON.parse(readFileSync("package.json", "utf8")).version;+// Only a single SemVer value is accepted, before any output-file or shell use.+const semver =+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;+if (!version || version.length > 128 || semver.exec(version)?.[0] !== version) {+ throw new Error("Release version must be a single valid SemVer value");+}+if (process.argv[3] !== "--new-version" && version !== expected) {+ throw new Error(+ "Release version must match package.json in the checked-out commit",+ );+}diff --git a/scripts/security/verify-release-source.mjs b/scripts/security/verify-release-source.mjsnew file mode 100644index 000000000..aed79fd84--- /dev/null+++ b/scripts/security/verify-release-source.mjs@@ -0,0 +1,74 @@+// biome-ignore-all lint/suspicious/noUndeclaredEnvVars: GitHub Actions invokes this guard directly, outside Turbo's cache.+import { execFileSync } from "node:child_process";+import { appendFileSync } from "node:fs";++// Run from the workflow's main-branch checkout BEFORE checking out a release+// tag. Never execute verification code taken from an unverified tag.+const [mode, version = ""] = process.argv.slice(2);+const git = (...args) =>+ execFileSync("git", args, {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "pipe"],+ }).trim();+const source = process.env.GITHUB_SHA;+if (+ process.env.GITHUB_REF !== "refs/heads/main" ||+ !/^[0-9a-f]{40}$/.test(source ?? "")+) {+ throw new Error(+ "Publication must use a main-branch workflow with a full source SHA",+ );+}+if (git("rev-parse", "HEAD") !== source)+ throw new Error("Checkout does not match the workflow source");+git("merge-base", "--is-ancestor", source, "refs/remotes/origin/main");++let approved = source;+if (mode === "nightly") {+ if (version !== "")+ throw new Error("Nightly builds cannot claim a release version");+} else if (mode === "planned" || mode === "released") {+ execFileSync(+ process.execPath,+ ["scripts/security/validate-release-version.mjs", version, "--new-version"],+ { stdio: "inherit" },+ );+ const tag = `refs/tags/v${version}`;+ if (mode === "planned") {+ if (git("rev-parse", "refs/remotes/origin/main") !== source) {+ throw new Error(+ "Main advanced since release planning; start a new release run",+ );+ }+ let exists = false;+ try {+ git("rev-parse", "--verify", tag);+ exists = true;+ } catch {}+ if (exists) throw new Error("The planned release tag already exists");+ } else {+ approved = git("rev-parse", "--verify", `${tag}^{commit}`);+ git("merge-base", "--is-ancestor", approved, "refs/remotes/origin/main");+ const pkg = JSON.parse(git("show", `${approved}:package.json`));+ const chart = git("show", `${approved}:charts/kaneo/Chart.yaml`);+ const field = (name) =>+ chart.match(+ new RegExp(`^${name}:\\s*["']?([^\\s"']+)["']?\\s*$`, "m"),+ )?.[1];+ if (+ pkg.version !== version ||+ field("version") !== version ||+ field("appVersion") !== version+ ) {+ throw new Error(+ "Release tag, package version and Helm chart versions must agree",+ );+ }+ }+} else {+ throw new Error("Unknown publication source mode");+}++if (process.env.GITHUB_OUTPUT)+ appendFileSync(process.env.GITHUB_OUTPUT, `source_sha=${approved}\n`);+console.log(`Verified ${mode} publication source: ${approved}`);diff --git a/scripts/security/web-runtime-env.test.mjs b/scripts/security/web-runtime-env.test.mjsnew file mode 100644index 000000000..6ecf5b6ce--- /dev/null+++ b/scripts/security/web-runtime-env.test.mjs@@ -0,0 +1,137 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import {+ chmodSync,+ copyFileSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { resolve } from "node:path";+import test from "node:test";+import { runInNewContext } from "node:vm";++const root = resolve(import.meta.dirname, "../..");+// Uses the production standalone-web runtime, without networking or published ports.+// Pull this public image explicitly before running the test; never pull implicitly.+const image = "nginx:1.29.5-alpine";+const scenarios = [+ {+ name: "ordinary URLs",+ api: "https://api.example.test/api/",+ client: "https://app.example.test",+ key: "site-key",+ },+ {+ name: "literal punctuation, control characters, UTF-8, and placeholder-like data",+ api: 'https://api.example.test/a&b/$host/"quoted"/\\path/api#fragment',+ client:+ // biome-ignore lint/suspicious/noTemplateCurlyInString: Must remain literal hostile configuration data.+ "https://app.example.test/#'\"` ${globalThis.injected = true} & \\ \n\r\t\u0001\u001f Grüße 😀 \u2028\u2029",+ key: 'KANEO_CLIENT_URL ";globalThis.injected=true;//',+ },+ { name: "unset public values", api: "", client: "", key: "" },+];++for (const scenario of scenarios) {+ test(scenario.name, () => {+ const fixture = mkdtempSync(resolve(tmpdir(), "kaneo-web-env-"));+ try {+ chmodSync(fixture, 0o777);+ const asset = resolve(fixture, "app with spaces\nand newline.js");+ writeFileSync(+ asset,+ 'globalThis.config = {api:"KANEO_API_URL",client:\'KANEO_CLIENT_URL\',callback:`KANEO_CLIENT_URL/auth/sign-in`,key:`KANEO_TURNSTILE_SITE_KEY`,private:"KANEO_SERVER_SECRET"};\n',+ );+ copyFileSync(+ resolve(root, "apps/web/nginx.conf"),+ resolve(fixture, "server.conf"),+ );+ writeFileSync(+ resolve(fixture, "nginx.conf"),+ "pid /tmp/nginx.pid;\nerror_log /tmp/nginx-error.log;\nevents {}\nhttp { access_log off; client_body_temp_path /tmp/client; proxy_temp_path /tmp/proxy; fastcgi_temp_path /tmp/fastcgi; uwsgi_temp_path /tmp/uwsgi; scgi_temp_path /tmp/scgi; include /usr/share/nginx/html/server.conf; }\n",+ );+ const result = spawnSync(+ "docker",+ [+ "run",+ "--rm",+ "--pull=never",+ "--network=none",+ "--user=1001:1001",+ "--mount",+ `type=bind,source=${fixture},target=/usr/share/nginx/html`,+ "--mount",+ `type=bind,source=${resolve(root, "apps/web")},target=/renderer,readonly`,+ "--env",+ "KANEO_API_URL",+ "--env",+ "KANEO_CLIENT_URL",+ "--env",+ "KANEO_TURNSTILE_SITE_KEY",+ "--env",+ "KANEO_SERVER_SECRET",+ "--entrypoint",+ "sh",+ image,+ "-eu",+ "-c",+ "sh /renderer/env.sh; nginx -t -c /usr/share/nginx/html/nginx.conf; nginx -c /usr/share/nginx/html/nginx.conf; wget -qO /usr/share/nginx/html/resource-response.json http://127.0.0.1:5173/.well-known/oauth-protected-resource/api/mcp; wget -qO /usr/share/nginx/html/authorization-response.json http://127.0.0.1:5173/.well-known/oauth-authorization-server/api; nginx -s quit -c /usr/share/nginx/html/nginx.conf",+ ],+ {+ encoding: "utf8",+ timeout: 30_000,+ env: {+ ...process.env,+ KANEO_API_URL: scenario.api,+ KANEO_CLIENT_URL: scenario.client,+ KANEO_TURNSTILE_SITE_KEY: scenario.key,+ KANEO_SERVER_SECRET: "must-not-be-published",+ },+ },+ );+ assert.equal(result.status, 0, result.stderr);+ const source = readFileSync(asset, "utf8");+ const context = {};+ runInNewContext(source, context);+ assert.equal(context.config.api, scenario.api);+ assert.equal(context.config.client, scenario.client);+ assert.equal(context.config.callback, `${scenario.client}/auth/sign-in`);+ assert.equal(context.config.key, scenario.key);+ assert.equal(context.config.private, "KANEO_SERVER_SECRET");+ assert.equal(context.injected, undefined);+ assert.ok(!source.includes("must-not-be-published"));+ assert.ok(!result.stdout.includes("site-key"));+ const resource = JSON.parse(+ readFileSync(resolve(fixture, "resource-response.json"), "utf8"),+ );+ const authorization = JSON.parse(+ readFileSync(resolve(fixture, "authorization-response.json"), "utf8"),+ );+ if (!scenario.api) {+ assert.deepEqual(resource, {});+ assert.deepEqual(authorization, {});+ } else {+ const base = scenario.api+ .replace(/[?#].*$/, "")+ .replace(/\/*$/, "")+ .replace(/\/api$/, "");+ assert.equal(resource.resource, `${base}/api/mcp`);+ assert.deepEqual(resource.authorization_servers, [`${base}/api`]);+ assert.equal(authorization.issuer, `${base}/api`);+ assert.equal(+ authorization.registration_endpoint,+ `${base}/api/mcp/register`,+ );+ }+ assert.equal(+ readFileSync(resolve(fixture, "server.conf"), "utf8"),+ readFileSync(resolve(root, "apps/web/nginx.conf"), "utf8"),+ );+ } finally {+ rmSync(fixture, { recursive: true, force: true });+ }+ });+}diff --git a/scripts/security/workflows.test.mjs b/scripts/security/workflows.test.mjsnew file mode 100644index 000000000..c9155b721--- /dev/null+++ b/scripts/security/workflows.test.mjs@@ -0,0 +1,260 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { test } from "node:test";++const root = path.resolve(import.meta.dirname, "../..");+function runBlock(file, step) {+ const source = readFileSync(+ path.join(root, ".github/workflows", file),+ "utf8",+ );+ const lines = source.slice(source.indexOf(`- name: ${step}`)).split("\n");+ const start = lines.findIndex((line) => line.trim() === "run: |");+ assert.ok(start >= 0);+ const result = [];+ for (const line of lines.slice(start + 1)) {+ if (line.trim() && !line.startsWith(" ")) break;+ result.push(line.slice(10));+ }+ return result.join("\n");+}++const mergeScript = runBlock(+ "auto-merge.yml",+ "Merge eligible npm updates after required checks pass",+);++test("issue notifications preserve untrusted text without Discord mentions", () => {+ const dir = mkdtempSync(path.join(tmpdir(), "kaneo-notification-test-"));+ try {+ const captured = path.join(dir, "payload.json");+ const marker = path.join(dir, "injected");+ writeFileSync(+ path.join(dir, "curl"),+ '#!/bin/sh\nset -eu\nwhile [ "$#" -gt 0 ]; do\n if [ "$1" = "-d" ]; then shift; printf "%s" "$1" > "$CAPTURED_PAYLOAD"; fi\n shift\ndone\n',+ { mode: 0o700 },+ );+ const title = `@everyone @here <@12345> <@&67890> "quote"\n$(touch '${marker}')`;+ const result = spawnSync(+ "bash",+ ["-c", runBlock("issue-notify.yml", "Post to Discord")],+ {+ env: {+ PATH: `${dir}:/usr/bin:/bin:/opt/homebrew/bin`,+ CAPTURED_PAYLOAD: captured,+ ISSUE_TITLE: title,+ ISSUE_URL: "https://example.invalid/issues/12",+ ISSUE_NUMBER: "12",+ AUTHOR: "untrusted-author",+ WEBHOOK: "https://example.invalid/never-called",+ },+ encoding: "utf8",+ },+ );+ assert.equal(result.status, 0, result.stderr);+ const payload = JSON.parse(readFileSync(captured, "utf8"));+ assert.deepEqual(payload.allowed_mentions, { parse: [] });+ assert.equal(+ payload.content,+ `New issue #12 by **untrusted-author**: ${title}\nhttps://example.invalid/issues/12`,+ );+ assert.throws(() => readFileSync(marker), { code: "ENOENT" });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});+const ghMock = `#!/bin/sh+set -eu+case "$1 $2" in+ 'api --paginate') printf '%s' "$MOCK_FILES" ;;+ 'pr checks')+ case "$*" in+ *--watch*) exit "$MOCK_WATCH_STATUS" ;;+ *) printf '%s' "$MOCK_CHECKS" ;;+ esac ;;+ 'pr view') printf '{"headRefOid":"%s"}' "$MOCK_HEAD" ;;+ 'pr merge') printf '%s' "$*" > "$MOCK_MERGED" ;;+ *) exit 99 ;;+esac+`;+const success = [{ name: "unit", bucket: "pass" }];+const manifest = [+ { filename: "packages/mcp/package.json", status: "modified" },+];+for (const [name, overrides, allowed] of [+ ["passing required checks permit the verified head", {}, true],+ ["missing required checks reject", { checks: [] }, false],+ ["failing checks reject", { checks: [{ bucket: "fail" }] }, false],+ ["pending checks reject", { checks: [{ bucket: "pending" }] }, false],+ ["skipped checks reject", { checks: [{ bucket: "skipping" }] }, false],+ ["cancelled checks reject", { checks: [{ bucket: "cancel" }] }, false],+ ["watch failure rejects", { watch: 1 }, false],+ ["updated PR head rejects", { head: "different-head" }, false],+ [+ "workflow edits reject",+ { files: [{ filename: ".github/workflows/ci.yml", status: "modified" }] },+ false,+ ],+ [+ "arbitrary source edits reject",+ { files: [{ filename: "apps/api/src/auth.ts", status: "modified" }] },+ false,+ ],+ [+ "renamed manifests reject",+ { files: [{ filename: "package.json", status: "renamed" }] },+ false,+ ],+ ["empty files reject", { files: [] }, false],+ ["malformed checks reject", { checks: null }, false],+]) {+ test(`Dependabot: ${name}`, () => {+ const dir = mkdtempSync(path.join(tmpdir(), "kaneo-merge-test-"));+ try {+ const marker = path.join(dir, "merged");+ writeFileSync(path.join(dir, "gh"), ghMock, { mode: 0o700 });+ const result = spawnSync("bash", ["-c", mergeScript], {+ env: {+ PATH: `${dir}:/usr/bin:/bin:/opt/homebrew/bin`,+ GITHUB_REPOSITORY: "test/repo",+ PR_URL: "https://example.invalid/pull/1",+ PR_NUMBER: "1",+ EXPECTED_HEAD: "reviewed-head",+ MOCK_FILES: JSON.stringify(overrides.files ?? manifest),+ MOCK_CHECKS: JSON.stringify(+ "checks" in overrides ? overrides.checks : success,+ ),+ MOCK_WATCH_STATUS: String(overrides.watch ?? 0),+ MOCK_HEAD: overrides.head ?? "reviewed-head",+ MOCK_MERGED: marker,+ },+ encoding: "utf8",+ });+ if (allowed) {+ assert.equal(result.status, 0, result.stderr);+ assert.match(+ readFileSync(marker, "utf8"),+ /--match-head-commit reviewed-head/,+ );+ } else {+ assert.notEqual(result.status, 0, result.stdout);+ assert.throws(() => readFileSync(marker), { code: "ENOENT" });+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+}++for (const version of ["1.2.3", "0.0.1-rc.1", "2.3.4+build.1"]) {+ test(`release version accepts ${version}`, () => {+ const result = spawnSync(+ process.execPath,+ [+ "scripts/security/validate-release-version.mjs",+ version,+ "--new-version",+ ],+ { cwd: root },+ );+ assert.equal(result.status, 0, String(result.stderr));+ });+}+for (const version of [+ "",+ "1.2",+ "01.2.3",+ "1.2.3-01",+ "1.2.3\nX=bad",+ "$(touch /tmp/kaneo-injection)1.2.3",+ '1.2.3"; exit 0; #',+ "--help",+]) {+ test(`release version rejects ${JSON.stringify(version)}`, () => {+ const result = spawnSync(+ process.execPath,+ [+ "scripts/security/validate-release-version.mjs",+ version,+ "--new-version",+ ],+ { cwd: root },+ );+ assert.notEqual(result.status, 0);+ });+}+test("image and chart version must match checked-out source", () => {+ const version = JSON.parse(+ readFileSync(path.join(root, "package.json")),+ ).version;+ for (const [input, allowed] of [+ [version, true],+ ["9999.0.0", false],+ ]) {+ const result = spawnSync(+ process.execPath,+ ["scripts/security/validate-release-version.mjs", input],+ { cwd: root },+ );+ assert.equal(result.status === 0, allowed);+ }+});++test("release packages reject a tag outside reviewed main history", () => {+ const dir = mkdtempSync(path.join(tmpdir(), "kaneo-release-test-"));+ const git = (...args) => {+ const result = spawnSync("git", args, { cwd: dir, encoding: "utf8" });+ assert.equal(result.status, 0, result.stderr);+ return result.stdout.trim();+ };+ try {+ git("init", "-b", "main");+ git(+ "-c",+ "user.name=Test",+ "-c",+ "[email protected]",+ "commit",+ "--allow-empty",+ "-m",+ "reviewed",+ );+ const approved = git("rev-parse", "HEAD");+ git("update-ref", "refs/remotes/origin/main", approved);+ git("checkout", "-b", "unreviewed");+ git(+ "-c",+ "user.name=Test",+ "-c",+ "[email protected]",+ "commit",+ "--allow-empty",+ "-m",+ "unreviewed",+ );+ const unapproved = git("rev-parse", "HEAD");+ for (const workflow of ["publish-mcp.yml", "publish-planka-import.yml"]) {+ const script = runBlock(workflow, "Require reviewed release source");+ for (const [sha, allowed] of [+ [approved, true],+ [unapproved, false],+ ]) {+ const result = spawnSync("bash", ["-c", script], {+ cwd: dir,+ env: {+ PATH: "/usr/bin:/bin:/opt/homebrew/bin",+ EVENT_NAME: "release",+ GITHUB_SHA: sha,+ GITHUB_REF: "refs/tags/package-v1.0.0",+ },+ });+ assert.equal(result.status === 0, allowed, workflow);+ }+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/tests/api-integration/asset-finalization.test.ts b/tests/api-integration/asset-finalization.test.tsnew file mode 100644index 000000000..83b13985a--- /dev/null+++ b/tests/api-integration/asset-finalization.test.ts@@ -0,0 +1,180 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ DeleteObjectCommand,+ HeadObjectCommand,+ S3Client,+} from "../../apps/api/node_modules/@aws-sdk/client-s3";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++async function fixture() {+ const member = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({ title: "Upload task", projectId: project.id })+ .returning();+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ const body = {+ filename: "test.png",+ contentType: "image/png",+ size: 12,+ surface: "description",+ };+ const response = await app.request(`/api/task/image-upload/${task.id}`, {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ });+ expect(response.status).toBe(200);+ const upload = (await response.json()) as { key: string; uploadUrl: string };+ const signedHeaders = new URL(upload.uploadUrl).searchParams+ .get("X-Amz-SignedHeaders")+ ?.split(";");+ expect(signedHeaders).toEqual(+ expect.arrayContaining(["content-length", "content-type"]),+ );+ return {+ key: upload.key,+ finalize(overrides: Record<string, unknown> = {}) {+ return app.request(`/api/task/image-upload/${task.id}/finalize`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ ...body, key: upload.key, ...overrides }),+ });+ },+ };+}++describe("asset finalization proof", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ vi.stubEnv("S3_ENDPOINT", "https://storage.example.test");+ vi.stubEnv("S3_BUCKET", "local-test-bucket");+ vi.stubEnv("S3_ACCESS_KEY_ID", "local-test-key");+ vi.stubEnv("S3_SECRET_ACCESS_KEY", "local-test-secret");+ vi.stubEnv("S3_KEY_PREFIX", "");+ vi.stubEnv("S3_MAX_IMAGE_UPLOAD_BYTES", "64");+ });+ afterEach(() => vi.unstubAllEnvs());++ it("does not create records for nonexistent objects", async () => {+ const send = vi.spyOn(S3Client.prototype, "send").mockRejectedValue(+ Object.assign(new Error("provider-private-detail"), {+ name: "NotFound",+ }),+ );+ const { finalize } = await fixture();+ const response = await finalize();+ expect(response.status).toBe(400);+ expect(await response.text()).toBe("Uploaded object was not found.");+ expect(await db.select().from(schema.assetTable)).toHaveLength(0);+ expect(send).toHaveBeenCalledOnce();+ expect(send.mock.calls[0][0]).toBeInstanceOf(HeadObjectCommand);+ });++ it.each([+ { ContentLength: 13, ContentType: "image/png" },+ { ContentLength: 12, ContentType: "text/html" },+ { ContentLength: 0, ContentType: "image/png" },+ { ContentType: "image/png" },+ ])(+ "rejects inconsistent metadata %j without deleting in-limit objects",+ async (metadata) => {+ const send = vi+ .spyOn(S3Client.prototype, "send")+ .mockResolvedValue(metadata);+ const { finalize } = await fixture();+ const response = await finalize();+ expect(response.status).toBe(400);+ expect(await db.select().from(schema.assetTable)).toHaveLength(0);+ expect(send).toHaveBeenCalledOnce();+ },+ );++ it("removes an oversized object left by an old upload URL without creating an asset", async () => {+ const send = vi+ .spyOn(S3Client.prototype, "send")+ .mockResolvedValueOnce({ ContentLength: 65, ContentType: "image/png" })+ .mockResolvedValueOnce({});+ const { key, finalize } = await fixture();+ const response = await finalize();+ expect(response.status).toBe(400);+ expect(send).toHaveBeenCalledTimes(2);+ expect(send.mock.calls[1][0]).toBeInstanceOf(DeleteObjectCommand);+ expect(send.mock.calls[1][0].input).toMatchObject({+ Key: key,+ Bucket: "local-test-bucket",+ });+ expect(await db.select().from(schema.assetTable)).toHaveLength(0);+ });++ it.each(["head", "delete"])(+ "fails closed without provider details when %s fails",+ async (stage) => {+ const send = vi.spyOn(S3Client.prototype, "send");+ if (stage === "delete")+ send.mockResolvedValueOnce({+ ContentLength: 65,+ ContentType: "image/png",+ });+ send.mockRejectedValueOnce(+ new Error("https://storage.example.test/?credential=secret"),+ );+ const { finalize } = await fixture();+ const response = await finalize();+ expect(response.status).toBe(503);+ expect(await response.text()).toBe("Unable to verify uploaded object.");+ expect(await db.select().from(schema.assetTable)).toHaveLength(0);+ },+ );++ it("checks key ownership before contacting storage", async () => {+ const send = vi+ .spyOn(S3Client.prototype, "send")+ .mockRejectedValue(new Error("must not run"));+ const { finalize } = await fixture();+ expect(+ (+ await finalize({+ key: "workspace/foreign/project/foreign/task/foreign/descriptions/x.png",+ })+ ).status,+ ).toBe(400);+ expect(send).not.toHaveBeenCalled();+ expect(await db.select().from(schema.assetTable)).toHaveLength(0);+ });++ it("persists verified metadata and preserves an existing record on failed refinalization", async () => {+ const send = vi+ .spyOn(S3Client.prototype, "send")+ .mockResolvedValue({ ContentLength: 12, ContentType: "image/png" });+ const { key, finalize } = await fixture();+ const first = await finalize();+ expect(first.status).toBe(200);+ const second = await finalize();+ expect(second.status).toBe(200);+ expect(await second.json()).toEqual(await first.json());+ const [asset] = await db.select().from(schema.assetTable);+ expect(asset).toMatchObject({+ objectKey: key,+ size: 12,+ mimeType: "image/png",+ kind: "image",+ });+ send.mockRejectedValueOnce(+ Object.assign(new Error("not found"), { name: "NotFound" }),+ );+ expect((await finalize({ filename: "changed.png" })).status).toBe(400);+ expect(await db.select().from(schema.assetTable)).toEqual([asset]);+ });+});diff --git a/tests/api-integration/asset-visibility.test.ts b/tests/api-integration/asset-visibility.test.tsnew file mode 100644index 000000000..6755f8dee--- /dev/null+++ b/tests/api-integration/asset-visibility.test.ts@@ -0,0 +1,76 @@+import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const { readObject } = vi.hoisted(() => ({+ readObject: vi.fn(async () => ({+ body: new Uint8Array([1, 2, 3]),+ contentType: "image/png",+ contentLength: 3,+ })),+}));+vi.mock("../../apps/api/src/storage/s3", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ getPrivateObject: readObject,+}));++describe("API integration: public project asset visibility", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ readObject.mockClear();+ });++ it("serves public descriptions but denies anonymous and other-workspace access to comment assets", async () => {+ const member = await createWorkspaceMember();+ const outsider = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ await db+ .update(schema.projectTable)+ .set({ isPublic: true })+ .where(eq(schema.projectTable.id, project.id));+ const assets = await db+ .insert(schema.assetTable)+ .values(+ ["description", "comment"].map((surface) => ({+ workspaceId: member.workspace.id,+ projectId: project.id,+ objectKey: randomUUID(),+ filename: "image.png",+ mimeType: "image/png",+ size: 3,+ surface,+ createdBy: member.user.id,+ })),+ )+ .returning();+ const description = assets.find((a) => a.surface === "description");+ const comment = assets.find((a) => a.surface === "comment");+ const { app } = createApp();+ mockAnonymousSession();+ const publicResponse = await app.request(`/api/asset/${description?.id}`);+ expect(publicResponse.status).toBe(200);+ expect(publicResponse.headers.get("cache-control")).toMatch(/^public,/);+ expect((await app.request(`/api/asset/${comment?.id}`)).status).toBe(401);+ expect(readObject).toHaveBeenCalledTimes(1);++ mockAuthenticatedSession(outsider.user);+ expect((await app.request(`/api/asset/${comment?.id}`)).status).toBe(403);+ expect(readObject).toHaveBeenCalledTimes(1);++ mockAuthenticatedSession(member.user);+ const privateResponse = await app.request(`/api/asset/${comment?.id}`);+ expect(privateResponse.status).toBe(200);+ expect(privateResponse.headers.get("cache-control")).toMatch(/^private,/);+ expect(readObject).toHaveBeenCalledTimes(2);+ });+});diff --git a/tests/api-integration/auth-captcha.test.ts b/tests/api-integration/auth-captcha.test.tsnew file mode 100644index 000000000..6ef077cad--- /dev/null+++ b/tests/api-integration/auth-captcha.test.ts@@ -0,0 +1,133 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { resetTestDatabase } from "./helpers/database";+import { createWorkspaceMember } from "./helpers/fixtures";++const endpoints = [+ [+ "/sign-up/email",+ {+ name: "User",+ email: "[email protected]",+ password: "long-test-password",+ },+ ],+ [+ "/sign-in/social",+ { provider: "github", callbackURL: "http://localhost:5173/dashboard" },+ ],+ [+ "/sign-in/oauth2",+ { providerId: "custom", callbackURL: "http://localhost:5173/dashboard" },+ ],+ ["/sign-in/anonymous", {}],+ [+ "/sign-in/magic-link",+ {+ email: "[email protected]",+ callbackURL: "http://localhost:5173/dashboard",+ },+ ],+ [+ "/email-otp/send-verification-otp",+ { email: "[email protected]", type: "sign-in" },+ ],+] as const;++function post(path: string, body: unknown, token?: string) {+ return createApp().app.request(`/api/auth${path}`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ Origin: "http://localhost:5173",+ ...(token ? { "x-turnstile-token": token } : {}),+ },+ body: JSON.stringify(body),+ });+}++describe("server-side auth CAPTCHA enforcement", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ await createWorkspaceMember();+ vi.stubEnv("TURNSTILE_SECRET_KEY", "test-only-secret");+ });+ afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ });++ it.each(endpoints)("rejects token-free calls to %s", async (path, body) => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ expect((await post(path, body)).status).toBe(403);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(await db.select().from(schema.userTable)).toHaveLength(1);+ expect(await db.select().from(schema.verificationTable)).toHaveLength(0);+ });++ it.each(endpoints)(+ "verifies before any account/mail/provider action at %s",+ async (path, body) => {+ const fetchMock = vi.fn(+ async () => new Response(JSON.stringify({ success: false })),+ );+ vi.stubGlobal("fetch", fetchMock);+ expect((await post(path, body, "invalid-token")).status).toBe(403);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0]?.[0]).toBe(+ "https://challenges.cloudflare.com/turnstile/v0/siteverify",+ );+ expect(await db.select().from(schema.userTable)).toHaveLength(1);+ expect(await db.select().from(schema.verificationTable)).toHaveLength(0);+ },+ );++ it("permits one verified guest request and rejects a replay response", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ success: true,+ hostname: "localhost",+ action: "auth",+ }),+ ),+ )+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ success: false,+ "error-codes": ["timeout-or-duplicate"],+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ expect(+ (await post("/sign-in/anonymous", {}, "single-use-token")).status,+ ).toBe(200);+ expect(+ (await post("/sign-in/anonymous", {}, "single-use-token")).status,+ ).toBe(403);+ expect(await db.select().from(schema.userTable)).toHaveLength(2);+ });++ it("does not exempt password bootstrap from configured CAPTCHA", async () => {+ await resetTestDatabase();+ expect((await post("/sign-up/email", endpoints[0][1])).status).toBe(403);+ expect(await db.select().from(schema.userTable)).toHaveLength(0);+ });++ it("does not redeem a second token at an OAuth callback", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const response = await createApp().app.request(+ "/api/auth/callback/github?code=invalid&state=invalid",+ );+ expect(response.status).not.toBe(200);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(await db.select().from(schema.userTable)).toHaveLength(1);+ });+});diff --git a/tests/api-integration/auth-client-ip.test.ts b/tests/api-integration/auth-client-ip.test.tsnew file mode 100644index 000000000..ef3bf64e4--- /dev/null+++ b/tests/api-integration/auth-client-ip.test.ts@@ -0,0 +1,55 @@+import { once } from "node:events";+import type { AddressInfo } from "node:net";+import { serve } from "@hono/node-server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { resetTestDatabase } from "./helpers/database";+import { createWorkspaceMember } from "./helpers/fixtures";++beforeEach(async () => {+ await resetTestDatabase();+ await createWorkspaceMember();+});+afterEach(() => vi.unstubAllEnvs());+describe("Better Auth session IP with trusted transport", () => {+ it.each(["none", "127.0.0.0/8"])(+ "records transport-resolved addresses under %s policy",+ async (policy) => {+ vi.stubEnv("TRUSTED_PROXIES", policy);+ const { app } = createApp();+ const server = serve({+ fetch: app.fetch,+ hostname: "127.0.0.1",+ port: 0,+ });+ await once(server, "listening");+ try {+ const response = await fetch(+ `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/auth/sign-in/anonymous`,+ {+ method: "POST",+ headers: {+ "content-type": "application/json",+ Origin: "http://localhost:5173",+ "x-kaneo-client-ip": "1.2.3.4",+ "cf-connecting-ip": "5.6.7.8",+ "x-forwarded-for": "1.2.3.4, 203.0.113.9",+ },+ body: "{}",+ },+ );+ expect(response.status, await response.text()).toBe(200);+ const sessions = await db.select().from(schema.sessionTable);+ expect(sessions).toHaveLength(1);+ expect(sessions[0].ipAddress).toBe(+ policy === "none" ? "127.0.0.1" : "203.0.113.9",+ );+ } finally {+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ }+ },+ );+});diff --git a/tests/api-integration/auth-registration-policy.test.ts b/tests/api-integration/auth-registration-policy.test.tsnew file mode 100644index 000000000..609e88afc--- /dev/null+++ b/tests/api-integration/auth-registration-policy.test.ts@@ -0,0 +1,262 @@+import * as email from "@kaneo/email";+import { eq } from "drizzle-orm";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import getInstanceStatus from "../../apps/api/src/instance/controllers/get-instance-status";+import { promoteInitialAdministrator } from "../../apps/api/src/utils/instance-bootstrap";+import { assertUserRegistrationAllowed } from "../../apps/api/src/utils/registration-policy";+import { resetTestDatabase } from "./helpers/database";+import { createWorkspaceMember } from "./helpers/fixtures";++const headers = {+ "content-type": "application/json",+ Origin: "http://localhost:5173",+};+function post(+ path: string,+ body: unknown,+ extraHeaders: Record<string, string> = {},+) {+ return createApp().app.request(`/api/auth${path}`, {+ method: "POST",+ headers: { ...headers, ...extraHeaders },+ body: JSON.stringify(body),+ });+}+function signup(email: string, extraHeaders?: Record<string, string>) {+ return post(+ "/sign-up/email",+ { name: "Test", email, password: "test-password-at-least-12" },+ extraHeaders,+ );+}+async function invitation(email: string) {+ const inviter = await createWorkspaceMember({ role: "owner" });+ const [row] = await db+ .insert(schema.invitationTable)+ .values({+ email,+ workspaceId: inviter.workspace.id,+ inviterId: inviter.user.id,+ role: "member",+ status: "pending",+ expiresAt: new Date(Date.now() + 60_000),+ })+ .returning();+ return row;+}++describe("auth registration and bootstrap boundaries", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });+ afterEach(() => vi.unstubAllEnvs());++ it("rejects anonymous bootstrap and ignores historical anonymous rows", async () => {+ expect((await post("/sign-in/anonymous", {})).status).toBe(403);+ expect(await db.select().from(schema.userTable)).toHaveLength(0);+ await db.insert(schema.userTable).values({+ id: "old-guest",+ email: "[email protected]",+ name: "Guest",+ isAnonymous: true,+ });+ expect(await getInstanceStatus()).toEqual({+ hasUsers: false,+ hasAdmin: false,+ });+ vi.stubEnv("DISABLE_REGISTRATION", "true");+ expect((await signup("[email protected]")).status).toBe(200);+ expect(await getInstanceStatus()).toEqual({+ hasUsers: true,+ hasAdmin: true,+ });+ expect(+ await db+ .select()+ .from(schema.userTable)+ .where(eq(schema.userTable.role, "admin")),+ ).toEqual([expect.objectContaining({ email: "[email protected]" })]);+ });++ it.each([+ "DISABLE_REGISTRATION",+ "DISABLE_PASSWORD_REGISTRATION",+ "DISABLE_LOGIN_FORM",+ "DISABLE_GUEST_ACCESS",+ ])("enforces %s on anonymous sign-in", async (flag) => {+ await createWorkspaceMember();+ vi.stubEnv(flag, "true");+ expect((await post("/sign-in/anonymous", {})).status).toBe(403);+ expect(await db.select().from(schema.userTable)).toHaveLength(1);+ });++ it("allows configured guest access on an initialized open instance", async () => {+ await createWorkspaceMember();+ expect((await post("/sign-in/anonymous", {})).status).toBe(200);+ expect(+ await db+ .select()+ .from(schema.userTable)+ .where(eq(schema.userTable.isAnonymous, true)),+ ).toHaveLength(1);+ expect(+ await db+ .select()+ .from(schema.userTable)+ .where(eq(schema.userTable.role, "admin")),+ ).toHaveLength(0);+ });++ it("elects exactly one admin when multiple first users already exist before the after-hooks", async () => {+ await db.insert(schema.userTable).values(+ ["first", "second"].map((id) => ({+ id,+ name: id,+ email: `${id}@example.com`,+ createdAt: new Date("2026-01-01"),+ })),+ );+ await Promise.all([+ promoteInitialAdministrator("second"),+ promoteInitialAdministrator("first"),+ ]);+ expect(+ await db+ .select()+ .from(schema.userTable)+ .where(eq(schema.userTable.role, "admin")),+ ).toEqual([expect.objectContaining({ id: "first" })]);+ });++ it("keeps one admin through concurrent HTTP first signups", async () => {+ const responses = await Promise.all(+ [1, 2, 3, 4].map((n) => signup(`race-${n}@example.com`)),+ );+ expect(responses.map((r) => r.status)).toEqual([200, 200, 200, 200]);+ expect(+ await db+ .select()+ .from(schema.userTable)+ .where(eq(schema.userTable.role, "admin")),+ ).toHaveLength(1);+ });++ it("does not give a new signup admin rights on an older instance lacking an admin", async () => {+ await createWorkspaceMember();+ expect((await signup("[email protected]")).status).toBe(200);+ expect(+ await db+ .select()+ .from(schema.userTable)+ .where(eq(schema.userTable.role, "admin")),+ ).toHaveLength(0);+ });++ it("requires the matching invitation secret for password signup", async () => {+ const invite = await invitation("[email protected]");+ vi.stubEnv("DISABLE_REGISTRATION", "true");+ expect((await signup(invite.email)).status).toBe(403);+ expect(+ (await signup(invite.email, { "x-invitation-id": "wrong" })).status,+ ).toBe(403);+ expect(+ (await signup("[email protected]", { "x-invitation-id": invite.id }))+ .status,+ ).toBe(403);+ expect(+ (await signup(invite.email, { "x-invitation-id": invite.id })).status,+ ).toBe(200);+ });++ it("only accepts provider or mailbox verified email claims at the user-create boundary", async () => {+ await invitation("[email protected]");+ vi.stubEnv("DISABLE_REGISTRATION", "true");+ for (const path of [+ "/callback/github",+ "/oauth2/callback/custom",+ "/sign-in/email-otp",+ "/magic-link/verify",+ ]) {+ await expect(+ assertUserRegistrationAllowed(+ { email: "[email protected]", emailVerified: false },+ { path },+ ),+ ).rejects.toMatchObject({ status: "FORBIDDEN" });+ await expect(+ assertUserRegistrationAllowed(+ { email: "[email protected]", emailVerified: true },+ { path },+ ),+ ).resolves.toBeUndefined();+ }+ await expect(+ assertUserRegistrationAllowed(+ { email: "[email protected]", emailVerified: true },+ { path: "/sign-up/email" },+ ),+ ).rejects.toMatchObject({ status: "FORBIDDEN" });+ });++ it("prevents new OTP accounts under the local-registration restriction but preserves existing-user OTP login", async () => {+ const member = await createWorkspaceMember();+ vi.stubEnv("DISABLE_PASSWORD_REGISTRATION", "true");+ const send = vi.spyOn(email, "sendOtpEmail").mockResolvedValue(undefined);+ for (const address of ["[email protected]", member.user.email]) {+ expect(+ (+ await post("/email-otp/send-verification-otp", {+ email: address,+ type: "sign-in",+ })+ ).status,+ ).toBe(200);+ const data = send.mock.lastCall?.[2] as { otp: string } | undefined;+ expect(data?.otp).toBeTruthy();+ const response = await post("/sign-in/email-otp", {+ email: address,+ otp: data?.otp,+ });+ expect(response.status).toBe(address === member.user.email ? 200 : 403);+ }+ expect(await db.select().from(schema.userTable)).toHaveLength(1);+ });++ it("stores a five-minute OTP expiry and rejects an expired code", async () => {+ const member = await createWorkspaceMember();+ const send = vi.spyOn(email, "sendOtpEmail").mockResolvedValue(undefined);+ const before = Date.now();+ expect(+ (+ await post("/email-otp/send-verification-otp", {+ email: member.user.email,+ type: "sign-in",+ })+ ).status,+ ).toBe(200);+ const rows = await db.select().from(schema.verificationTable);+ expect(rows).toHaveLength(1);+ expect(rows[0].expiresAt.getTime()).toBeGreaterThanOrEqual(+ before + 300_000,+ );+ expect(rows[0].expiresAt.getTime()).toBeLessThanOrEqual(+ Date.now() + 300_000,+ );+ const data = send.mock.lastCall?.[2] as { otp: string };+ await db+ .update(schema.verificationTable)+ .set({ expiresAt: new Date(Date.now() - 1000) })+ .where(eq(schema.verificationTable.id, rows[0].id));+ expect(+ (+ await post("/sign-in/email-otp", {+ email: member.user.email,+ otp: data.otp,+ })+ ).status,+ ).toBe(400);+ expect(await db.select().from(schema.sessionTable)).toHaveLength(0);+ });+});diff --git a/tests/api-integration/avatar-bounds.test.ts b/tests/api-integration/avatar-bounds.test.tsnew file mode 100644index 000000000..164f4f239--- /dev/null+++ b/tests/api-integration/avatar-bounds.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import {+ MAX_AVATAR_BYTES,+ MAX_AVATAR_INPUT_CHARS,+ MAX_AVATAR_REQUEST_BYTES,+} from "../../apps/api/src/user/avatar";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import { createWorkspaceMember } from "./helpers/fixtures";++beforeEach(resetTestDatabase);+async function fixture() {+ const member = await createWorkspaceMember({ role: "viewer" });+ mockAuthenticatedSession(member.user);+ return createApp().app;+}+describe("avatar request bounds", () => {+ it("rejects excessive declared length before reading the body", async () => {+ const app = await fixture();+ const cancel = vi.fn();+ const response = await app.request(+ new Request("http://localhost/api/user/avatar", {+ method: "PUT",+ headers: {+ "content-type": "application/json",+ "content-length": String(MAX_AVATAR_REQUEST_BYTES + 1),+ },+ body: new ReadableStream({ cancel }),+ duplex: "half",+ } as RequestInit),+ );+ expect(response.status).toBe(413);+ expect(cancel).toHaveBeenCalledOnce();+ expect(await db.select().from(schema.userAvatarTable)).toHaveLength(0);+ });+ it.each([undefined, "1"])(+ "counts actual chunked bytes with length header %s before JSON parsing",+ async (length) => {+ const app = await fixture();+ const cancel = vi.fn();+ const headers: Record<string, string> = {+ "content-type": "application/json",+ };+ if (length) headers["content-length"] = length;+ const response = await app.request(+ new Request("http://localhost/api/user/avatar", {+ method: "PUT",+ headers,+ body: new ReadableStream({+ pull(controller) {+ controller.enqueue(new Uint8Array(16 * 1024));+ },+ cancel,+ }),+ duplex: "half",+ } as RequestInit),+ );+ // Invalid JSON would be 400 if the parser ran before the byte guard.+ expect(response.status).toBe(413);+ expect(cancel).toHaveBeenCalledOnce();+ expect(await db.select().from(schema.userAvatarTable)).toHaveLength(0);+ },+ );+ it("rejects oversized encoded input inside a bounded JSON request", async () => {+ const app = await fixture();+ const response = await app.request("/api/user/avatar", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ contentType: "image/png",+ data: " ".repeat(MAX_AVATAR_INPUT_CHARS + 1),+ }),+ });+ expect(response.status).toBe(400);+ expect(await db.select().from(schema.userAvatarTable)).toHaveLength(0);+ });+ it("stores a valid maximum-size avatar for an authenticated viewer", async () => {+ const app = await fixture();+ const bytes = Buffer.alloc(MAX_AVATAR_BYTES);+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(bytes);+ const response = await app.request("/api/user/avatar", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ contentType: "image/png",+ data: bytes.toString("base64"),+ }),+ });+ expect(response.status, await response.text()).toBe(200);+ const [row] = await db.select().from(schema.userAvatarTable);+ expect(row.size).toBe(MAX_AVATAR_BYTES);+ expect(Buffer.from(row.data).equals(bytes)).toBe(true);+ });+});diff --git a/tests/api-integration/bulk-task-events.test.ts b/tests/api-integration/bulk-task-events.test.tsnew file mode 100644index 000000000..e3d989669--- /dev/null+++ b/tests/api-integration/bulk-task-events.test.ts@@ -0,0 +1,95 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import bulkUpdateTasks from "../../apps/api/src/task/controllers/bulk-update-tasks";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const publish = vi.hoisted(() => vi.fn(async () => undefined));+vi.mock("../../apps/api/src/events", () => ({ publishEvent: publish }));++beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+});++describe("bulk task event snapshots", () => {+ it("preserves each task's old status, title and assignee for reopening and notifications", async () => {+ const { user, workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const tasks = await db+ .insert(schema.taskTable)+ .values([+ {+ projectId: project.id,+ title: "Completed",+ status: "done",+ userId: user.id,+ number: 1,+ },+ { projectId: project.id, title: "Queued", status: "to-do", number: 2 },+ ])+ .returning();+ await bulkUpdateTasks({+ taskIds: tasks.map((task) => task.id),+ operation: "updateStatus",+ value: "in-progress",+ userId: user.id,+ });+ for (const task of tasks) {+ expect(publish).toHaveBeenCalledWith(+ "task.status_changed",+ expect.objectContaining({+ taskId: task.id,+ projectId: project.id,+ oldStatus: task.status,+ newStatus: "in-progress",+ title: task.title,+ assigneeId: task.userId,+ }),+ );+ }+ expect(await db.query.taskTable.findMany()).toEqual(+ expect.arrayContaining(+ tasks.map((task) =>+ expect.objectContaining({ id: task.id, status: "in-progress" }),+ ),+ ),+ );+ });++ it("preserves differing old priorities and titles in a single bulk operation", async () => {+ const { user, workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const tasks = await db+ .insert(schema.taskTable)+ .values([+ { projectId: project.id, title: "Low", priority: "low", number: 1 },+ { projectId: project.id, title: "High", priority: "high", number: 2 },+ ])+ .returning();+ await bulkUpdateTasks({+ taskIds: tasks.map((task) => task.id),+ operation: "updatePriority",+ value: "medium",+ userId: user.id,+ });+ for (const task of tasks) {+ expect(publish).toHaveBeenCalledWith(+ "task.priority_changed",+ expect.objectContaining({+ taskId: task.id,+ oldPriority: task.priority,+ newPriority: "medium",+ title: task.title,+ }),+ );+ }+ });+});diff --git a/tests/api-integration/comment-attribution.test.ts b/tests/api-integration/comment-attribution.test.tsnew file mode 100644index 000000000..0966c694f--- /dev/null+++ b/tests/api-integration/comment-attribution.test.ts@@ -0,0 +1,110 @@+import { createHash, randomUUID } from "node:crypto";+import { beforeEach, describe, expect, it } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++beforeEach(resetTestDatabase);+describe("external comment attribution", () => {+ it.each(["planka", "trello", "jira"])(+ "blocks ordinary member impersonation through %s but allows their own comments",+ async (externalSource) => {+ const member = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Task",+ status: "to-do",+ number: 1,+ })+ .returning();+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ const send = (body: object) =>+ app.request(`/api/comment/${task.id}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ });+ expect(+ (+ await send({+ content: "Fake",+ externalUserName: "Executive",+ externalSource,+ })+ ).status,+ ).toBe(403);+ expect(await db.select().from(schema.activityTable)).toHaveLength(0);+ expect((await send({ content: "My comment" })).status).toBe(200);+ const [row] = await db.select().from(schema.activityTable);+ expect(row.userId).toBe(member.user.id);+ expect(row.externalUserName).toBeNull();+ expect(row.externalSource).toBeNull();+ },+ );++ it.each([false, true])(+ "requires explicit import permission on an admin's API key (granted=%s)",+ async (granted) => {+ const member = await createWorkspaceMember({ role: "admin" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Task",+ status: "to-do",+ number: 1,+ })+ .returning();+ mockAnonymousSession();+ const key = `test_${randomUUID()}`;+ await db.insert(schema.apikeyTable).values({+ referenceId: member.user.id,+ userId: member.user.id,+ key: createHash("sha256").update(key).digest("base64url"),+ enabled: true,+ createdAt: new Date(),+ updatedAt: new Date(),+ permissions: JSON.stringify({+ task: ["update"],+ ...(granted ? { workspace: ["manage_settings"] } : {}),+ }),+ });+ const { app } = createApp();+ const response = await app.request(`/api/comment/${task.id}`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ Authorization: `Bearer ${key}`,+ },+ body: JSON.stringify({+ content: "Imported",+ externalSource: "planka",+ externalUserName: "Historical Author",+ }),+ });+ expect(response.status).toBe(granted ? 200 : 403);+ const rows = await db.select().from(schema.activityTable);+ expect(rows).toHaveLength(granted ? 1 : 0);+ if (granted)+ expect(rows[0]).toMatchObject({+ userId: member.user.id,+ externalUserName: "Historical Author",+ externalSource: "planka",+ });+ },+ );+});diff --git a/tests/api-integration/comment.test.ts b/tests/api-integration/comment.test.tsindex 9955410fb..60f1926c5 100644--- a/tests/api-integration/comment.test.ts+++ b/tests/api-integration/comment.test.ts@@ -95,8 +95,8 @@ describe("API integration: task comments", () => {expect(legacyComments).toHaveLength(0);});- it("records an external author when both name and source are given", async () => {- const member = await createWorkspaceMember();+ it("records an external author for an authorized workspace administrator", async () => {+ const member = await createWorkspaceMember({ role: "admin" });const { project, columns } = await createProjectFixture({workspaceId: member.workspace.id,});diff --git a/tests/api-integration/custom-field-security.test.ts b/tests/api-integration/custom-field-security.test.tsnew file mode 100644index 000000000..f864ad482--- /dev/null+++ b/tests/api-integration/custom-field-security.test.ts@@ -0,0 +1,201 @@+import { createHash, randomUUID } from "node:crypto";+import { beforeEach, describe, expect, it } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++beforeEach(resetTestDatabase);++async function fixture(role = "admin") {+ const member = await createWorkspaceMember({ role });+ const { project, columns } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Private task",+ number: 1,+ status: "to-do",+ columnId: columns.todo.id,+ })+ .returning();+ const [field] = await db+ .insert(schema.customFieldDefinitionTable)+ .values({+ projectId: project.id,+ name: "Private field",+ type: "text",+ required: false,+ defaultValue: "private-default",+ position: 0,+ })+ .returning();+ await db+ .insert(schema.customFieldValueTable)+ .values({ taskId: task.id, fieldId: field.id, value: "private-value" });+ const { app } = createApp();+ return {+ member,+ project,+ task,+ app,+ paths: [+ `/api/custom-field/project/${project.id}`,+ `/api/custom-field/project/${project.id}/values`,+ `/api/custom-field/task/${task.id}`,+ `/api/custom-field/project/${project.id}/filter-values`,+ ],+ };+}++describe("custom field read authorization", () => {+ for (const authentication of ["api-key", "custom-role"] as const) {+ it.each([+ [{}, [403, 403, 403, 403]],+ [{ project: ["read"] }, [200, 403, 403, 403]],+ [{ task: ["read"] }, [403, 200, 200, 200]],+ [{ project: ["read"], task: ["read"] }, [200, 200, 200, 200]],+ ] as [Record<string, string[]>, number[]][])(+ `${authentication} respects permission map %j`,+ async (permissions, expected) => {+ const { member, app, paths } = await fixture(+ authentication === "custom-role" ? "limited" : "admin",+ );+ const headers: Record<string, string> = {};+ if (authentication === "custom-role") {+ await db.insert(schema.workspaceRoleTable).values({+ workspaceId: member.workspace.id,+ role: "limited",+ permission: JSON.stringify(permissions),+ });+ mockAuthenticatedSession(member.user);+ } else {+ mockAnonymousSession();+ const key = `kaneo_test_${randomUUID()}`;+ await db.insert(schema.apikeyTable).values({+ referenceId: member.user.id,+ userId: member.user.id,+ key: createHash("sha256").update(key).digest("base64url"),+ name: "scoped test key",+ createdAt: new Date(),+ updatedAt: new Date(),+ permissions: JSON.stringify(permissions),+ enabled: true,+ });+ headers.Authorization = `Bearer ${key}`;+ }+ for (const [i, path] of paths.entries()) {+ const response = await app.request(path, { headers });+ expect(response.status, path).toBe(expected[i]);+ const body = await response.text();+ if (expected[i] === 403) {+ expect(body).not.toContain("private-default");+ expect(body).not.toContain("private-value");+ expect(body).not.toContain("Private field");+ } else {+ expect(body).toContain(+ i === 0 ? "private-default" : "private-value",+ );+ }+ }+ },+ );+ }++ it("does not let read scopes bypass workspace membership", async () => {+ const { app, paths } = await fixture();+ const outsider = await createWorkspaceMember({ role: "admin" });+ mockAuthenticatedSession(outsider.user);+ for (const path of paths)+ expect((await app.request(path)).status).toBe(403);+ });+});++describe("date defaults", () => {+ it.each([+ "2026-02-30",+ "2025-02-29",+ "2026-13-01",+ "2026-00-01",+ "2026-01-00",+ "2026-02-30T12:00:00Z",+ "September 19, 2026",+ ])(+ "rejects invalid default %s without definition or backfill writes",+ async (defaultValue) => {+ const { member, project, app } = await fixture();+ mockAuthenticatedSession(member.user);+ const response = await app.request("/api/custom-field", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ projectId: project.id,+ name: "Deadline",+ type: "date",+ required: true,+ defaultValue,+ }),+ });+ expect(response.status).toBe(400);+ expect(+ await db.select().from(schema.customFieldDefinitionTable),+ ).toHaveLength(1);+ expect(await db.select().from(schema.customFieldValueTable)).toHaveLength(+ 1,+ );+ },+ );++ it.each(["2028-02-29", "2028-02-29T12:00:00Z", " 2028-02-29 "])(+ "accepts %s and uses it for existing and newly created tasks",+ async (defaultValue) => {+ const { member, project, app } = await fixture();+ mockAuthenticatedSession(member.user);+ // Fixtures inserted a task directly; synchronize its project counter.+ const { eq } = await import("drizzle-orm");+ await db+ .update(schema.projectTable)+ .set({ lastTaskNumber: 1 })+ .where(eq(schema.projectTable.id, project.id));+ const response = await app.request("/api/custom-field", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ projectId: project.id,+ name: "Deadline",+ type: "date",+ required: true,+ defaultValue,+ }),+ });+ expect(response.status).toBe(200);+ const field = await response.json();+ const created = await app.request(`/api/task/${project.id}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ title: "New task",+ description: "",+ priority: "low",+ status: "to-do",+ }),+ });+ expect(created.status, await created.text()).toBe(200);+ const values = await db+ .select()+ .from(schema.customFieldValueTable)+ .where(eq(schema.customFieldValueTable.fieldId, field.id));+ expect(values).toHaveLength(2);+ expect(values.every((value) => value.value === defaultValue.trim())).toBe(+ true,+ );+ },+ );+});diff --git a/tests/api-integration/gitea-task-numbering.test.ts b/tests/api-integration/gitea-task-numbering.test.tsnew file mode 100644index 000000000..d797d93db--- /dev/null+++ b/tests/api-integration/gitea-task-numbering.test.ts@@ -0,0 +1,130 @@+import { readFileSync } from "node:fs";+import { eq, sql } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { importGiteaIssues } from "../../apps/api/src/gitea-integration/controllers/import-gitea-issues";+import createTask from "../../apps/api/src/task/controllers/create-task";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++vi.mock("../../apps/api/src/events", () => ({+ publishEvent: vi.fn(async () => undefined),+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({+ createGiteaClient: () => ({+ listIssues: async () => [+ {+ number: 1,+ title: "Imported issue",+ body: "Body",+ state: "open",+ labels: [],+ html_url: "https://gitea.example/owner/repo/issues/1",+ },+ ],+ listPulls: async () => [],+ listIssueComments: async () => [],+ }),+}));+const repair = readFileSync(+ new URL(+ "../../apps/api/drizzle/0046_repair_task_number_counters.sql",+ import.meta.url,+ ),+ "utf8",+);+beforeEach(async () => {+ await resetTestDatabase();+});+async function setup() {+ const { user, workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({ workspaceId: workspace.id });+ await db.insert(schema.integrationTable).values({+ projectId: project.id,+ type: "gitea",+ config: JSON.stringify({+ baseUrl: "https://gitea.example",+ accessToken: "fake-local-token",+ repositoryOwner: "owner",+ repositoryName: "repo",+ }),+ });+ return { user, project };+}++describe("Gitea import task numbers", () => {+ it("advances the shared counter before a normal task is created", async () => {+ const { user, project } = await setup();+ expect(await importGiteaIssues(project.id)).toMatchObject({ imported: 1 });+ const task = await createTask({+ projectId: project.id,+ currentUserId: user.id,+ title: "Next",+ status: "to-do",+ });+ expect(task.number).toBe(2);+ expect(+ await db.query.projectTable.findFirst({+ where: eq(schema.projectTable.id, project.id),+ }),+ ).toHaveProperty("lastTaskNumber", 2);+ });++ it("serializes import and concurrent ordinary creation through one counter", async () => {+ const { user, project } = await setup();+ const [imported] = await Promise.all([+ importGiteaIssues(project.id),+ ...Array.from({ length: 3 }, (_, index) =>+ createTask({+ projectId: project.id,+ currentUserId: user.id,+ title: `Concurrent ${index}`,+ status: "to-do",+ }),+ ),+ ]);+ expect(imported).toMatchObject({ imported: 1 });+ const tasks = await db.query.taskTable.findMany();+ expect(tasks.map((task) => task.number).sort()).toEqual([1, 2, 3, 4]);+ });++ it("repairs a legacy counter without renumbering existing references, and is idempotent", async () => {+ const { user, project } = await setup();+ await db.insert(schema.taskTable).values([+ { projectId: project.id, title: "Legacy import", number: 42 },+ { projectId: project.id, title: "Earlier task", number: 41 },+ ]);+ await db.execute(sql.raw(repair));+ await db.execute(sql.raw(repair));+ const task = await createTask({+ projectId: project.id,+ currentUserId: user.id,+ title: "After upgrade",+ status: "to-do",+ });+ expect(task.number).toBe(43);+ const tasks = await db.query.taskTable.findMany();+ expect(tasks.map((row) => row.number).sort()).toEqual([41, 42, 43]);+ });++ it("never lowers a high-water counter when the highest task was deleted", async () => {+ const { project } = await setup();+ await db+ .update(schema.projectTable)+ .set({ lastTaskNumber: 100 })+ .where(eq(schema.projectTable.id, project.id));+ await db+ .insert(schema.taskTable)+ .values({ projectId: project.id, title: "Older task", number: 1 });+ await db.execute(sql.raw(repair));+ expect(await importGiteaIssues(project.id)).toMatchObject({ imported: 1 });+ expect(+ await db.query.projectTable.findFirst({+ where: eq(schema.projectTable.id, project.id),+ }),+ ).toHaveProperty("lastTaskNumber", 101);+ });+});diff --git a/tests/api-integration/github-binding-routes.test.ts b/tests/api-integration/github-binding-routes.test.tsnew file mode 100644index 000000000..57876f83d--- /dev/null+++ b/tests/api-integration/github-binding-routes.test.ts@@ -0,0 +1,211 @@+import { createHash } from "node:crypto";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { handleLabelCreated } from "../../apps/api/src/plugins/github/webhooks/label-created";+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const m = vi.hoisted(() => ({ installation: vi.fn(), permission: vi.fn() }));+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({+ getGithubApp: () => ({+ octokit: { rest: { apps: { getRepoInstallation: m.installation } } },+ getInstallationOctokit: async () => ({+ rest: {+ users: { getById: async () => ({ data: { id: 30, login: "admin" } }) },+ repos: {+ getCollaboratorPermissionLevel: m.permission,+ get: async () => ({+ data: { id: 20, owner: { login: "owner" }, name: "repo" },+ }),+ },+ },+ }),+ }),+}));++beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+ m.installation.mockResolvedValue({ data: { id: 10 } });+ m.permission.mockResolvedValue({ data: { permission: "admin" } });+});++async function fixture(role = "admin") {+ const member = await createWorkspaceMember({ role });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ return { ...member, project };+}+function calls(projectId: string) {+ return [+ [+ `/api/github-integration/project/${projectId}`,+ {+ method: "POST",+ body: JSON.stringify({+ repositoryOwner: "owner",+ repositoryName: "repo",+ }),+ },+ ],+ [+ "/api/github-integration/verify",+ {+ method: "POST",+ body: JSON.stringify({+ projectId,+ repositoryOwner: "owner",+ repositoryName: "repo",+ }),+ },+ ],+ [`/api/github-integration/repositories/${projectId}`, { method: "GET" }],+ ] as const;+}++describe("GitHub binding HTTP and webhook tenant boundaries", () => {+ it("rejects an owner's unrestricted API key before repository provider calls", async () => {+ const owner = await fixture();+ mockAnonymousSession();+ const key = "kaneo_local_binding_test_key";+ await db.insert(schema.apikeyTable).values({+ referenceId: owner.user.id,+ userId: owner.user.id,+ key: createHash("sha256").update(key).digest("base64url"),+ name: "local test",+ createdAt: new Date(),+ updatedAt: new Date(),+ enabled: true,+ });+ const { app } = createApp();+ for (const [url, options] of calls(owner.project.id)) {+ const response = await app.request(url, {+ ...options,+ headers: {+ "content-type": "application/json",+ Authorization: `Bearer ${key}`,+ },+ });+ expect(response.status).toBe(403);+ }+ expect(m.installation).not.toHaveBeenCalled();+ expect(await db.query.integrationTable.findMany()).toHaveLength(0);+ });++ it("denies members and foreign-workspace administrators before provider lookup", async () => {+ const member = await fixture("member");+ const outsider = await fixture();+ const { app } = createApp();+ for (const user of [member.user, outsider.user]) {+ mockAuthenticatedSession(user);+ for (const [url, options] of calls(member.project.id)) {+ const response = await app.request(url, {+ ...options,+ headers: { "content-type": "application/json" },+ });+ expect(response.status).toBe(403);+ }+ }+ expect(m.installation).not.toHaveBeenCalled();+ });++ it("requires a completed OAuth account and permits independently authorized tenant bindings", async () => {+ const owners = [await fixture(), await fixture()];+ const { app } = createApp();+ const connect = (projectId: string) =>+ app.request(calls(projectId)[0][0], {+ ...calls(projectId)[0][1],+ headers: { "content-type": "application/json" },+ });+ mockAuthenticatedSession(owners[0].user);+ expect((await connect(owners[0].project.id)).status).toBe(403);+ expect(m.installation).not.toHaveBeenCalled();+ for (const owner of owners) {+ await db.insert(schema.accountTable).values({+ id: `account-${owner.user.id}`,+ userId: owner.user.id,+ providerId: "github",+ accountId: "30",+ createdAt: new Date(),+ updatedAt: new Date(),+ });+ mockAuthenticatedSession(owner.user);+ expect((await connect(owner.project.id)).status).toBe(200);+ }+ const bindings = await db.query.integrationTable.findMany();+ expect(bindings).toHaveLength(2);+ for (const binding of bindings)+ expect(JSON.parse(binding.config)).toMatchObject({+ repositoryId: 20,+ installationId: 10,+ verifiedGithubAccountId: "30",+ });+ m.permission.mockResolvedValue({ data: { permission: "read" } });+ const forbidden = await connect(owners[1].project.id);+ expect(forbidden.status).toBe(403);+ expect(await forbidden.text()).not.toContain(owners[0].workspace.id);+ });++ it("an actual label webhook mutates only a verified matching active tenant", async () => {+ const configs = [+ {+ repositoryId: 20,+ installationId: 10,+ verifiedGithubAccountId: "30",+ verifiedByUserId: "operator",+ },+ { installationId: 10 },+ {+ repositoryId: 21,+ installationId: 10,+ verifiedGithubAccountId: "30",+ verifiedByUserId: "operator",+ },+ {+ repositoryId: 20,+ installationId: 11,+ verifiedGithubAccountId: "30",+ verifiedByUserId: "operator",+ },+ ];+ const tenants = [];+ for (const config of configs) {+ const tenant = await fixture();+ tenants.push(tenant);+ await db.insert(schema.integrationTable).values({+ projectId: tenant.project.id,+ type: "github",+ isActive: true,+ config: JSON.stringify({+ repositoryOwner: "owner",+ repositoryName: "repo",+ ...config,+ }),+ });+ }+ await handleLabelCreated({+ action: "created",+ label: { name: "Provider label", color: "123456" },+ repository: { id: 20, owner: { login: "owner" }, name: "repo" },+ installation: { id: 10 },+ });+ const labels = await db.query.labelTable.findMany();+ expect(labels).toHaveLength(1);+ expect(labels[0]).toMatchObject({+ workspaceId: tenants[0].workspace.id,+ name: "Provider label",+ });+ await handleLabelCreated({+ action: "created",+ label: { name: "Missing installation", color: "123456" },+ repository: { id: 20, owner: { login: "owner" }, name: "repo" },+ });+ expect(await db.query.labelTable.findMany()).toHaveLength(1);+ });+});diff --git a/tests/api-integration/github-description-sync.test.ts b/tests/api-integration/github-description-sync.test.tsnew file mode 100644index 000000000..2e536515a--- /dev/null+++ b/tests/api-integration/github-description-sync.test.ts@@ -0,0 +1,118 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { formatIssueBody } from "../../apps/api/src/plugins/github/utils/format";+import { handleIssueEdited } from "../../apps/api/src/plugins/github/webhooks/issue-edited";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const m = vi.hoisted(() => ({+ find: vi.fn(),+ update: vi.fn(async () => undefined),+}));+vi.mock("../../apps/api/src/plugins/github/services/task-service", () => ({+ findAllIntegrationsByRepo: async () => [{ id: "verified-integration" }],+}));+vi.mock("../../apps/api/src/plugins/github/services/link-manager", () => ({+ findExternalLink: m.find,+ updateExternalLink: m.update,+}));++beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+});++async function setup() {+ const { workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({ workspaceId: workspace.id });+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Linked",+ description: "Original description",+ number: 1,+ })+ .returning();+ m.find.mockResolvedValue({+ id: "link",+ taskId: task.id,+ metadata: JSON.stringify({+ lastSync: {+ description: {+ source: "kaneo",+ value: task.description,+ timestamp: new Date(Date.now() - 60_000).toISOString(),+ },+ },+ }),+ });+ return task;+}+function webhook(body: string) {+ return handleIssueEdited({+ action: "edited",+ issue: {+ number: 1,+ title: "Linked",+ body,+ html_url: "https://github.com/example/repo/issues/1",+ },+ changes: { body: { from: "Old body" } },+ installation: { id: 10 },+ repository: {+ id: 20,+ owner: { login: "example" },+ name: "repo",+ full_name: "example/repo",+ },+ });+}++describe("GitHub description round trip", () => {+ it("ignores the echoed body even after the two-second sync window", async () => {+ const task = await setup();+ await webhook(formatIssueBody(task.description, task.id));+ const stored = await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, task.id),+ });+ expect(stored?.description).toBe(task.description);+ expect(m.update).not.toHaveBeenCalled();+ });++ it("accepts a real GitHub edit without importing the generated footer", async () => {+ const task = await setup();+ await webhook(formatIssueBody("Edited on GitHub\n\nDetails", task.id));+ const stored = await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, task.id),+ });+ expect(stored?.description).toBe("Edited on GitHub\n\nDetails");+ expect(m.update).toHaveBeenCalledWith(+ "link",+ expect.objectContaining({+ metadata: expect.objectContaining({+ lastSync: expect.objectContaining({+ description: expect.objectContaining({+ source: "github",+ value: stored?.description,+ }),+ }),+ }),+ }),+ );+ });++ it("preserves a footer mentioning a different task", async () => {+ const task = await setup();+ const body = formatIssueBody("User content", "another-task");+ await webhook(body);+ const stored = await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, task.id),+ });+ expect(stored?.description).toBe(body);+ });+});diff --git a/tests/api-integration/github-import-bounds.test.ts b/tests/api-integration/github-import-bounds.test.tsnew file mode 100644index 000000000..2ad71ae15--- /dev/null+++ b/tests/api-integration/github-import-bounds.test.ts@@ -0,0 +1,632 @@+import { and, eq, sql } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { getDatabasePool, schema } from "../../apps/api/src/database";+import { importIssues } from "../../apps/api/src/github-integration/controllers/import-issues";+import { withGithubImportLock } from "../../apps/api/src/github-integration/import-lock";+import { IMPORT_PAGES_PER_REQUEST } from "../../apps/api/src/github-integration/import-pages";+import { createApp } from "../../apps/api/src/index";+import { handleIssueOpened } from "../../apps/api/src/plugins/github/webhooks/issue-opened";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const mocks = vi.hoisted(() => ({+ graphql: vi.fn(),+ verify: vi.fn(),+ comment: vi.fn(),+}));+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({+ getVerifiedInstallationOctokit: mocks.verify,+ getGithubApp: () => ({+ getInstallationOctokit: async () => ({+ rest: { issues: { createComment: mocks.comment } },+ }),+ }),+}));+const old = "2020-01-01T00:00:00Z";+function connection<T>(+ nodes: T[],+ more = false,+ cursor: string | null = null,+ totalCount = nodes.length,+) {+ return {+ nodes,+ totalCount,+ pageInfo: { hasNextPage: more, endCursor: cursor },+ };+}+function issue(number: number, options: Record<string, unknown> = {}) {+ return {+ number,+ title: `Issue ${number}`,+ body: "Description",+ url: `https://github.com/example/repo/issues/${number}`,+ state: "OPEN",+ createdAt: old,+ author: null,+ labels: connection([]),+ comments: connection([]),+ ...options,+ };+}+function comment(number: number, options: Record<string, unknown> = {}) {+ return {+ body: `Comment ${number}`,+ url: `https://github.com/example/repo/issues/1#issuecomment-${number}`,+ createdAt: old,+ author: {+ login: "contributor",+ avatarUrl: "https://avatars.githubusercontent.com/u/1",+ __typename: "User",+ },+ ...options,+ };+}+function label(number: number) {+ return { name: `label-${number}`, color: "abcdef" };+}+function issuePage(+ nodes: ReturnType<typeof issue>[],+ more = false,+ cursor: string | null = null,+ total = nodes.length,+) {+ return {+ repository: {+ databaseId: 2,+ issues: connection(nodes, more, cursor, total),+ },+ };+}+const emptyPulls = () => ({+ repository: { databaseId: 2, pullRequests: connection([]) },+});+function serveIssues(count: number) {+ mocks.graphql.mockImplementation(+ async (query: string, variables: { cursor: string | null }) => {+ if (query.includes("query ImportPullRequests(")) return emptyPulls();+ const number = Number(variables.cursor ?? 0) + 1;+ return issuePage([issue(number)], number < count, String(number), count);+ },+ );+}+function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}+beforeEach(async () => {+ await resetTestDatabase();+ mocks.graphql.mockReset();+ mocks.verify.mockReset().mockResolvedValue({ graphql: mocks.graphql });+ mocks.comment.mockReset();+});+async function setup() {+ const member = await createWorkspaceMember({ role: "admin" });+ const { project, columns } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const config = {+ repositoryOwner: "example",+ repositoryName: "repo",+ installationId: 1,+ repositoryId: 2,+ verifiedGithubAccountId: "3",+ verifiedByUserId: member.user.id,+ commentTaskLinkOnGitHubIssue: false,+ };+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: "github",+ isActive: true,+ config: JSON.stringify(config),+ })+ .returning();+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ const request = (runId?: string) =>+ app.request("/api/github-integration/import-issues", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ projectId: project.id,+ ...(runId ? { runId } : {}),+ }),+ });+ return { member, project, columns, integration, config, app, request };+}+async function saved() {+ return db.query.githubImportTable.findFirst();+}++describe("bounded resumable GitHub import", () => {+ it("bounds each HTTP step, persists resumable state, imports every issue and retries completion without restarting", async () => {+ const { request, app, project } = await setup();+ serveIssues(9);+ const first = await request();+ expect(first.status).toBe(202);+ const progress = await first.json();+ expect(progress).toMatchObject({+ pending: true,+ imported: IMPORT_PAGES_PER_REQUEST,+ updated: 0,+ });+ expect(mocks.graphql).toHaveBeenCalledTimes(IMPORT_PAGES_PER_REQUEST);+ const info = await app.request(+ `/api/github-integration/project/${project.id}`,+ );+ expect((await info.json()).importProgress).toEqual(progress);+ let response = await request(progress.runId);+ expect(response.status).toBe(202);+ response = await request(progress.runId);+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ pending: false,+ imported: 9,+ });+ expect(await db.query.taskTable.findMany()).toHaveLength(9);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(9);+ const calls = mocks.graphql.mock.calls.length;+ expect((await request(progress.runId)).status).toBe(200);+ expect(mocks.graphql).toHaveBeenCalledTimes(calls);+ expect(await db.query.githubImportTable.findMany()).toHaveLength(1);+ expect(mocks.verify).toHaveBeenCalledWith(expect.anything(), true);+ });++ it("resumes after provider failure without replaying committed pages or leaking provider errors", async () => {+ const { request, project } = await setup();+ serveIssues(7);+ const original = mocks.graphql.getMockImplementation();+ if (!original) throw new Error("Expected provider mock");+ mocks.graphql.mockImplementation(async (query, vars) => {+ if (vars.cursor === "2") throw new Error("private-token-provider-url");+ return original(query, vars);+ });+ const failed = await request();+ expect(failed.status).toBe(502);+ expect(await failed.text()).not.toContain("private-token");+ expect(await db.query.taskTable.findMany()).toHaveLength(2);+ expect((await saved())?.state).toMatchObject({+ imported: 2,+ issueCursor: "2",+ });+ mocks.graphql.mockImplementation(original);+ let result = await importIssues(project.id);+ while (result.pending)+ result = await importIssues(project.id, result.runId);+ expect(result).toMatchObject({ imported: 7, updated: 0 });+ expect(await db.query.taskTable.findMany()).toHaveLength(7);+ });++ it("processes all label and comment pages, applies late system labels and deduplicates comments on reimport", async () => {+ const { project, columns } = await setup();+ const labels = Array.from({ length: 27 }, (_, n) => label(n));+ labels[25] = { name: "status:in-progress", color: "ffffff" };+ labels[26] = { name: "priority:urgent", color: "ffffff" };+ const comments = Array.from({ length: 85 }, (_, n) => comment(n));+ comments[2] = comment(2, {+ author: {+ login: "robot",+ avatarUrl: "https://example.test/a",+ __typename: "Bot",+ },+ });+ comments[3] = comment(3, {+ author: {+ login: "robot[bot]",+ avatarUrl: "https://example.test/a",+ __typename: "User",+ },+ });+ comments[84] = comment(84, { createdAt: "2099-01-01T00:00:00Z" });+ mocks.graphql.mockImplementation(+ async (query: string, vars: { cursor: string | null }) => {+ if (query.includes("query ImportIssues("))+ return issuePage([+ issue(1, {+ labels: connection(labels.slice(0, 25), true, "25", 27),+ comments: connection(comments.slice(0, 20), true, "20", 85),+ }),+ ]);+ if (query.includes("query ImportIssueLabels("))+ return {+ repository: {+ databaseId: 2,+ issue: { labels: connection(labels.slice(25), false, "27", 27) },+ },+ };+ if (query.includes("query ImportIssueComments(")) {+ const offset = Number(vars.cursor);+ const end = Math.min(85, offset + 20);+ return {+ repository: {+ databaseId: 2,+ issue: {+ comments: connection(+ comments.slice(offset, end),+ end < 85,+ String(end),+ 85,+ ),+ },+ },+ };+ }+ return emptyPulls();+ },+ );+ let result = await importIssues(project.id);+ expect(result.pending).toBe(true);+ expect((await saved())?.state).toMatchObject({+ phase: "comments",+ currentIssue: { commentCursor: "60", labelsRemaining: 0 },+ });+ result = await importIssues(project.id, result.runId);+ expect(result.pending).toBe(false);+ expect(await db.query.labelTable.findMany()).toHaveLength(25);+ expect(await db.query.activityTable.findMany()).toHaveLength(82);+ expect(await db.query.taskTable.findFirst()).toMatchObject({+ priority: "urgent",+ status: "in-progress",+ columnId: columns.inProgress.id,+ });+ result = await importIssues(project.id);+ while (result.pending)+ result = await importIssues(project.id, result.runId);+ expect(result).toMatchObject({ imported: 0, updated: 1 });+ expect(await db.query.activityTable.findMany()).toHaveLength(82);+ expect(await db.query.labelTable.findMany()).toHaveLength(25);+ });++ it("does not chase comments added after the initial count or issues after the import boundary", async () => {+ const { project } = await setup();+ mocks.graphql.mockImplementation(async (query: string) => {+ if (query.includes("query ImportIssues("))+ return issuePage([+ issue(1, {+ comments: connection(+ Array.from({ length: 20 }, (_, n) => comment(n)),+ true,+ "20",+ 21,+ ),+ }),+ ]);+ if (query.includes("query ImportIssueComments("))+ return {+ repository: {+ databaseId: 2,+ issue: {+ comments: connection(+ Array.from({ length: 20 }, (_, n) => comment(20 + n)),+ true,+ "40",+ 99999,+ ),+ },+ },+ };+ return emptyPulls();+ });+ expect(await importIssues(project.id)).toMatchObject({+ pending: false,+ imported: 1,+ });+ expect(await db.query.activityTable.findMany()).toHaveLength(21);+ mocks.graphql.mockImplementation(async (query: string) =>+ query.includes("query ImportIssues(")+ ? issuePage(+ [issue(2, { createdAt: "2099-01-01T00:00:00Z" })],+ true,+ "2",+ 999,+ )+ : emptyPulls(),+ );+ expect(await importIssues(project.id)).toMatchObject({+ pending: false,+ imported: 0,+ });+ expect(await db.query.taskTable.findMany()).toHaveLength(1);+ });++ it("rolls back task, link, comments, number allocation and cursor together when saving progress fails", async () => {+ const { project } = await setup();+ serveIssues(1);+ await db.execute(+ sql.raw(+ `CREATE FUNCTION fail_import_progress() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test failure'; END $$`,+ ),+ );+ await db.execute(+ sql.raw(+ "CREATE TRIGGER fail_import_progress BEFORE UPDATE ON github_import FOR EACH ROW EXECUTE FUNCTION fail_import_progress()",+ ),+ );+ try {+ await expect(importIssues(project.id)).rejects.toThrow();+ expect(await db.query.taskTable.findMany()).toHaveLength(0);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(0);+ expect((await saved())?.state).toMatchObject({+ phase: "issues",+ issueCursor: null,+ imported: 0,+ });+ expect(await db.query.projectTable.findFirst()).toMatchObject({+ lastTaskNumber: 0,+ });+ } finally {+ await db.execute(+ sql.raw("DROP TRIGGER fail_import_progress ON github_import"),+ );+ await db.execute(sql.raw("DROP FUNCTION fail_import_progress()"));+ }+ expect(await importIssues(project.id)).toMatchObject({+ imported: 1,+ pending: false,+ });+ expect(await db.query.taskTable.findFirst()).toMatchObject({ number: 1 });+ });++ it("rechecks workspace access on every continuation and keeps state scoped to its integration", async () => {+ const { request, project, app } = await setup();+ serveIssues(7);+ const first = await (await request()).json();+ const calls = mocks.graphql.mock.calls.length;+ const other = await createWorkspaceMember({ role: "admin" });+ mockAuthenticatedSession(other.user);+ expect((await request(first.runId)).status).toBe(403);+ expect(+ (await app.request(`/api/github-integration/project/${project.id}`))+ .status,+ ).toBe(403);+ expect(mocks.graphql).toHaveBeenCalledTimes(calls);+ });++ it("rejects wrong run IDs and changed repository identities without consuming old cursors", async () => {+ const { project, integration, config } = await setup();+ serveIssues(7);+ const first = await importIssues(project.id);+ await expect(+ importIssues(project.id, "not-this-run"),+ ).rejects.toMatchObject({ status: 409 });+ await db+ .update(schema.integrationTable)+ .set({ config: JSON.stringify({ ...config, repositoryId: 22 }) })+ .where(eq(schema.integrationTable.id, integration.id));+ await expect(importIssues(project.id, first.runId)).rejects.toMatchObject({+ status: 409,+ });+ expect(mocks.graphql).toHaveBeenCalledTimes(4);+ });++ it("does not commit a fetched page after the integration is disabled", async () => {+ const { project, integration } = await setup();+ mocks.graphql.mockImplementation(async () => {+ await db+ .update(schema.integrationTable)+ .set({ isActive: false })+ .where(eq(schema.integrationTable.id, integration.id));+ return issuePage([issue(1)]);+ });+ await expect(importIssues(project.id)).rejects.toMatchObject({+ status: 409,+ });+ expect(await db.query.taskTable.findMany()).toHaveLength(0);+ });++ it.each(["identity", "cursor", "oversized"])(+ "rejects invalid provider %s without advancing saved progress",+ async (kind) => {+ const { project } = await setup();+ mocks.graphql.mockResolvedValue(+ kind === "identity"+ ? {+ ...issuePage([issue(1)]),+ repository: {+ ...issuePage([issue(1)]).repository,+ databaseId: 99,+ },+ }+ : kind === "cursor"+ ? issuePage([issue(1)], true, null)+ : issuePage([issue(1), issue(2)]),+ );+ await expect(importIssues(project.id)).rejects.toMatchObject({+ status: kind === "identity" ? 409 : 502,+ });+ expect((await saved())?.state.imported).toBe(0);+ expect(await db.query.taskTable.findMany()).toHaveLength(0);+ },+ );++ it("pauses on an empty unfinished page instead of silently dropping remaining issues", async () => {+ const { project } = await setup();+ mocks.graphql.mockResolvedValue(issuePage([], true, "next", 10));+ await expect(importIssues(project.id)).rejects.toMatchObject({+ status: 502,+ });+ expect((await saved())?.state).toMatchObject({+ imported: 0,+ issueCursor: null,+ });+ });++ it("does not loop on a repeated cursor and retains earlier pages", async () => {+ const { project } = await setup();+ mocks.graphql.mockResolvedValue(issuePage([issue(1)], true, "same", 100));+ await expect(importIssues(project.id)).rejects.toMatchObject({+ status: 502,+ });+ expect(mocks.graphql).toHaveBeenCalledTimes(2);+ expect((await saved())?.state).toMatchObject({+ imported: 1,+ issueCursor: "same",+ });+ expect(await db.query.taskTable.findMany()).toHaveLength(1);+ });++ it("finishes a disappeared source without losing other issues or modifying another project's task", async () => {+ const { project } = await setup();+ mocks.graphql.mockImplementation(+ async (query: string, vars: { cursor: string | null }) => {+ if (query.includes("query ImportIssues("))+ return vars.cursor+ ? issuePage([issue(2)])+ : issuePage(+ [+ issue(1, {+ comments: connection([comment(1)], true, "first", 100),+ }),+ ],+ true,+ "1",+ 2,+ );+ if (query.includes("query ImportIssueComments("))+ return { repository: { databaseId: 2, issue: null } };+ return emptyPulls();+ },+ );+ expect(await importIssues(project.id)).toMatchObject({+ pending: false,+ imported: 2,+ skipped: 1,+ });+ expect(await db.query.taskTable.findMany()).toHaveLength(2);+ });++ it("deleting an integration removes its saved progress but preserves imported tasks", async () => {+ const { project, integration } = await setup();+ serveIssues(8);+ await importIssues(project.id);+ await db+ .delete(schema.integrationTable)+ .where(eq(schema.integrationTable.id, integration.id));+ expect(await saved()).toBeUndefined();+ expect(await db.query.taskTable.findMany()).toHaveLength(4);+ });++ it("limits simultaneous imports across processes and releases slots after failure", async () => {+ const client = await getDatabasePool().connect();+ await client.query(+ "SELECT pg_advisory_lock(773623, 0), pg_advisory_lock(773623, 1)",+ );+ try {+ await expect(+ withGithubImportLock("any", async () => {}),+ ).rejects.toMatchObject({ status: 429 });+ } finally {+ await client.query("SELECT pg_advisory_unlock_all()");+ client.release();+ }+ await expect(+ withGithubImportLock("any", async () => {+ throw new Error("failed");+ }),+ ).rejects.toThrow("failed");+ expect(await withGithubImportLock("any", async () => "free")).toBe("free");+ });++ it("rejects overlapping steps for one project and permits later continuation", async () => {+ const { project, request } = await setup();+ serveIssues(1);+ const gate = deferred();+ const started = deferred();+ const original = mocks.graphql.getMockImplementation();+ if (!original) throw new Error("Expected provider mock");+ mocks.graphql.mockImplementation(async (query, vars) => {+ started.resolve();+ await gate.promise;+ return original(query, vars);+ });+ const first = importIssues(project.id);+ await started.promise;+ try {+ const busy = await request();+ expect(busy.status).toBe(429);+ expect(busy.headers.get("Retry-After")).toBe("1");+ } finally {+ gate.resolve();+ }+ expect(await first).toMatchObject({ pending: false, imported: 1 });+ });++ it("coordinates webhook creation with imports so both paths create only one task and link", async () => {+ const { project } = await setup();+ serveIssues(1);+ const payload = {+ action: "opened",+ installation: { id: 1 },+ repository: {+ id: 2,+ owner: { login: "example" },+ name: "repo",+ full_name: "example/repo",+ },+ issue: {+ number: 1,+ title: "Issue 1",+ body: "Description",+ html_url: "https://github.com/example/repo/issues/1",+ user: null,+ },+ };+ await Promise.all([+ importIssues(project.id),+ handleIssueOpened(payload),+ handleIssueOpened(payload),+ ]);+ expect(await db.query.taskTable.findMany()).toHaveLength(1);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(1);+ expect(mocks.comment).not.toHaveBeenCalled();+ });++ it("continues all pull request pages and links only matching tasks in this project", async () => {+ const { project, integration } = await setup();+ mocks.graphql.mockImplementation(+ async (query: string, vars: { cursor: string | null }) => {+ if (query.includes("query ImportIssues(")) return issuePage([issue(1)]);+ const offset = Number(vars.cursor ?? 0);+ const end = Math.min(25, offset + 10);+ const pulls = Array.from({ length: end - offset }, (_, index) => ({+ number: offset + index + 1,+ title: `${project.slug.toUpperCase()}-1`,+ body: null,+ url: `https://github.com/example/repo/pull/${offset + index + 1}`,+ state: "OPEN",+ createdAt: old,+ headRefName: `${project.slug.toLowerCase()}-1`,+ author: null,+ }));+ return {+ repository: {+ databaseId: 2,+ pullRequests: connection(pulls, end < 25, String(end), 25),+ },+ };+ },+ );+ const result = await importIssues(project.id);+ expect(result.pending).toBe(false);+ expect(+ await db+ .select()+ .from(schema.externalLinkTable)+ .where(+ and(+ eq(schema.externalLinkTable.resourceType, "pull_request"),+ eq(schema.externalLinkTable.integrationId, integration.id),+ ),+ ),+ ).toHaveLength(25);+ });+});diff --git a/tests/api-integration/github-import-status.test.ts b/tests/api-integration/github-import-status.test.tsnew file mode 100644index 000000000..e9efd2358--- /dev/null+++ b/tests/api-integration/github-import-status.test.ts@@ -0,0 +1,195 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { importIssues } from "../../apps/api/src/github-integration/controllers/import-issues";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const m = vi.hoisted(() => ({ labels: [] as string[] }));+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({+ getVerifiedInstallationOctokit: async () => ({+ graphql: async (query: string) => ({+ repository: {+ databaseId: 2,+ ...(query.includes("query ImportIssues(")+ ? {+ issues: {+ totalCount: 1,+ pageInfo: { hasNextPage: false, endCursor: "issue-1" },+ nodes: [+ {+ number: 1,+ title: "Imported",+ body: "Description",+ url: "https://github.com/example/repo/issues/1",+ state: "OPEN",+ createdAt: "2020-01-01T00:00:00Z",+ author: null,+ labels: {+ totalCount: m.labels.length,+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: m.labels.map((name) => ({+ name,+ color: "ffffff",+ })),+ },+ comments: {+ totalCount: 0,+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: [],+ },+ },+ ],+ },+ }+ : {+ pullRequests: {+ totalCount: 0,+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: [],+ },+ }),+ },+ }),+ }),+}));+beforeEach(async () => {+ await resetTestDatabase();+ m.labels = [];+});+async function setup() {+ const { user, workspace } = await createWorkspaceMember();+ const { project, columns } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: "github",+ isActive: true,+ config: JSON.stringify({+ repositoryOwner: "example",+ repositoryName: "repo",+ installationId: 1,+ repositoryId: 2,+ verifiedGithubAccountId: "3",+ verifiedByUserId: user.id,+ }),+ })+ .returning();+ return { project, columns, integration, workspace };+}+async function storedTask() {+ return db.query.taskTable.findFirst();+}++describe("GitHub import project workflow validation", () => {+ it("maps arbitrary external statuses to a real local column for new tasks", async () => {+ const { project, columns } = await setup();+ m.labels = ["status:hidden"];+ expect(await importIssues(project.id)).toMatchObject({ imported: 1 });+ expect(await storedTask()).toMatchObject({+ status: "to-do",+ columnId: columns.todo.id,+ });+ });++ it("preserves an existing valid status when reimport has an unknown label", async () => {+ const { project, columns } = await setup();+ m.labels = ["status:in-progress"];+ await importIssues(project.id);+ m.labels = ["status:hidden"];+ expect(await importIssues(project.id)).toMatchObject({ updated: 1 });+ expect(await storedTask()).toMatchObject({+ status: "in-progress",+ columnId: columns.inProgress.id,+ });+ });++ it("uses custom columns belonging to the imported project and updates columnId together", async () => {+ const { project, columns } = await setup();+ await db+ .update(schema.columnTable)+ .set({ slug: "ready", name: "Ready" })+ .where(eq(schema.columnTable.id, columns.todo.id));+ m.labels = ["status:hidden"];+ await importIssues(project.id);+ expect(await storedTask()).toMatchObject({+ status: "ready",+ columnId: columns.todo.id,+ });+ m.labels = ["status:in-review"];+ await importIssues(project.id);+ expect(await storedTask()).toMatchObject({+ status: "in-review",+ columnId: columns.inReview.id,+ });+ });++ it.each(["planned", "archived"])(+ "allows virtual status %s and clears the old column",+ async (status) => {+ const { project } = await setup();+ await importIssues(project.id);+ m.labels = [`status:${status}`];+ await importIssues(project.id);+ expect(await storedTask()).toMatchObject({ status, columnId: null });+ },+ );++ it("uses planned without workflow columns and repairs an invalid legacy status on reimport", async () => {+ const { project } = await setup();+ await db+ .delete(schema.columnTable)+ .where(eq(schema.columnTable.projectId, project.id));+ await importIssues(project.id);+ expect(await storedTask()).toMatchObject({+ status: "planned",+ columnId: null,+ });+ const task = await storedTask();+ if (!task) throw new Error("Expected imported task");+ await db+ .update(schema.taskTable)+ .set({ status: "hidden" })+ .where(eq(schema.taskTable.id, task.id));+ m.labels = ["status:hidden"];+ await importIssues(project.id);+ expect(await storedTask()).toMatchObject({+ status: "planned",+ columnId: null,+ });+ });++ it("does not mutate another project's task through a legacy external link", async () => {+ const { project, integration, workspace } = await setup();+ const { project: other } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({ projectId: other.id, title: "Untouched", number: 1 })+ .returning();+ await db.insert(schema.externalLinkTable).values({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: "1",+ url: "https://github.com/example/repo/issues/1",+ });+ m.labels = ["status:archived"];+ expect(await importIssues(project.id)).toMatchObject({+ imported: 0,+ updated: 0,+ skipped: 1,+ });+ expect(await storedTask()).toMatchObject({+ title: "Untouched",+ status: "to-do",+ });+ });+});diff --git a/tests/api-integration/github-rebind.test.ts b/tests/api-integration/github-rebind.test.tsnew file mode 100644index 000000000..36d7bf253--- /dev/null+++ b/tests/api-integration/github-rebind.test.ts@@ -0,0 +1,205 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import createIntegration from "../../apps/api/src/github-integration/controllers/create-github-integration";+import deleteIntegration from "../../apps/api/src/github-integration/controllers/delete-github-integration";+import { initialImportState } from "../../apps/api/src/github-integration/import-state";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const { verify } = vi.hoisted(() => ({ verify: vi.fn() }));+vi.mock(+ "../../apps/api/src/github-integration/controllers/verify-repository-owner",+ () => ({ verifyRepositoryOwner: verify }),+);+beforeEach(async () => {+ await resetTestDatabase();+ verify.mockReset();+});+async function setup() {+ const member = await createWorkspaceMember({ role: "admin" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const config = {+ repositoryOwner: "owner",+ repositoryName: "repo",+ installationId: 1,+ repositoryId: 2,+ verifiedGithubAccountId: "3",+ verifiedByUserId: member.user.id,+ branchPattern: "feature/{slug}-{number}",+ commentTaskLinkOnGitHubIssue: false,+ };+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: "github",+ isActive: true,+ config: JSON.stringify(config),+ })+ .returning();+ const [task] = await db+ .insert(schema.taskTable)+ .values({ projectId: project.id, title: "Existing task", number: 1 })+ .returning();+ const [link] = await db+ .insert(schema.externalLinkTable)+ .values({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: "1",+ url: "https://github.com/owner/repo/issues/1",+ })+ .returning();+ await db+ .insert(schema.githubImportTable)+ .values({ integrationId: integration.id, state: initialImportState(2) });+ verify.mockResolvedValue({+ repositoryOwner: "owner",+ repositoryName: "repo",+ repositoryId: 2,+ installationId: 1,+ verifiedGithubAccountId: "3",+ verifiedByUserId: member.user.id,+ });+ const connect = () =>+ createIntegration({+ userId: member.user.id,+ projectId: project.id,+ repositoryOwner: "owner",+ repositoryName: "repo",+ });+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ return { project, config, integration, task, link, connect, app };+}++describe("GitHub repository changes preserve link ownership", () => {+ it("rejects a different numeric repository even when its name is identical", async () => {+ const { integration, config, link, connect } = await setup();+ verify.mockResolvedValue({ ...config, repositoryId: 99 });+ await expect(connect()).rejects.toMatchObject({ status: 409 });+ expect(await db.query.integrationTable.findFirst()).toMatchObject({+ id: integration.id,+ config: integration.config,+ });+ expect(await db.query.externalLinkTable.findFirst()).toMatchObject(link);+ expect(await db.query.githubImportTable.findFirst()).toBeDefined();+ });+ it("preserves links, pending imports and settings when the same repository is renamed or reinstalled", async () => {+ const { config, integration, link, connect } = await setup();+ verify.mockResolvedValue({+ repositoryOwner: "new-owner",+ repositoryName: "renamed",+ repositoryId: 2,+ installationId: 88,+ verifiedGithubAccountId: "3",+ verifiedByUserId: config.verifiedByUserId,+ });+ expect(await connect()).toMatchObject({+ id: integration.id,+ repositoryName: "renamed",+ installationId: 88,+ });+ expect(+ JSON.parse((await db.query.integrationTable.findFirst())?.config ?? "{}"),+ ).toMatchObject({+ branchPattern: config.branchPattern,+ commentTaskLinkOnGitHubIssue: false,+ repositoryId: 2,+ });+ expect(await db.query.externalLinkTable.findFirst()).toMatchObject(link);+ expect(await db.query.githubImportTable.findFirst()).toBeDefined();+ });+ it("allows administrator reverification of a matching legacy name, but requires disconnect for a different name", async () => {+ const { config, integration, connect } = await setup();+ const legacy = {+ repositoryOwner: "OWNER",+ repositoryName: "REPO",+ installationId: 1,+ };+ await db+ .update(schema.integrationTable)+ .set({ config: JSON.stringify(legacy) })+ .where(eq(schema.integrationTable.id, integration.id));+ verify.mockResolvedValue({ ...config, repositoryName: "another" });+ await expect(connect()).rejects.toMatchObject({ status: 409 });+ verify.mockResolvedValue(config);+ await expect(connect()).resolves.toMatchObject({ id: integration.id });+ });+ it("requires an explicit disconnect when an existing configuration cannot establish repository identity", async () => {+ const { integration, connect } = await setup();+ await db+ .update(schema.integrationTable)+ .set({ config: "invalid" })+ .where(eq(schema.integrationTable.id, integration.id));+ await expect(connect()).rejects.toMatchObject({ status: 409 });+ expect(await db.query.externalLinkTable.findFirst()).toBeDefined();+ });+ it("permits switching after disconnect without reusing old links or import cursors", async () => {+ const { project, config, integration, task, connect } = await setup();+ await deleteIntegration(project.id);+ verify.mockResolvedValue({+ ...config,+ repositoryId: 99,+ repositoryName: "other",+ });+ const next = await connect();+ expect(next.id).not.toBe(integration.id);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(0);+ expect(await db.query.githubImportTable.findMany()).toHaveLength(0);+ expect(await db.query.taskTable.findFirst()).toMatchObject({ id: task.id });+ });+ it.each(["reconnect", "settings"])(+ "rejects a concurrent repository change during %s instead of overwriting the new binding",+ async (operation) => {+ const { project, config, integration, connect, app } = await setup();+ const nextConfig = JSON.stringify({+ ...config,+ repositoryId: 99,+ repositoryName: "new",+ });+ const find = db.query.integrationTable.findFirst.bind(+ db.query.integrationTable,+ );+ const spy = vi+ .spyOn(db.query.integrationTable, "findFirst")+ .mockImplementationOnce(async (...args) => {+ const row = await find(...args);+ await db+ .update(schema.integrationTable)+ .set({ config: nextConfig })+ .where(eq(schema.integrationTable.id, integration.id));+ return row;+ });+ try {+ if (operation === "reconnect")+ await expect(connect()).rejects.toMatchObject({ status: 409 });+ else {+ const response = await app.request(+ `/api/github-integration/project/${project.id}`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ commentTaskLinkOnGitHubIssue: true }),+ },+ );+ expect(response.status).toBe(409);+ }+ } finally {+ spy.mockRestore();+ }+ expect((await db.query.integrationTable.findFirst())?.config).toBe(+ nextConfig,+ );+ },+ );+});diff --git a/tests/api-integration/label-deletion-bounds.test.ts b/tests/api-integration/label-deletion-bounds.test.tsnew file mode 100644index 000000000..0eb75b309--- /dev/null+++ b/tests/api-integration/label-deletion-bounds.test.ts@@ -0,0 +1,325 @@+import { and, eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { getDatabasePool, schema } from "../../apps/api/src/database";+import { subscribeToEvent } from "../../apps/api/src/events";+import { createApp } from "../../apps/api/src/index";+import deleteLabel, {+ LABEL_DELETE_BATCH_SIZE,+} from "../../apps/api/src/label/controllers/delete-label";+import {+ MAX_LABEL_DELETIONS_IN_FLIGHT,+ withLabelDeletionLock,+} from "../../apps/api/src/label/deletion-lock";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const { github, gitea } = vi.hoisted(() => ({+ github: vi.fn(async (_id: string, _name: string) => {}),+ gitea: vi.fn(async (_id: string, _name: string) => {}),+}));+vi.mock("../../apps/api/src/plugins/github/utils/sync-label-to-github", () => ({+ removeLabelFromGitHub: github,+ syncLabelToGitHub: vi.fn(),+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/sync-label-to-gitea", () => ({+ removeLabelFromGitea: gitea,+ syncLabelToGitea: vi.fn(),+}));++let eventGate: Promise<void> | undefined;+let eventCalls: string[] = [];+await subscribeToEvent<{ taskId: string }>(+ "task.label_deleted",+ async (data) => {+ eventCalls.push(data.taskId);+ await eventGate;+ },+);+function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}+beforeEach(async () => {+ await resetTestDatabase();+ github.mockReset().mockResolvedValue();+ gitea.mockReset().mockResolvedValue();+ eventGate = undefined;+ eventCalls = [];+});+async function fixture(count: number) {+ const member = await createWorkspaceMember({ role: "admin" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [root] = await db+ .insert(schema.labelTable)+ .values({ workspaceId: member.workspace.id, name: "bug", color: "red" })+ .returning();+ const tasks = count+ ? await db+ .insert(schema.taskTable)+ .values(+ Array.from({ length: count }, (_, i) => ({+ projectId: project.id,+ title: `Task ${i}`,+ status: "to-do",+ number: i + 1,+ })),+ )+ .returning()+ : [];+ if (tasks.length)+ await db.insert(schema.labelTable).values(+ tasks.map((task) => ({+ workspaceId: member.workspace.id,+ taskId: task.id,+ name: "bug",+ color: "red",+ })),+ );+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ return { member, project, root, tasks, app };+}+async function labelsFor(workspaceId: string) {+ return db+ .select()+ .from(schema.labelTable)+ .where(eq(schema.labelTable.workspaceId, workspaceId));+}++describe("bounded, resumable label deletion", () => {+ it("finishes all copies through bounded HTTP steps and keeps the root until completion", async () => {+ const { app, member, root } = await fixture(+ LABEL_DELETE_BATCH_SIZE * 2 + 3,+ );+ const first = await app.request(`/api/label/${root.id}`, {+ method: "DELETE",+ });+ expect(first.status).toBe(202);+ expect(await first.json()).toMatchObject({+ id: root.id,+ pendingDeletion: true,+ });+ expect(github).toHaveBeenCalledTimes(LABEL_DELETE_BATCH_SIZE);+ expect(gitea).toHaveBeenCalledTimes(LABEL_DELETE_BATCH_SIZE);+ expect(eventCalls).toHaveLength(LABEL_DELETE_BATCH_SIZE);+ const remaining = await labelsFor(member.workspace.id);+ expect(remaining).toHaveLength(LABEL_DELETE_BATCH_SIZE + 4);+ const marker = remaining.find(+ (label) => label.id === root.id,+ )?.deletionStartedAt;+ expect(marker).toBeInstanceOf(Date);+ // A fresh app/request resumes persisted state, without an in-memory cursor.+ const second = await createApp().app.request(`/api/label/${root.id}`, {+ method: "DELETE",+ });+ expect(second.status).toBe(202);+ expect(+ (await labelsFor(member.workspace.id)).find(+ (label) => label.id === root.id,+ )?.deletionStartedAt,+ ).toEqual(marker);+ expect(+ (await app.request(`/api/label/${root.id}`, { method: "DELETE" })).status,+ ).toBe(200);+ expect(await labelsFor(member.workspace.id)).toEqual([]);+ expect(github).toHaveBeenCalledTimes(LABEL_DELETE_BATCH_SIZE * 2 + 3);+ expect(new Set(eventCalls).size).toBe(eventCalls.length);+ });+ it("does not start the next provider operation until the current one resolves", async () => {+ const { member, root } = await fixture(3);+ const gate = deferred();+ github.mockImplementationOnce(async () => gate.promise);+ const pending = deleteLabel(root.id, member.user.id);+ try {+ await vi.waitFor(() => expect(github).toHaveBeenCalledTimes(1));+ expect(gitea).not.toHaveBeenCalled();+ expect(eventCalls).toHaveLength(0);+ await expect(deleteLabel(root.id, member.user.id)).rejects.toMatchObject({+ status: 429,+ });+ } finally {+ gate.resolve();+ }+ await pending;+ expect(github).toHaveBeenCalledTimes(3);+ expect(gitea).toHaveBeenCalledTimes(3);+ });+ it("awaits real asynchronous event subscribers before deleting another copy", async () => {+ const { member, root } = await fixture(3);+ const gate = deferred();+ eventGate = gate.promise;+ const pending = deleteLabel(root.id, member.user.id);+ try {+ await vi.waitFor(() => expect(eventCalls).toHaveLength(1));+ expect(github).toHaveBeenCalledTimes(1);+ expect(await labelsFor(member.workspace.id)).toHaveLength(3); // root plus two copies+ } finally {+ gate.resolve();+ }+ await pending;+ expect(eventCalls).toHaveLength(3);+ });+ it("preserves task labels created after the persisted deletion boundary", async () => {+ const { member, root, tasks } = await fixture(LABEL_DELETE_BATCH_SIZE + 1);+ expect((await deleteLabel(root.id, member.user.id)).pendingDeletion).toBe(+ true,+ );+ const deletedTask = github.mock.calls[0][0];+ const [newLabel] = await db+ .insert(schema.labelTable)+ .values({+ workspaceId: member.workspace.id,+ taskId: deletedTask,+ name: "bug",+ color: "blue",+ createdAt: new Date(Date.now() + 1000),+ })+ .returning();+ await deleteLabel(root.id, member.user.id);+ expect(await labelsFor(member.workspace.id)).toEqual([newLabel]);+ expect(github).toHaveBeenCalledTimes(tasks.length);+ });+ it("prevents root renaming and reassignment while a deletion is pending", async () => {+ const { app, member, root, tasks } = await fixture(+ LABEL_DELETE_BATCH_SIZE + 1,+ );+ await deleteLabel(root.id, member.user.id);+ for (const [path, method, body] of [+ [`/api/label/${root.id}`, "PUT", { name: "renamed", color: "blue" }],+ [`/api/label/${root.id}/task`, "PUT", { taskId: tasks[0].id }],+ [+ "/api/label",+ "POST",+ {+ workspaceId: member.workspace.id,+ name: "bug",+ color: "red",+ taskId: tasks[0].id,+ },+ ],+ ] as const)+ expect(+ (+ await app.request(path, {+ method,+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ })+ ).status,+ ).toBe(409);+ expect(+ (await labelsFor(member.workspace.id)).find(+ (label) => label.id === root.id,+ )?.name,+ ).toBe("bug");+ });+ it("completes an empty cascade without provider calls or events", async () => {+ const { member, root } = await fixture(0);+ expect(+ (await deleteLabel(root.id, member.user.id)).pendingDeletion,+ ).toBeUndefined();+ expect(await labelsFor(member.workspace.id)).toHaveLength(0);+ expect(github).not.toHaveBeenCalled();+ expect(gitea).not.toHaveBeenCalled();+ expect(eventCalls).toHaveLength(0);+ });+ it("removes individual task labels with both providers and an awaited event", async () => {+ const { member, root, tasks } = await fixture(1);+ const [copy] = await db+ .select()+ .from(schema.labelTable)+ .where(+ and(+ eq(schema.labelTable.taskId, tasks[0].id),+ eq(schema.labelTable.workspaceId, member.workspace.id),+ ),+ );+ await deleteLabel(copy.id, member.user.id);+ expect((await labelsFor(member.workspace.id)).map((row) => row.id)).toEqual(+ [root.id],+ );+ expect(github).toHaveBeenCalledWith(tasks[0].id, "bug");+ expect(gitea).toHaveBeenCalledWith(tasks[0].id, "bug");+ expect(eventCalls).toEqual([tasks[0].id]);+ });+ it("releases process and database capacity after an operation fails", async () => {+ await expect(+ withLabelDeletionLock("failure", async () => {+ throw new Error("test failure");+ }),+ ).rejects.toThrow("test failure");+ await expect(+ withLabelDeletionLock("failure", async () => "ok"),+ ).resolves.toBe("ok");+ });+ it("honors the four-slot cap held by a separate database session", async () => {+ const { app, member, root } = await fixture(0);+ const other = await getDatabasePool().connect();+ try {+ for (let i = 0; i < MAX_LABEL_DELETIONS_IN_FLIGHT; i++)+ await other.query("SELECT pg_advisory_lock(773622, $1::int)", [i]);+ await expect(+ withLabelDeletionLock("blocked", async () => "must not run"),+ ).rejects.toMatchObject({ status: 429 });+ const response = await app.request(`/api/label/${root.id}`, {+ method: "DELETE",+ });+ expect(response.status).toBe(429);+ expect(response.headers.get("Retry-After")).toBe("1");+ expect(+ (await labelsFor(member.workspace.id))[0].deletionStartedAt,+ ).toBeNull();+ } finally {+ await other.query("SELECT pg_advisory_unlock_all()");+ other.release();+ }+ await expect(+ withLabelDeletionLock("available", async () => "ok"),+ ).resolves.toBe("ok");+ });++ it("checks workspace access again when another client tries to resume", async () => {+ const { app, member, root } = await fixture(LABEL_DELETE_BATCH_SIZE + 1);+ expect(+ (await app.request(`/api/label/${root.id}`, { method: "DELETE" })).status,+ ).toBe(202);+ const other = await createWorkspaceMember({ role: "admin" });+ mockAuthenticatedSession(other.user);+ expect(+ (await app.request(`/api/label/${root.id}`, { method: "DELETE" })).status,+ ).toBe(403);+ expect(await labelsFor(member.workspace.id)).toHaveLength(2);+ expect(github).toHaveBeenCalledTimes(LABEL_DELETE_BATCH_SIZE);+ mockAuthenticatedSession(member.user);+ expect(+ (await app.request(`/api/label/${root.id}`, { method: "DELETE" })).status,+ ).toBe(200);+ });++ it("does not lose local progress or the next event when a provider fails", async () => {+ const { member, root } = await fixture(3);+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ github.mockRejectedValueOnce(new Error("provider unavailable"));+ try {+ await deleteLabel(root.id, member.user.id);+ expect(await labelsFor(member.workspace.id)).toHaveLength(0);+ expect(github).toHaveBeenCalledTimes(3);+ expect(gitea).toHaveBeenCalledTimes(3);+ expect(eventCalls).toHaveLength(3);+ expect(log).toHaveBeenCalledWith(+ "Failed to synchronize a label removal with an external provider",+ );+ } finally {+ log.mockRestore();+ }+ });+});diff --git a/tests/api-integration/legacy-auth-migration.test.ts b/tests/api-integration/legacy-auth-migration.test.tsnew file mode 100644index 000000000..b48134890--- /dev/null+++ b/tests/api-integration/legacy-auth-migration.test.ts@@ -0,0 +1,101 @@+import { readFileSync } from "node:fs";+import { eq, sql } from "drizzle-orm";+import { beforeEach, describe, expect, it } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const repair = readFileSync(+ new URL(+ "../../apps/api/drizzle/0047_repair_legacy_auth_ownership.sql",+ import.meta.url,+ ),+ "utf8",+);+beforeEach(async () => {+ await resetTestDatabase();+});++describe("legacy ownership and archival migration", () => {+ it("repairs the old comment-only schema, retains valid keys and invalidates orphaned credentials", async () => {+ const { user, workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ await db.transaction(async (tx) => {+ // Model an already-applied old0015 journal: archived_at absent, ownership+ // constraints never installed. All DDL is isolated to this transaction.+ await tx.execute(sql`ALTER TABLE project DROP COLUMN archived_at`);+ await tx.execute(+ sql`ALTER TABLE apikey DROP CONSTRAINT apikey_reference_id_user_id_fk`,+ );+ await tx.execute(+ sql`ALTER TABLE apikey ALTER COLUMN reference_id DROP NOT NULL`,+ );+ await tx.execute(sql`+ INSERT INTO apikey (id, key, user_id, reference_id, created_at, updated_at)+ VALUES ('legacy', 'legacy-hash', ${user.id}, null, now(), now()),+ ('modern', 'modern-hash', null, ${user.id}, now(), now()),+ ('orphan', 'orphan-hash', null, 'deleted-user', now(), now()),+ ('missing', 'missing-hash', null, null, now(), now()),+ ('contradictory', 'invalid-reference-hash', ${user.id}, 'deleted-user', now(), now())+ `);+ await tx.execute(sql.raw(repair));+ await tx.execute(sql.raw(repair));+ const keys = await tx+ .select({+ id: schema.apikeyTable.id,+ key: schema.apikeyTable.key,+ referenceId: schema.apikeyTable.referenceId,+ })+ .from(schema.apikeyTable);+ expect(keys).toEqual(+ expect.arrayContaining([+ { id: "legacy", key: "legacy-hash", referenceId: user.id },+ { id: "modern", key: "modern-hash", referenceId: user.id },+ ]),+ );+ expect(keys).toHaveLength(2);+ const [archived] = await tx+ .update(schema.projectTable)+ .set({ archivedAt: new Date("2026-09-19") })+ .where(eq(schema.projectTable.id, project.id))+ .returning();+ expect(archived.archivedAt).toEqual(new Date("2026-09-19"));+ await tx.delete(schema.userTable).where(eq(schema.userTable.id, user.id));+ expect(await tx.select().from(schema.apikeyTable)).toHaveLength(0);+ });+ });++ it.each([null, "nonexistent-user"])(+ "rejects invalid ownership after all fresh migrations: %s",+ async (owner) => {+ await expect(+ db.execute(+ sql`INSERT INTO apikey (id, key, reference_id, created_at, updated_at) VALUES ('bad', 'bad-hash', ${owner}, now(), now())`,+ ),+ ).rejects.toThrow();+ },+ );++ it("preserves an already archived project on repeat application", async () => {+ const { workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const date = new Date("2026-01-01T12:00:00.000Z");+ await db+ .update(schema.projectTable)+ .set({ archivedAt: date })+ .where(eq(schema.projectTable.id, project.id));+ await db.execute(sql.raw(repair));+ expect(+ await db.query.projectTable.findFirst({+ where: eq(schema.projectTable.id, project.id),+ }),+ ).toHaveProperty("archivedAt", date);+ });+});diff --git a/tests/api-integration/mcp-oauth-bounds.test.ts b/tests/api-integration/mcp-oauth-bounds.test.tsnew file mode 100644index 000000000..c075cf11c--- /dev/null+++ b/tests/api-integration/mcp-oauth-bounds.test.ts@@ -0,0 +1,168 @@+import { createHash } from "node:crypto";+import { and, count, eq } from "drizzle-orm";+import { beforeEach, describe, expect, it } from "vitest";+import db from "../../apps/api/src/database";+import { mcpOauthStateTable } from "../../apps/api/src/database/schema";+import mcp from "../../apps/api/src/mcp";+import {+ createAuthorizationRequest,+ getAuthorizationRequest,+ registerClient,+} from "../../apps/api/src/mcp/oauth";+import { OAUTH_STATE_LIMITS } from "../../apps/api/src/mcp/oauth-store";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import { createWorkspaceMember } from "./helpers/fixtures";++const redirectUri = "https://client.example/callback";+const challenge = createHash("sha256")+ .update("test-verifier")+ .digest("base64url");+beforeEach(async () => {+ await resetTestDatabase();+});+async function total(kind: string) {+ const [row] = await db+ .select({ total: count() })+ .from(mcpOauthStateTable)+ .where(eq(mcpOauthStateTable.kind, kind));+ return row.total;+}+function post(+ path: string,+ body: unknown,+ headers: Record<string, string> = {},+) {+ return mcp.request(path, {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: JSON.stringify(body),+ });+}++describe("MCP OAuth HTTP resource bounds", () => {+ it.each([+ { redirect_uris: Array.from({ length: 11 }, () => redirectUri) },+ { redirect_uris: [redirectUri], client_name: "x".repeat(101) },+ { redirect_uris: [`https://example.com/${"x".repeat(2048)}`] },+ ])(+ "rejects oversized registration fields before storing them: %j",+ async (body) => {+ expect((await post("/mcp/register", body)).status).toBe(400);+ expect(await total("client")).toBe(0);+ },+ );++ it("rejects a large actual body even with a misleading Content-Length", async () => {+ const response = await post(+ "/mcp/register",+ { redirect_uris: [redirectUri], ignored: "x".repeat(33 * 1024) },+ { "content-length": "1" },+ );+ expect(response.status).toBe(413);+ expect(await total("client")).toBe(0);+ });++ it("bounds authorization fields and the raw URL before any request row is created", async () => {+ const client = await registerClient({ redirectUris: [redirectUri] });+ for (const [field, value, status] of [+ ["state", "s".repeat(1025), 400],+ ["state", "s".repeat(9000), 414],+ ["code_challenge", "x".repeat(44), 400],+ ["client_id", "x".repeat(129), 400],+ ] as const) {+ const query = new URLSearchParams({+ response_type: "code",+ client_id: client.clientId,+ redirect_uri: redirectUri,+ code_challenge: challenge,+ code_challenge_method: "S256",+ [field]: value,+ });+ expect((await mcp.request(`/mcp/authorize?${query}`)).status).toBe(+ status,+ );+ }+ expect(await total("request")).toBe(0);+ const query = new URLSearchParams({+ response_type: "code",+ client_id: client.clientId,+ redirect_uri: redirectUri,+ code_challenge: challenge,+ code_challenge_method: "S256",+ state: "s".repeat(1024),+ });+ expect((await mcp.request(`/mcp/authorize?${query}`)).status).toBe(302);+ expect(await total("request")).toBe(1);+ });++ it("returns a retryable JSON error at the durable registration limit", async () => {+ await db.insert(mcpOauthStateTable).values({+ kind: "rate",+ key: "client",+ payload: { count: OAUTH_STATE_LIMITS.client.perMinute },+ expiresAt: new Date(Date.now() + 60_000),+ });+ const response = await post("/mcp/register", {+ redirect_uris: [redirectUri],+ });+ expect(response.status).toBe(429);+ expect(response.headers.get("retry-after")).toBe("60");+ expect(await response.json()).toHaveProperty(+ "error",+ "temporarily_unavailable",+ );+ expect(await total("client")).toBe(0);+ });++ it("allows retrying consent after capacity recovers without issuing multiple codes", async () => {+ const { user } = await createWorkspaceMember();+ mockAuthenticatedSession(user);+ const client = await registerClient({ redirectUris: [redirectUri] });+ const id = await createAuthorizationRequest({+ clientId: client.clientId,+ codeChallenge: challenge,+ redirectUri,+ });+ await db.insert(mcpOauthStateTable).values({+ kind: "rate",+ key: "code",+ payload: { count: OAUTH_STATE_LIMITS.code.perMinute },+ expiresAt: new Date(Date.now() + 60_000),+ });+ const approve = () =>+ post(+ `/mcp/authorize/request/${id}`,+ { approved: true },+ { origin: "http://localhost:5173" },+ );+ expect((await approve()).status).toBe(429);+ expect(await getAuthorizationRequest(id)).not.toBeNull();+ await db+ .delete(mcpOauthStateTable)+ .where(+ and(+ eq(mcpOauthStateTable.kind, "rate"),+ eq(mcpOauthStateTable.key, "code"),+ ),+ );+ expect((await approve()).status).toBe(200);+ expect(await getAuthorizationRequest(id)).toBeNull();+ expect((await approve()).status).toBe(404);+ expect(await total("code")).toBe(1);+ });++ it.each([+ null,+ [],+ {+ grant_type: "authorization_code",+ code: {},+ client_id: "x",+ code_verifier: "x",+ redirect_uri: redirectUri,+ },+ ])("returns400 for malformed token inputs: %j", async (input) => {+ expect((await post("/mcp/token", input)).status).toBe(400);+ });+});diff --git a/tests/api-integration/mcp-oauth-store.test.ts b/tests/api-integration/mcp-oauth-store.test.tsindex 1029399e1..87f9cc990 100644--- a/tests/api-integration/mcp-oauth-store.test.ts+++ b/tests/api-integration/mcp-oauth-store.test.ts@@ -1,66 +1,192 @@-import { describe, expect, it } from "vitest";+import { and, count, eq, sql } from "drizzle-orm";+import { beforeEach, describe, expect, it } from "vitest";+import db from "../../apps/api/src/database";+import { mcpOauthStateTable } from "../../apps/api/src/database/schema";import {consumeState,deleteExpiredStates,- enforceStateCap,+ EXPIRED_STATE_BATCH,getState,+ OAUTH_STATE_LIMITS,putState,} from "../../apps/api/src/mcp/oauth-store";import { resetTestDatabase } from "./helpers/database";-describe("mcp oauth store", () => {- it("stores and returns state by kind and key", async () => {- const key = `client-${Date.now()}`;- const payload = { clientId: key, redirectUris: ["https://a.example/cb"] };- await putState("client", key, payload, new Date(Date.now() + 60_000));+beforeEach(async () => {+ await resetTestDatabase();+});+const future = () => new Date(Date.now() + 60_000);+async function seed(+ kind: "client" | "request" | "code",+ total: number,+ expired = false,+ clientId = "seed-client",+) {+ await db.execute(sql`INSERT INTO mcp_oauth_state (id,kind,key,payload,expires_at)+ SELECT ${kind} || '-' || i, ${kind}, ${kind} || '-' || i,+ jsonb_build_object('clientId', ${clientId}::text),+ CASE WHEN ${expired} THEN now() - interval '1 hour' ELSE now() + interval '1 hour' END+ FROM generate_series(1, ${total}::integer) AS i`);+}+async function total(kind: string) {+ const [row] = await db+ .select({ count: count() })+ .from(mcpOauthStateTable)+ .where(eq(mcpOauthStateTable.kind, kind));+ return row.count;+}- await expect(getState("client", key)).resolves.toEqual(payload);- await expect(getState("code", key)).resolves.toBeNull();+describe("bounded shared MCP OAuth store", () => {+ it("stores by kind and consumes exactly once", async () => {+ const payload = { clientId: "client", userId: "user" };+ await putState("code", "code", payload, future());+ expect(await getState("client", "code")).toBeNull();+ expect(await getState("code", "code")).toEqual(payload);+ expect(await consumeState("code", "code")).toEqual(payload);+ expect(await consumeState("code", "code")).toBeNull();});- it("consumes state exactly once", async () => {- const key = `code-${Date.now()}`;- const payload = { clientId: "c", userId: "u" };- await putState("code", key, payload, new Date(Date.now() + 60_000));-- await expect(consumeState("code", key)).resolves.toEqual(payload);- await expect(consumeState("code", key)).resolves.toBeNull();- await expect(getState("code", key)).resolves.toBeNull();+ it("bounds each cleanup batch, including registration-only traffic", async () => {+ await seed("client", EXPIRED_STATE_BATCH * 2 + 1, true);+ expect(await getState("client", "client-1")).toBeNull();+ await deleteExpiredStates();+ expect(await total("client")).toBe(EXPIRED_STATE_BATCH + 1);+ await putState("client", "fresh", {}, future());+ expect(await total("client")).toBe(2);});- it("treats expired rows as absent and sweeps them", async () => {- const key = `request-${Date.now()}`;- await putState("request", key, { clientId: "c" }, new Date(Date.now() - 1));+ it("commits bounded cleanup even when a legacy over-cap table denies the insert", async () => {+ await seed(+ "client",+ OAUTH_STATE_LIMITS.client.rows + EXPIRED_STATE_BATCH * 2,+ true,+ );+ await expect(+ putState("client", "denied", {}, future()),+ ).rejects.toMatchObject({ status: 429 });+ expect(await total("client")).toBe(+ OAUTH_STATE_LIMITS.client.rows + EXPIRED_STATE_BATCH,+ );+ await expect(+ putState("client", "denied", {}, future()),+ ).rejects.toMatchObject({ status: 429 });+ expect(await total("client")).toBe(OAUTH_STATE_LIMITS.client.rows);+ await expect(+ putState("client", "accepted", {}, future()),+ ).resolves.toBeUndefined();+ });- await expect(getState("request", key)).resolves.toBeNull();- await expect(consumeState("request", `${key}-other`)).resolves.toBeNull();+ it.each(["client", "request", "code"] as const)(+ "enforces the real global %s cap atomically under parallel attempts without evicting live state",+ async (kind) => {+ const limit = OAUTH_STATE_LIMITS[kind].rows;+ await seed(kind, limit - 1);+ const results = await Promise.allSettled(+ Array.from({ length: 12 }, (_, index) =>+ putState(+ kind,+ `new-${index}`,+ { clientId: `new-client-${index}` },+ future(),+ ),+ ),+ );+ expect(+ results.filter((result) => result.status === "fulfilled"),+ ).toHaveLength(1);+ for (const result of results)+ if (result.status === "rejected")+ expect(result.reason).toMatchObject({ status: 429 });+ expect(await total(kind)).toBe(limit);+ expect(await getState(kind, `${kind}-1`)).toEqual({+ clientId: "seed-client",+ });+ },+ );- await putState(- "request",- `${key}-expired`,- { clientId: "c" },- new Date(Date.now() - 1),+ it("limits outstanding state per client while allowing another client", async () => {+ await seed("request", OAUTH_STATE_LIMITS.request.perClient);+ await expect(+ putState("request", "denied", { clientId: "seed-client" }, future()),+ ).rejects.toMatchObject({ status: 429 });+ await expect(+ putState("request", "other", { clientId: "other-client" }, future()),+ ).resolves.toBeUndefined();+ expect(await total("request")).toBe(+ OAUTH_STATE_LIMITS.request.perClient + 1,);- await deleteExpiredStates();- await expect(getState("request", `${key}-expired`)).resolves.toBeNull();});- it("evicts the oldest rows of a kind once the cap is reached", async () => {- await resetTestDatabase();- const base = Date.now();- const payload = { clientId: "c" };- await putState("request", "cap-old", payload, new Date(base + 10_000));- await putState("request", "cap-mid", payload, new Date(base + 20_000));- await putState("request", "cap-new", payload, new Date(base + 30_000));- await putState("client", "cap-client", payload, new Date(base + 30_000));-- await enforceStateCap("request", 100);- await expect(getState("request", "cap-old")).resolves.toEqual(payload);+ it("enforces durable registration rate limits and reuses one counter after its window expires", async () => {+ await db.insert(mcpOauthStateTable).values({+ kind: "rate",+ key: "client",+ payload: { count: OAUTH_STATE_LIMITS.client.perMinute },+ expiresAt: future(),+ });+ await expect(+ putState("client", "denied", {}, future()),+ ).rejects.toMatchObject({ status: 429 });+ expect(await total("client")).toBe(0);+ await db+ .update(mcpOauthStateTable)+ .set({ expiresAt: new Date(0) })+ .where(eq(mcpOauthStateTable.kind, "rate"));+ await putState("client", "allowed", {}, future());+ expect(await total("rate")).toBe(1);+ expect(await total("client")).toBe(1);+ });- await enforceStateCap("request", 3);- await expect(getState("request", "cap-old")).resolves.toBeNull();- await expect(getState("request", "cap-mid")).resolves.toEqual(payload);- await expect(getState("request", "cap-new")).resolves.toEqual(payload);- await expect(getState("client", "cap-client")).resolves.toEqual(payload);+ it("keeps a consent request on code quota failure and atomically consumes it on success", async () => {+ await putState("request", "consent", { clientId: "client" }, future());+ await db.insert(mcpOauthStateTable).values({+ kind: "rate",+ key: "code",+ payload: { count: OAUTH_STATE_LIMITS.code.perMinute },+ expiresAt: future(),+ });+ await expect(+ putState("code", "denied", { clientId: "client" }, future(), "consent"),+ ).rejects.toMatchObject({ status: 429 });+ expect(await getState("request", "consent")).not.toBeNull();+ await db+ .delete(mcpOauthStateTable)+ .where(+ and(+ eq(mcpOauthStateTable.kind, "rate"),+ eq(mcpOauthStateTable.key, "code"),+ ),+ );+ await putState(+ "code",+ "issued",+ { clientId: "client" },+ future(),+ "consent",+ );+ expect(await getState("request", "consent")).toBeNull();+ await expect(+ putState("code", "replayed", { clientId: "client" }, future(), "consent"),+ ).rejects.toMatchObject({ status: 404 });+ expect(await total("code")).toBe(1);+ });+ it("issues only one code when multiple replicas approve the same consent", async () => {+ await putState("request", "race", { clientId: "client" }, future());+ const results = await Promise.allSettled(+ Array.from({ length: 12 }, (_, index) =>+ putState(+ "code",+ `code-${index}`,+ { clientId: "client" },+ future(),+ "race",+ ),+ ),+ );+ expect(+ results.filter((result) => result.status === "fulfilled"),+ ).toHaveLength(1);+ expect(await total("code")).toBe(1);+ expect(await getState("request", "race")).toBeNull();});});diff --git a/tests/api-integration/mocks/email.ts b/tests/api-integration/mocks/email.tsindex dbfbb6eb4..7ccea0d56 100644--- a/tests/api-integration/mocks/email.ts+++ b/tests/api-integration/mocks/email.ts@@ -1,5 +1,7 @@import type { EmailResult } from "../../../packages/email/src/send-email";+export { OTP_EXPIRY_SECONDS } from "../../../packages/email/src/otp-expiry";+export async function sendMagicLinkEmail(_to: string,_subject: string,diff --git a/tests/api-integration/notification-access.test.ts b/tests/api-integration/notification-access.test.tsnew file mode 100644index 000000000..4fa1f9cf4--- /dev/null+++ b/tests/api-integration/notification-access.test.ts@@ -0,0 +1,347 @@+import { and, eq } from "drizzle-orm";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import createComment from "../../apps/api/src/activity/controllers/create-comment";+import db, { schema } from "../../apps/api/src/database";+import { taskReminderSentTable } from "../../apps/api/src/database/schema";+import createNotification from "../../apps/api/src/notification/controllers/create-notification";+import getNotifications from "../../apps/api/src/notification/controllers/get-notifications";+import markAsRead from "../../apps/api/src/notification/controllers/mark-notification-as-read";++const { deliverNotification } = await vi.importActual<+ typeof import("../../apps/api/src/notification-preferences/delivery")+>("../../apps/api/src/notification-preferences/delivery");++import { checkDueDateReminders } from "../../apps/api/src/scheduler/due-date-reminders";+import bulkUpdateTasks from "../../apps/api/src/task/controllers/bulk-update-tasks";+import createTask from "../../apps/api/src/task/controllers/create-task";+import importTasks from "../../apps/api/src/task/controllers/import-tasks";+import updateAssignee from "../../apps/api/src/task/controllers/update-task-assignee";+import updateDescription from "../../apps/api/src/task/controllers/update-task-description";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const { publish, sendEmail } = vi.hoisted(() => ({+ publish: vi.fn(),+ sendEmail: vi.fn(async () => undefined),+}));+vi.mock("../../apps/api/src/events", () => ({ publishEvent: publish }));+vi.mock("@kaneo/email", async (original) => ({+ ...(await original<object>()),+ sendNotificationEmail: sendEmail,+}));++vi.mock("../../apps/api/src/notification-preferences/delivery", () => ({+ deliverNotification: vi.fn(async () => undefined),+}));++async function fixture() {+ const actor = await createWorkspaceMember();+ const outsider = await createWorkspaceMember();+ const member = await createWorkspaceMember();+ await db.insert(schema.workspaceUserTable).values({+ workspaceId: actor.workspace.id,+ userId: member.user.id,+ joinedAt: new Date(),+ });+ const { project, columns } = await createProjectFixture({+ workspaceId: actor.workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ columnId: columns.todo.id,+ title: "Private task",+ userId: member.user.id,+ })+ .returning();+ return { actor, outsider, member, project, task };+}++describe("notification recipient boundaries", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ });+ beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+ });++ it("filters outsider and nonexistent comment mentions without failing the comment", async () => {+ const { actor, outsider, member, task } = await fixture();+ const content = [member.user.id, outsider.user.id, "nonexistent"]+ .map((id) => `<kaneo-mention id="${id}">name</kaneo-mention>`)+ .join(" ");+ await expect(+ createComment(task.id, actor.user.id, content),+ ).resolves.toHaveProperty("content", content);+ const notifications = await db.select().from(schema.notificationTable);+ expect(notifications.map((n) => n.userId)).toEqual([member.user.id]);+ expect(notifications[0].type).toBe("task_mention");+ });++ it("filters description mentions at the shared creation boundary", async () => {+ const { actor, outsider, member, task } = await fixture();+ const description = [member.user.id, outsider.user.id, "nonexistent"]+ .map((id) => `<kaneo-mention id="${id}">name</kaneo-mention>`)+ .join(" ");+ await expect(+ updateDescription({+ id: task.id,+ currentUserId: actor.user.id,+ description,+ }),+ ).resolves.toHaveProperty("description", description);+ expect(+ (await db.select().from(schema.notificationTable)).map((n) => n.userId),+ ).toEqual([member.user.id]);+ });++ it("does not notify a stale assignee about comments or due dates", async () => {+ const { actor, member, task } = await fixture();+ await db+ .delete(schema.workspaceUserTable)+ .where(+ and(+ eq(schema.workspaceUserTable.userId, member.user.id),+ eq(schema.workspaceUserTable.workspaceId, actor.workspace.id),+ ),+ );+ await db+ .update(schema.taskTable)+ .set({ dueDate: new Date(Date.now() - 60_000) })+ .where(eq(schema.taskTable.id, task.id));+ await createComment(task.id, actor.user.id, "Private comment");+ await checkDueDateReminders();+ expect(await db.select().from(schema.notificationTable)).toEqual([]);+ expect(await db.select().from(taskReminderSentTable)).toEqual([]);+ expect(sendEmail).not.toHaveBeenCalled();+ });++ it("keeps reminders working for current assignees", async () => {+ const { member, task } = await fixture();+ await db+ .update(schema.taskTable)+ .set({ dueDate: new Date(Date.now() - 60_000) })+ .where(eq(schema.taskTable.id, task.id));+ await checkDueDateReminders();+ expect(await getNotifications(member.user.id)).toEqual([+ expect.objectContaining({ type: "task_overdue", resourceId: task.id }),+ ]);+ });++ it("treats foreign, missing and unsupported references identically and never enriches historical forged references", async () => {+ const { outsider, member, task } = await fixture();+ for (const id of [task.id, "missing"]) {+ expect(+ await createNotification({+ userId: outsider.user.id,+ resourceType: "task",+ resourceId: id,+ }),+ ).toBeNull();+ await db.insert(schema.notificationTable).values({+ userId: outsider.user.id,+ resourceType: "task",+ resourceId: id,+ eventData: { taskTitle: "old leaked title" },+ });+ }+ expect(+ await createNotification({+ userId: member.user.id,+ resourceType: "unsupported",+ resourceId: task.id,+ }),+ ).toBeNull();+ expect(await getNotifications(outsider.user.id)).toEqual([]);+ expect(publish).not.toHaveBeenCalled();+ expect(+ await createNotification({+ userId: member.user.id,+ title: "Generic message",+ }),+ ).toHaveProperty("title", "Generic message");+ });++ it("hides historical contents from list, read response and external delivery after removal", async () => {+ const { actor, member, task } = await fixture();+ const notification = await createNotification({+ userId: member.user.id,+ resourceType: "task",+ resourceId: task.id,+ type: "task_comment",+ eventData: { taskTitle: task.title },+ });+ if (!notification) throw new Error("Expected member notification");+ expect(await getNotifications(member.user.id)).toEqual([+ expect.objectContaining({+ id: notification.id,+ eventData: expect.objectContaining({ workspaceId: actor.workspace.id }),+ }),+ ]);+ await db+ .insert(schema.userNotificationPreferenceTable)+ .values({ userId: member.user.id, emailEnabled: true });+ await db.insert(schema.userNotificationWorkspaceRuleTable).values({+ userId: member.user.id,+ workspaceId: actor.workspace.id,+ isActive: true,+ emailEnabled: true,+ });+ await deliverNotification(notification.id);+ expect(sendEmail).toHaveBeenCalledTimes(1);+ await db+ .delete(schema.workspaceUserTable)+ .where(+ and(+ eq(schema.workspaceUserTable.userId, member.user.id),+ eq(schema.workspaceUserTable.workspaceId, actor.workspace.id),+ ),+ );+ expect(await getNotifications(member.user.id)).toEqual([]);+ await expect(+ markAsRead(notification.id, member.user.id),+ ).rejects.toMatchObject({ status: 404 });+ await deliverNotification(notification.id);+ expect(sendEmail).toHaveBeenCalledTimes(1);+ });++ it("rejects foreign assignees while preserving valid partial imports", async () => {+ const { actor, outsider, member, project, task } = await fixture();+ await expect(+ updateAssignee({+ id: task.id,+ userId: outsider.user.id,+ currentUserId: actor.user.id,+ }),+ ).rejects.toMatchObject({ status: 403 });+ await expect(+ createTask({+ projectId: project.id,+ title: "Invalid",+ status: "to-do",+ userId: outsider.user.id,+ currentUserId: actor.user.id,+ }),+ ).rejects.toMatchObject({ status: 403 });+ await expect(+ bulkUpdateTasks({+ taskIds: [task.id],+ operation: "updateAssignee",+ value: outsider.user.id,+ userId: actor.user.id,+ }),+ ).rejects.toMatchObject({ status: 403 });+ await db+ .update(schema.projectTable)+ .set({ lastTaskNumber: 1 })+ .where(eq(schema.projectTable.id, project.id));+ await expect(+ importTasks(+ project.id,+ [+ { title: "Valid", status: "to-do" },+ { title: "Invalid", status: "to-do", userId: outsider.user.id },+ ],+ actor.user.id,+ ),+ ).resolves.toMatchObject({+ results: {+ successful: 1,+ failed: 1,+ tasks: [+ { success: true },+ {+ success: false,+ error: "Assignee is not a member of this workspace",+ },+ ],+ },+ });+ const tasks = await db.select().from(schema.taskTable);+ expect(tasks).toHaveLength(2);+ expect(tasks).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: task.id, userId: member.user.id }),+ expect.objectContaining({ title: "Valid", userId: null }),+ ]),+ );+ expect(tasks.some((row) => row.userId === outsider.user.id)).toBe(false);+ await expect(+ updateAssignee({+ id: task.id,+ userId: actor.user.id,+ currentUserId: actor.user.id,+ }),+ ).resolves.toHaveProperty("userId", actor.user.id);+ await expect(+ updateAssignee({+ id: task.id,+ userId: null,+ currentUserId: actor.user.id,+ }),+ ).resolves.toHaveProperty("userId", null);+ });++ it("uses bounded non-redirecting requests and safe errors for all external channels", async () => {+ const { actor, member, task } = await fixture();+ const [notification] = await db+ .insert(schema.notificationTable)+ .values({+ userId: member.user.id,+ resourceType: "task",+ resourceId: task.id,+ type: "task_comment",+ })+ .returning();+ await db.insert(schema.userNotificationPreferenceTable).values({+ userId: member.user.id,+ ntfyEnabled: true,+ ntfyServerUrl: "http://127.0.0.1",+ ntfyTopic: "topic",+ ntfyToken: "ntfy-secret",+ gotifyEnabled: true,+ gotifyServerUrl: "http://127.0.0.1",+ gotifyToken: "gotify-secret",+ webhookEnabled: true,+ webhookUrl: "http://127.0.0.1/private-url?key=secret",+ webhookSecret: "webhook-secret",+ });+ await db.insert(schema.userNotificationWorkspaceRuleTable).values({+ userId: member.user.id,+ workspaceId: actor.workspace.id,+ ntfyEnabled: true,+ gotifyEnabled: true,+ webhookEnabled: true,+ });+ vi.stubEnv("KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS", "true");+ const fetchMock = vi+ .fn()+ .mockRejectedValue(+ new Error("gotify-secret ntfy-secret webhook-secret private-url"),+ );+ vi.stubGlobal("fetch", fetchMock);+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ await deliverNotification(notification.id);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ for (const [, options] of fetchMock.mock.calls) {+ expect(options.redirect).toBe("error");+ expect(options.signal).toBeInstanceOf(AbortSignal);+ }+ expect(log).toHaveBeenCalledTimes(3);+ const logged = JSON.stringify(log.mock.calls);+ for (const secret of [+ "gotify-secret",+ "ntfy-secret",+ "webhook-secret",+ "private-url",+ ])+ expect(logged).not.toContain(secret);+ expect(logged).toContain("network");+ });+});diff --git a/tests/api-integration/registration-invitation.test.ts b/tests/api-integration/registration-invitation.test.tsindex 35929e34e..9aec09eee 100644--- a/tests/api-integration/registration-invitation.test.ts+++ b/tests/api-integration/registration-invitation.test.ts@@ -42,12 +42,26 @@ describe("API integration: invite-only registration", () => {const result = await checkRegistrationAllowed(email, undefined, {allowInvitationByEmail: true,+ emailVerified: true,});expect(result.allowed).toBe(true);expect(result.invitation?.id).toBe(invitation.id);});+ it.each([false, undefined])(+ "rejects an unverified provider email (%s)",+ async (emailVerified) => {+ const email = `invited-${randomUUID()}@example.com`;+ await seedInvitation(email);+ const result = await checkRegistrationAllowed(email, undefined, {+ allowInvitationByEmail: true,+ emailVerified,+ });+ expect(result.allowed).toBe(false);+ },+ );+it("matches the invitation regardless of email casing", async () => {const email = `invited-${randomUUID()}@example.com`;await seedInvitation(email);@@ -55,7 +69,7 @@ describe("API integration: invite-only registration", () => {const result = await checkRegistrationAllowed(email.toUpperCase(),undefined,- { allowInvitationByEmail: true },+ { allowInvitationByEmail: true, emailVerified: true },);expect(result.allowed).toBe(true);@@ -67,7 +81,7 @@ describe("API integration: invite-only registration", () => {const result = await checkRegistrationAllowed(`stranger-${randomUUID()}@example.com`,undefined,- { allowInvitationByEmail: true },+ { allowInvitationByEmail: true, emailVerified: true },);expect(result.allowed).toBe(false);@@ -85,6 +99,7 @@ describe("API integration: invite-only registration", () => {const result = await checkRegistrationAllowed(email, undefined, {allowInvitationByEmail: true,+ emailVerified: true,});expect(result.allowed).toBe(false);@@ -107,6 +122,7 @@ describe("API integration: invite-only registration", () => {const result = await checkRegistrationAllowed(email, "does-not-exist", {allowInvitationByEmail: true,+ emailVerified: true,});expect(result.allowed).toBe(false);diff --git a/tests/api-integration/search-bounds.test.ts b/tests/api-integration/search-bounds.test.tsnew file mode 100644index 000000000..3c52ffba4--- /dev/null+++ b/tests/api-integration/search-bounds.test.ts@@ -0,0 +1,57 @@+import { beforeEach, describe, expect, it } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++describe("short task ID search bounds", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });+ it("handles invalid int4 IDs without querying an overflowing task number", async () => {+ const member = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ slug: "DEP",+ });+ await db.insert(schema.taskTable).values({+ projectId: project.id,+ title: "Boundary",+ number: 2_147_483_647,+ });+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ for (const number of [+ "2147483648",+ "999999999999999999999999999999",+ "9".repeat(400),+ "0",+ ]) {+ const response = await app.request(+ `/api/search?${new URLSearchParams({ q: `DEP-${number}`, workspaceId: member.workspace.id, type: "tasks" })}`,+ );+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({ results: [] });+ }+ const valid = await app.request(+ `/api/search?${new URLSearchParams({ q: "DEP-2147483647", workspaceId: member.workspace.id, type: "tasks" })}`,+ );+ expect(valid.status).toBe(200);+ expect(await valid.json()).toMatchObject({+ results: [+ expect.objectContaining({+ title: "Boundary",+ taskNumber: 2_147_483_647,+ }),+ ],+ });+ const oversized = await app.request(+ `/api/search?${new URLSearchParams({ q: "9".repeat(513), workspaceId: member.workspace.id })}`,+ );+ expect(oversized.status).toBe(400);+ });+});diff --git a/tests/api-integration/session-client-ip.test.ts b/tests/api-integration/session-client-ip.test.tsindex cb11cd3a7..2d461fd4b 100644--- a/tests/api-integration/session-client-ip.test.ts+++ b/tests/api-integration/session-client-ip.test.ts@@ -1,6 +1,9 @@import { randomUUID } from "node:crypto";+import { once } from "node:events";+import type { AddressInfo } from "node:net";+import { serve } from "@hono/node-server";import { desc, eq } from "drizzle-orm";-import { beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import db, { schema } from "../../apps/api/src/database";import { createApp } from "../../apps/api/src/index";import { resetTestDatabase } from "./helpers/database";@@ -9,19 +12,32 @@ async function signUpWithForwardedFor(forwardedFor: string) {const { app } = createApp();const email = `ip-${randomUUID()}@example.com`;- const response = await app.request("/api/auth/sign-up/email", {- method: "POST",- headers: {- "content-type": "application/json",- "x-forwarded-for": forwardedFor,- },- body: JSON.stringify({- email,- password: "TestPassw0rd!23",- name: "IP Probe",- }),- });+ const server = serve({ fetch: app.fetch, hostname: "127.0.0.1", port: 0 });+ await once(server, "listening");+ let response: Response;+ try {+ response = await fetch(+ `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/auth/sign-up/email`,+ {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-forwarded-for": forwardedFor,+ },+ body: JSON.stringify({+ email,+ password: "TestPassw0rd!23",+ name: "IP Probe",+ }),+ },+ );+ await response.text();+ } finally {+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ }expect(response.status).toBeLessThan(400);const [user] = await db@@ -42,8 +58,11 @@ async function signUpWithForwardedFor(forwardedFor: string) {describe("session records the real client IP behind the proxy chain", () => {beforeEach(async () => {await resetTestDatabase();+ vi.stubEnv("TRUSTED_PROXIES", "127.0.0.0/8,172.19.0.5");});+ afterEach(() => vi.unstubAllEnvs());+it("stores the client, not the in-image nginx or Caddy hop", async () => {const session = await signUpWithForwardedFor("203.0.113.9, 172.19.0.5");diff --git a/tests/api-integration/task-description-pages.test.ts b/tests/api-integration/task-description-pages.test.tsnew file mode 100644index 000000000..3f4438523--- /dev/null+++ b/tests/api-integration/task-description-pages.test.ts@@ -0,0 +1,355 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it } from "vitest";+import db, { getDatabasePool, schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import {+ BOARD_DESCRIPTION_MAX_BYTES,+ DESCRIPTION_CHUNK_CHARACTERS,+ getDescriptionPage,+} from "../../apps/api/src/task/description-pages";+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++beforeEach(resetTestDatabase);+async function fixture(description: string | null, isPublic = false) {+ const member = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ if (isPublic)+ await db+ .update(schema.projectTable)+ .set({ isPublic })+ .where(eq(schema.projectTable.id, project.id));+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Task",+ description,+ status: "to-do",+ priority: "low",+ number: 1,+ })+ .returning();+ mockAuthenticatedSession(member.user);+ return { ...createApp(), member, project, task };+}++describe("large task descriptions", () => {+ it("omits large text from both boards while retaining exact boundary-sized text", async () => {+ const body = "😺".repeat(BOARD_DESCRIPTION_MAX_BYTES / 4 + 1);+ const { app, project, task } = await fixture(body, true);+ const [small] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "At boundary",+ number: 2,+ status: "to-do",+ description: "a".repeat(BOARD_DESCRIPTION_MAX_BYTES),+ })+ .returning();+ for (const prefix of ["task/tasks", "public-project"]) {+ const response = await app.request(`/api/${prefix}/${project.id}`);+ expect(response.status).toBe(200);+ const json = await response.json();+ const tasks = (json.data ?? json).columns.flatMap(+ (column: { tasks: unknown[] }) => column.tasks,+ );+ expect(+ tasks.find((entry: { id: string }) => entry.id === task.id),+ ).toMatchObject({ description: null, descriptionDeferred: true });+ expect(+ tasks.find((entry: { id: string }) => entry.id === small.id),+ ).toMatchObject({+ description: "a".repeat(BOARD_DESCRIPTION_MAX_BYTES),+ descriptionDeferred: false,+ });+ }+ });+ it("moves a summarized task without replacing its stored description and accepts an explicit clear", async () => {+ const body = "kept ".repeat(20000);+ const { app, project, task } = await fixture(body);+ const update = {+ title: task.title,+ status: "in-progress",+ priority: "low",+ position: 5,+ projectId: project.id,+ };+ const response = await app.request(`/api/task/${task.id}`, {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(update),+ });+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ status: "in-progress",+ description: null,+ descriptionDeferred: true,+ });+ expect(+ (+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, task.id),+ })+ )?.description,+ ).toBe(body);+ const cleared = await app.request(`/api/task/${task.id}`, {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ ...update, description: "" }),+ });+ expect(cleared.status).toBe(200);+ expect(await cleared.json()).toMatchObject({+ description: "",+ descriptionDeferred: false,+ });+ expect(+ (+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, task.id),+ })+ )?.description,+ ).toBe("");+ });+ it("reads full Unicode text in bounded pages without splitting or dropping characters", async () => {+ const body = "😺é\n".repeat(DESCRIPTION_CHUNK_CHARACTERS);+ const { app, project, task } = await fixture(body, true);+ for (const url of [+ `/api/task/${task.id}/description`,+ `/api/public-project/${project.id}/task/${task.id}/description`,+ ]) {+ let offset = 0;+ let version: string | undefined;+ let actual = "";+ let pages = 0;+ while (true) {+ const response = await app.request(+ `${url}?offset=${offset}${version ? `&version=${version}` : ""}`,+ );+ expect(response.status).toBe(200);+ const page = await response.json();+ expect(Array.from(page.content).length).toBeLessThanOrEqual(+ DESCRIPTION_CHUNK_CHARACTERS,+ );+ if (version) expect(page.version).toBe(version);+ version = page.version;+ actual += page.content;+ pages++;+ if (page.nextOffset === null) break;+ expect(page.nextOffset).toBeGreaterThan(offset);+ offset = page.nextOffset;+ }+ expect(actual).toBe(body);+ expect(pages).toBe(3);+ }+ });+ it("rejects a stale version rather than joining two revisions", async () => {+ const { app, task } = await fixture("a".repeat(100000));+ const first = await (+ await app.request(`/api/task/${task.id}/description`)+ ).json();+ await db+ .update(schema.taskTable)+ .set({ description: "b".repeat(100000) })+ .where(eq(schema.taskTable.id, task.id));+ expect(+ (+ await app.request(+ `/api/task/${task.id}/description?offset=${first.nextOffset}&version=${first.version}`,+ )+ ).status,+ ).toBe(409);+ });+ it("enforces workspace access, public project ownership and visibility on every chunk", async () => {+ const { app, project, task } = await fixture("secret ".repeat(20000), true);+ const other = await createWorkspaceMember();+ const { project: otherProject } = await createProjectFixture({+ workspaceId: other.workspace.id,+ });+ await db+ .update(schema.projectTable)+ .set({ isPublic: true })+ .where(eq(schema.projectTable.id, otherProject.id));+ mockAuthenticatedSession(other.user);+ expect((await app.request(`/api/task/${task.id}/description`)).status).toBe(+ 403,+ );+ expect(+ (+ await app.request(+ `/api/task/description-matches/${project.id}?query=secret`,+ )+ ).status,+ ).toBe(403);+ mockAnonymousSession();+ expect((await app.request(`/api/task/${task.id}/description`)).status).toBe(+ 401,+ );+ expect(+ (+ await app.request(+ `/api/public-project/${otherProject.id}/task/${task.id}/description`,+ )+ ).status,+ ).toBe(404);+ const url = `/api/public-project/${project.id}/task/${task.id}/description`;+ const first = await (await app.request(url)).json();+ await db+ .update(schema.projectTable)+ .set({ isPublic: false })+ .where(eq(schema.projectTable.id, project.id));+ const denied = await app.request(+ `${url}?offset=${first.nextOffset}&version=${first.version}`,+ );+ expect(denied.status).toBe(409);+ expect(await denied.text()).not.toContain("secret");+ });+ it("finds literal description matches on every bounded page, only within the project", async () => {+ const { app, project, member } = await fixture("needle short");+ const { project: other } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const body = `${"x".repeat(70000)} Needle%_tail`;+ await db.insert(schema.taskTable).values(+ Array.from({ length: 203 }, (_, i) => ({+ id: `match-${String(i).padStart(3, "0")}`,+ projectId: project.id,+ number: i + 2,+ title: "Unrelated",+ status: "to-do",+ description: body,+ })),+ );+ await db.insert(schema.taskTable).values({+ projectId: other.id,+ title: "Other",+ status: "to-do",+ description: body,+ });+ let after: string | null = null;+ const ids: string[] = [];+ do {+ const response = await app.request(+ `/api/task/description-matches/${project.id}?query=${encodeURIComponent("NEEDLE%_tail")}${after ? `&after=${after}` : ""}`,+ );+ expect(response.status).toBe(200);+ const page = await response.json();+ expect(page.ids.length).toBeLessThanOrEqual(100);+ ids.push(...page.ids);+ after = page.nextCursor;+ } while (after);+ expect(ids).toEqual(+ Array.from(+ { length: 203 },+ (_, i) => `match-${String(i).padStart(3, "0")}`,+ ),+ );+ const absent = await (+ await app.request(+ `/api/task/description-matches/${project.id}?query=NEEDLE___tail`,+ )+ ).json();+ expect(absent.ids).toEqual([]);+ });+ it("defers large project descriptions and serves complete public text with version and visibility checks", async () => {+ const { app, project } = await fixture("task body", true);+ const body = "😺project".repeat(12000);+ await db+ .update(schema.projectTable)+ .set({ description: body })+ .where(eq(schema.projectTable.id, project.id));+ for (const prefix of ["task/tasks", "public-project"]) {+ const payload = await (+ await app.request(`/api/${prefix}/${project.id}`)+ ).json();+ expect(payload.data ?? payload).toMatchObject({+ description: null,+ descriptionDeferred: true,+ });+ }+ mockAnonymousSession();+ const url = `/api/public-project/${project.id}/description`;+ let offset = 0;+ let version: string | undefined;+ let text = "";+ while (true) {+ const response = await app.request(+ `${url}?offset=${offset}${version ? `&version=${version}` : ""}`,+ );+ expect(response.status).toBe(200);+ const page = await response.json();+ expect(Array.from(page.content).length).toBeLessThanOrEqual(+ DESCRIPTION_CHUNK_CHARACTERS,+ );+ version = page.version;+ text += page.content;+ if (page.nextOffset === null) break;+ offset = page.nextOffset;+ }+ expect(text).toBe(body);+ await db+ .update(schema.projectTable)+ .set({ description: "new" })+ .where(eq(schema.projectTable.id, project.id));+ expect(+ (await app.request(`${url}?version=${version}&offset=32768`)).status,+ ).toBe(409);+ await db+ .update(schema.projectTable)+ .set({ isPublic: false })+ .where(eq(schema.projectTable.id, project.id));+ expect((await app.request(url)).status).toBe(404);+ });+ it("bounds description database work and returns a retryable error after a statement timeout", async () => {+ const { task } = await fixture("body");+ const lock = await getDatabasePool().connect();+ try {+ await lock.query("BEGIN");+ await lock.query('LOCK TABLE "task" IN ACCESS EXCLUSIVE MODE');+ await expect(+ getDescriptionPage(task.id, { offset: 0 }),+ ).rejects.toMatchObject({+ status: 503,+ message: "Description request took too long; retry later",+ });+ } finally {+ await lock.query("ROLLBACK");+ lock.release();+ }+ });+ it("validates offsets, versions and search length, including the public route", async () => {+ const { app, project, task } = await fixture(null, true);+ for (const url of [+ `/api/task/${task.id}/description`,+ `/api/public-project/${project.id}/task/${task.id}/description`,+ ]) {+ expect(await (await app.request(url)).json()).toMatchObject({+ content: "",+ nextOffset: null,+ });+ for (const query of [+ "offset=-1",+ "offset=1e9",+ "offset=2147483648",+ "version=bad",+ "offset=1.2",+ ])+ expect((await app.request(`${url}?${query}`)).status).toBe(400);+ }+ for (const query of ["", "a".repeat(257)])+ expect(+ (+ await app.request(+ `/api/task/description-matches/${project.id}?query=${query}`,+ )+ ).status,+ ).toBe(400);+ });+});diff --git a/tests/api-integration/task-image-upload.test.ts b/tests/api-integration/task-image-upload.test.tsindex dc3c51e94..662066cbf 100644--- a/tests/api-integration/task-image-upload.test.ts+++ b/tests/api-integration/task-image-upload.test.ts@@ -1,5 +1,6 @@import { randomUUID } from "node:crypto";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { S3Client } from "../../apps/api/node_modules/@aws-sdk/client-s3";import db, { schema } from "../../apps/api/src/database";import { createApp } from "../../apps/api/src/index";import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";@@ -18,6 +19,11 @@ describe("API integration: task image upload finalize", () => {process.env.S3_ACCESS_KEY_ID = "test-access-key";process.env.S3_SECRET_ACCESS_KEY = "test-secret-key";delete process.env.S3_KEY_PREFIX;+ // These URL/metadata tests must provide an uploaded-object fixture now+ // that finalization verifies storage. Never contact the placeholder host.+ vi.spyOn(S3Client.prototype, "send").mockRejectedValue(+ new Error("No uploaded-object fixture configured"),+ );});afterEach(() => {@@ -25,6 +31,10 @@ describe("API integration: task image upload finalize", () => {});it("returns a URL using KANEO_API_URL", async () => {+ vi.mocked(S3Client.prototype.send).mockResolvedValueOnce({+ ContentLength: 12345,+ ContentType: "image/png",+ });process.env.KANEO_API_URL = "http://kaneo.test:1337";const member = await createWorkspaceMember();@@ -75,6 +85,10 @@ describe("API integration: task image upload finalize", () => {});it("updates the URL when KANEO_API_URL changes", async () => {+ vi.mocked(S3Client.prototype.send).mockResolvedValueOnce({+ ContentLength: 99999,+ ContentType: "image/png",+ });process.env.KANEO_API_URL = "https://proxy.kaneo.internal";const member = await createWorkspaceMember();@@ -125,6 +139,10 @@ describe("API integration: task image upload finalize", () => {});it("falls back to deriving URL from the request when KANEO_API_URL is not set", async () => {+ vi.mocked(S3Client.prototype.send).mockResolvedValueOnce({+ ContentLength: 12345,+ ContentType: "image/png",+ });delete process.env.KANEO_API_URL;const member = await createWorkspaceMember();@@ -173,6 +191,10 @@ describe("API integration: task image upload finalize", () => {});it("persists a new asset record with correct metadata", async () => {+ vi.mocked(S3Client.prototype.send).mockResolvedValueOnce({+ ContentLength: 45678,+ ContentType: "image/png",+ });process.env.KANEO_API_URL = "http://localhost:1337";const member = await createWorkspaceMember();@@ -236,6 +258,10 @@ describe("API integration: task image upload finalize", () => {});it("creates attachment records for non-image content types", async () => {+ vi.mocked(S3Client.prototype.send).mockResolvedValueOnce({+ ContentLength: 102400,+ ContentType: "application/pdf",+ });process.env.KANEO_API_URL = "http://localhost:1337";const member = await createWorkspaceMember();diff --git a/tests/api-integration/task-pagination.test.ts b/tests/api-integration/task-pagination.test.tsnew file mode 100644index 000000000..bbd528d3e--- /dev/null+++ b/tests/api-integration/task-pagination.test.ts@@ -0,0 +1,201 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import * as taskController from "../../apps/api/src/task/controllers/get-tasks";+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++beforeEach(resetTestDatabase);+async function fixture(count = 237, publicProject = false) {+ const member = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ if (publicProject)+ await db+ .update(schema.projectTable)+ .set({ isPublic: true })+ .where(eq(schema.projectTable.id, project.id));+ const tasks = count+ ? await db+ .insert(schema.taskTable)+ .values(+ Array.from({ length: count }, (_, index) => ({+ id: `page-task-${String(index).padStart(4, "0")}`,+ projectId: project.id,+ title: `Task ${index}`,+ description: `Description ${index}`,+ number: index + 1,+ position: 100,+ status:+ index % 3 === 0+ ? "planned"+ : index % 3 === 1+ ? "archived"+ : "to-do",+ priority: index % 2 ? "high" : "low",+ })),+ )+ .returning()+ : [];+ mockAuthenticatedSession(member.user);+ const { app } = createApp();+ return { project, member, tasks, app };+}+function allTasks(board: {+ columns: { tasks: { id: string; number: number }[] }[];+ archivedTasks: { id: string; number: number }[];+ plannedTasks: { id: string; number: number }[];+}) {+ return [+ ...board.columns.flatMap((column) => column.tasks),+ ...board.archivedTasks,+ ...board.plannedTasks,+ ];+}+describe("bounded task pages", () => {+ it("bounds the default and retrieves every bucket with deterministic tied-position ordering", async () => {+ const { project, app, tasks } = await fixture();+ const first = await app.request(`/api/task/tasks/${project.id}`);+ expect(first.status).toBe(200);+ const initial = await first.json();+ expect(allTasks(initial.data)).toHaveLength(50);+ expect(initial.pagination).toMatchObject({+ page: 1,+ pageSize: 50,+ total: 237,+ totalPages: 5,+ });+ const ids = allTasks(initial.data).map((task) => task.id);+ for (let page = 2; page <= initial.pagination.totalPages; page++) {+ const response = await app.request(+ `/api/task/tasks/${project.id}?page=${page}`,+ );+ expect(response.status).toBe(200);+ const data = await response.json();+ expect(allTasks(data.data).length).toBeLessThanOrEqual(50);+ ids.push(...allTasks(data.data).map((task) => task.id));+ }+ expect(new Set(ids).size).toBe(237);+ expect(ids.sort()).toEqual(tasks.map((task) => task.id).sort());+ });+ it("applies filters and sorting before paginating and keeps labels and links with their tasks", async () => {+ const { project, member, tasks, app } = await fixture();+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({ projectId: project.id, type: "github", config: "{}" })+ .returning();+ const task = tasks[235];+ await db.insert(schema.labelTable).values({+ name: "late-page-label",+ color: "red",+ workspaceId: member.workspace.id,+ taskId: task.id,+ });+ await db.insert(schema.externalLinkTable).values({+ integrationId: integration.id,+ taskId: task.id,+ resourceType: "issue",+ externalId: "235",+ url: "https://github.com/example/repo/issues/235",+ metadata: JSON.stringify({ state: "open" }),+ });+ const response = await app.request(+ `/api/task/tasks/${project.id}?priority=high&sortBy=number&sortOrder=desc&limit=1`,+ );+ const payload = await response.json();+ expect(payload.pagination).toMatchObject({+ total: 118,+ pageSize: 1,+ totalPages: 118,+ });+ const match = allTasks(payload.data)[0];+ expect(match).toMatchObject({+ id: task.id,+ number: 236,+ labels: [{ name: "late-page-label" }],+ externalLinks: [{ externalId: "235", metadata: { state: "open" } }],+ });+ });+ it("caps explicit pages at 100 and rejects invalid limits or offsets", async () => {+ const { project, app } = await fixture();+ const response = await app.request(+ `/api/task/tasks/${project.id}?limit=100`,+ );+ expect(allTasks((await response.json()).data)).toHaveLength(100);+ for (const query of [+ "limit=101",+ "limit=0",+ "page=0",+ "page=-1",+ "page=1e9",+ "page=1000001",+ ])+ expect(+ (await app.request(`/api/task/tasks/${project.id}?${query}`)).status,+ ).toBe(400);+ });+ it("rejects another workspace before returning any page", async () => {+ const { project, app } = await fixture();+ const other = await createWorkspaceMember();+ mockAuthenticatedSession(other.user);+ const response = await app.request(`/api/task/tasks/${project.id}?page=2`);+ expect(response.status).toBe(403);+ expect(await response.text()).not.toContain("Description");+ });+ it("paginates public boards and rechecks visibility on every request", async () => {+ const { project, app } = await fixture(237, true);+ mockAnonymousSession();+ const first = await app.request(`/api/public-project/${project.id}`);+ expect(first.status).toBe(200);+ const payload = await first.json();+ expect(allTasks(payload)).toHaveLength(50);+ expect(payload.pagination.totalPages).toBe(5);+ const last = await app.request(+ `/api/public-project/${project.id}?page=3&limit=100`,+ );+ expect(last.status).toBe(200);+ expect(allTasks(await last.json())).toHaveLength(37);+ await db+ .update(schema.projectTable)+ .set({ isPublic: false })+ .where(eq(schema.projectTable.id, project.id));+ const spy = vi.spyOn(taskController, "default");+ const denied = await app.request(+ `/api/public-project/${project.id}?page=2`,+ );+ expect(denied.status).toBe(403);+ expect(spy).not.toHaveBeenCalled(); // getTasks starts here; private boards never reach it.+ spy.mockRestore();+ });+ it("validates public pagination before loading a board", async () => {+ const { project, app } = await fixture(1, true);+ mockAnonymousSession();+ const response = await app.request(+ `/api/public-project/${project.id}?limit=101`,+ );+ expect(response.status).toBe(400);+ expect(response.headers.get("Content-Type")).toContain("text/plain");+ });+ it("returns empty pages and an empty project without inventing tasks", async () => {+ const { project, app } = await fixture(0);+ for (const page of [1, 10]) {+ const response = await app.request(+ `/api/task/tasks/${project.id}?page=${page}`,+ );+ const payload = await response.json();+ expect(allTasks(payload.data)).toHaveLength(0);+ expect(payload.data.columns).toHaveLength(4);+ expect(payload.pagination).toMatchObject({+ total: 0,+ totalPages: 1,+ page,+ });+ }+ });+});diff --git a/tests/api-integration/task-position-bounds.test.ts b/tests/api-integration/task-position-bounds.test.tsnew file mode 100644index 000000000..380d918d4--- /dev/null+++ b/tests/api-integration/task-position-bounds.test.ts@@ -0,0 +1,177 @@+import { asc, eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import createTask from "../../apps/api/src/task/controllers/create-task";+import moveTask from "../../apps/api/src/task/controllers/move-task";+import { MAX_TASK_POSITION } from "../../apps/api/src/task/controllers/next-task-position";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++vi.mock("../../apps/api/src/events", async (original) => ({+ ...(await original<object>()),+ publishEvent: vi.fn(async () => undefined),+}));+beforeEach(async () => {+ await resetTestDatabase();+});+async function setup() {+ const member = await createWorkspaceMember();+ const { project, columns } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ mockAuthenticatedSession(member.user);+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ columnId: columns.todo.id,+ title: "Original",+ status: "to-do",+ number: 1,+ position: 1,+ })+ .returning();+ await db+ .update(schema.projectTable)+ .set({ lastTaskNumber: 1 })+ .where(eq(schema.projectTable.id, project.id));+ return { ...member, project, columns, task };+}++describe("task position bounds and legacy recovery", () => {+ it.each([-1, 0.5, 2_147_483_647, 2_147_483_648, Number.MAX_SAFE_INTEGER])(+ "rejects unsafe position %s before updating any task field",+ async (position) => {+ const { project, task } = await setup();+ const { app } = createApp();+ const response = await app.request(`/api/task/${task.id}`, {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ title: "Should not write",+ description: "",+ status: "to-do",+ priority: "low",+ projectId: project.id,+ position,+ }),+ });+ expect(response.status).toBe(400);+ expect(+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, task.id),+ }),+ ).toMatchObject({ title: "Original", position: 1 });+ },+ );++ it("accepts bounded positions and recovers legacy overflow without touching other columns", async () => {+ const { project, columns, task, user } = await setup();+ await db+ .update(schema.taskTable)+ .set({ position: 2_147_483_647 })+ .where(eq(schema.taskTable.id, task.id));+ const [earlier, other] = await db+ .insert(schema.taskTable)+ .values([+ {+ projectId: project.id,+ columnId: columns.todo.id,+ title: "Earlier",+ number: 2,+ status: "to-do",+ position: 10,+ },+ {+ projectId: project.id,+ columnId: columns.done.id,+ title: "Other column",+ number: 3,+ status: "done",+ position: 999,+ },+ ])+ .returning();+ await db+ .update(schema.projectTable)+ .set({ lastTaskNumber: 3 })+ .where(eq(schema.projectTable.id, project.id));+ const appended = await createTask({+ projectId: project.id,+ currentUserId: user.id,+ title: "Appended",+ status: "to-do",+ });+ expect(appended.position).toBe(3);+ const rows = await db.query.taskTable.findMany({+ orderBy: asc(schema.taskTable.position),+ });+ expect(rows.map((row) => [row.id, row.position])).toEqual([+ [earlier.id, 1],+ [task.id, 2],+ [appended.id, 3],+ [other.id, 999],+ ]);+ });++ it("repairs virtual-status tasks and serializes concurrent appends", async () => {+ const { project, task, user } = await setup();+ await db+ .update(schema.taskTable)+ .set({ status: "planned", columnId: null, position: MAX_TASK_POSITION })+ .where(eq(schema.taskTable.id, task.id));+ const added = await Promise.all(+ Array.from({ length: 4 }, (_, index) =>+ createTask({+ projectId: project.id,+ currentUserId: user.id,+ title: `New ${index}`,+ status: "planned",+ }),+ ),+ );+ expect(added.map((row) => row.position).sort()).toEqual([2, 3, 4, 5]);+ expect(new Set(added.map((row) => row.number)).size).toBe(4);+ });++ it("recovers an overflowed destination when moving a task", async () => {+ const { project, user, workspace, task } = await setup();+ const { project: destination, columns } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const [poisoned] = await db+ .insert(schema.taskTable)+ .values({+ projectId: destination.id,+ columnId: columns.todo.id,+ title: "Existing",+ status: "to-do",+ position: 2_147_483_647,+ })+ .returning();+ await db+ .update(schema.projectTable)+ .set({ lastTaskNumber: 1 })+ .where(eq(schema.projectTable.id, destination.id));+ const result = await moveTask({+ taskId: task.id,+ destinationProjectId: destination.id,+ currentUserId: user.id,+ });+ expect(result.task).toMatchObject({+ projectId: destination.id,+ position: 2,+ });+ expect(+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, poisoned.id),+ }),+ ).toHaveProperty("position", 1);+ expect(result.sourceProjectId).toBe(project.id);+ });+});diff --git a/tests/api-integration/task-related-pages.test.ts b/tests/api-integration/task-related-pages.test.tsnew file mode 100644index 000000000..b3168b434--- /dev/null+++ b/tests/api-integration/task-related-pages.test.ts@@ -0,0 +1,190 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it } from "vitest";+import db, { getDatabasePool, schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import getTasks from "../../apps/api/src/task/controllers/get-tasks";+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++beforeEach(resetTestDatabase);+async function fixture() {+ const member = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ await db+ .update(schema.projectTable)+ .set({ isPublic: true })+ .where(eq(schema.projectTable.id, project.id));+ await db.insert(schema.columnTable).values(+ Array.from({ length: 237 }, (_, i) => ({+ id: `column-${i}`,+ projectId: project.id,+ slug: `extra-${i}`,+ name: `Extra ${i}`,+ position: i + 4,+ })),+ );+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Late column task",+ number: 1,+ status: "extra-236",+ description: "Body",+ })+ .returning();+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({ projectId: project.id, type: "github", config: "{}" })+ .returning();+ await db.insert(schema.labelTable).values(+ Array.from({ length: 237 }, (_, i) => ({+ id: `label-${String(i).padStart(3, "0")}`,+ taskId: task.id,+ workspaceId: member.workspace.id,+ name: `Label ${i}`,+ color: "red",+ })),+ );+ await db.insert(schema.externalLinkTable).values(+ Array.from({ length: 203 }, (_, i) => ({+ id: `link-${String(i).padStart(3, "0")}`,+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: String(i),+ url: `https://example.com/issues/${i}`,+ metadata: JSON.stringify({ state: "open" }),+ })),+ );+ mockAuthenticatedSession(member.user);+ return { ...createApp(), member, project, task };+}++describe("bounded board related pages", () => {+ it.each([false, true])(+ "returns bounded rows and all related records on the public=%s path",+ async (isPublic) => {+ const { app, project, task } = await fixture();+ if (isPublic) mockAnonymousSession();+ const labels = new Set<string>();+ const links = new Set<string>();+ const columns = new Set<string>();+ for (let relatedPage = 1; relatedPage <= 3; relatedPage++) {+ const response = await app.request(+ `/api/${isPublic ? "public-project" : "task/tasks"}/${project.id}?relatedPage=${relatedPage}`,+ );+ expect(response.status).toBe(200);+ const json = await response.json();+ const board = isPublic ? json : json.data;+ expect(json.pagination).toMatchObject({+ total: 1,+ totalPages: 1,+ relatedPage,+ relatedTotalPages: 3,+ relatedPageSize: 100,+ });+ expect(board.columns.length).toBeLessThanOrEqual(101);+ const tasks = board.columns.flatMap(+ (column: {+ tasks: {+ id: string;+ labels: { id: string }[];+ externalLinks: { id: string }[];+ }[];+ }) => column.tasks,+ );+ expect(tasks).toHaveLength(1);+ expect(tasks[0].id).toBe(task.id);+ expect(tasks[0].labels.length).toBeLessThanOrEqual(100);+ expect(tasks[0].externalLinks.length).toBeLessThanOrEqual(100);+ for (const value of tasks[0].labels) labels.add(value.id);+ for (const value of tasks[0].externalLinks) links.add(value.id);+ for (const value of board.columns) columns.add(value.id);+ }+ expect(labels.size).toBe(237);+ expect(links.size).toBe(203);+ expect(columns.size).toBe(241);+ },+ );+ it("does not let malformed legacy link metadata break the board", async () => {+ const { project, task } = await fixture();+ for (const metadata of ["broken {", "null", '"primitive"', "[1,2]"]) {+ await db+ .update(schema.externalLinkTable)+ .set({ metadata })+ .where(eq(schema.externalLinkTable.id, "link-000"));+ const response = await getTasks(project.id);+ expect(+ response.data.columns+ .flatMap((column) => column.tasks)+ .find((entry) => entry.id === task.id)?.externalLinks[0]?.metadata,+ ).toBeNull();+ }+ });+ it("rejects other workspaces, revoked public visibility and invalid metadata pages", async () => {+ const { app, project } = await fixture();+ for (const query of [+ "relatedPage=0",+ "relatedPage=-1",+ "relatedPage=1000001",+ "relatedPage=1e4",+ ])+ expect(+ (await app.request(`/api/task/tasks/${project.id}?${query}`)).status,+ ).toBe(400);+ const other = await createWorkspaceMember();+ mockAuthenticatedSession(other.user);+ expect(+ (await app.request(`/api/task/tasks/${project.id}?relatedPage=2`)).status,+ ).toBe(403);+ mockAnonymousSession();+ await db+ .update(schema.projectTable)+ .set({ isPublic: false })+ .where(eq(schema.projectTable.id, project.id));+ expect(+ (await app.request(`/api/public-project/${project.id}?relatedPage=2`))+ .status,+ ).toBe(403);+ });+ it("keeps association counts scoped to the selected task page", async () => {+ const { project } = await fixture();+ await db.insert(schema.taskTable).values({+ projectId: project.id,+ title: "No related records",+ number: 2,+ status: "planned",+ });+ const page = await getTasks(project.id, {+ page: 2,+ limit: 1,+ sortBy: "number",+ });+ expect(page.data.plannedTasks).toHaveLength(1);+ expect(page.data.plannedTasks[0].labels).toEqual([]);+ expect(page.data.plannedTasks[0].externalLinks).toEqual([]);+ expect(page.pagination.totalPages).toBe(2);+ });+ it("limits expensive list queries with a retryable database timeout", async () => {+ const { project } = await fixture();+ const lock = await getDatabasePool().connect();+ try {+ await lock.query("BEGIN");+ await lock.query('LOCK TABLE "task" IN ACCESS EXCLUSIVE MODE');+ await expect(getTasks(project.id)).rejects.toMatchObject({+ status: 503,+ message: "Task list request took too long; retry later",+ });+ } finally {+ await lock.query("ROLLBACK");+ lock.release();+ }+ });+});diff --git a/tests/api-integration/task-relation-boundaries.test.ts b/tests/api-integration/task-relation-boundaries.test.tsnew file mode 100644index 000000000..6715e4212--- /dev/null+++ b/tests/api-integration/task-relation-boundaries.test.ts@@ -0,0 +1,151 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const m = vi.hoisted(() => ({ publish: vi.fn(async () => undefined) }));+vi.mock("../../apps/api/src/events", async (original) => ({+ ...(await original<object>()),+ publishEvent: m.publish,+}));+beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+});+async function context() {+ const member = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({ projectId: project.id, title: "Private title", number: 1 })+ .returning();+ return { ...member, task };+}+function request(path: string, method: string, body?: unknown) {+ return createApp().app.request(`/api/task-relation${path}`, {+ method,+ ...(body === undefined+ ? {}+ : {+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ }),+ });+}+async function seedRelation(sourceTaskId: string, targetTaskId: string) {+ const [relation] = await db+ .insert(schema.taskRelationTable)+ .values({ sourceTaskId, targetTaskId, relationType: "blocks" })+ .returning();+ return relation;+}++describe("task relation tenant boundaries", () => {+ it("rejects a foreign target and a nonexistent target identically", async () => {+ const own = await context();+ const foreign = await context();+ mockAuthenticatedSession(own.user);+ for (const targetTaskId of [foreign.task.id, "missing-task"]) {+ const response = await request("", "POST", {+ sourceTaskId: own.task.id,+ targetTaskId,+ relationType: "blocks",+ });+ expect(response.status).toBe(404);+ expect(await response.text()).toBe("Target task not found");+ }+ expect(await db.query.taskRelationTable.findMany()).toHaveLength(0);+ expect(m.publish).not.toHaveBeenCalled();+ });++ it.each([false, true])(+ "hides legacy cross-workspace relations from reads in either direction (reverse=%s)",+ async (reverse) => {+ const own = await context();+ const foreign = await context();+ await seedRelation(+ reverse ? foreign.task.id : own.task.id,+ reverse ? own.task.id : foreign.task.id,+ );+ for (const member of [own, foreign]) {+ mockAuthenticatedSession(member.user);+ const response = await request(`/${member.task.id}`, "GET");+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual([]);+ }+ },+ );++ it("rejects deletion of a legacy foreign-target row without mutation or event", async () => {+ const own = await context();+ const foreign = await context();+ const relation = await seedRelation(own.task.id, foreign.task.id);+ mockAuthenticatedSession(own.user);+ const response = await request(`/${relation.id}`, "DELETE");+ expect(response.status).toBe(404);+ expect(await response.text()).toBe("Task relation not found");+ expect(+ await db.query.taskRelationTable.findFirst({+ where: eq(schema.taskRelationTable.id, relation.id),+ }),+ ).toBeDefined();+ expect(m.publish).not.toHaveBeenCalled();+ });++ it("requires source-workspace access for deletion even when the target is owned", async () => {+ const own = await context();+ const foreign = await context();+ const relation = await seedRelation(foreign.task.id, own.task.id);+ mockAuthenticatedSession(own.user);+ expect((await request(`/${relation.id}`, "DELETE")).status).toBe(403);+ expect(await db.query.taskRelationTable.findMany()).toHaveLength(1);+ expect(m.publish).not.toHaveBeenCalled();+ });++ it("keeps same-workspace cross-project relations fully usable", async () => {+ const own = await context();+ const { project } = await createProjectFixture({+ workspaceId: own.workspace.id,+ });+ const [target] = await db+ .insert(schema.taskTable)+ .values({ projectId: project.id, title: "Related", number: 1 })+ .returning();+ mockAuthenticatedSession(own.user);+ const created = await request("", "POST", {+ sourceTaskId: own.task.id,+ targetTaskId: target.id,+ relationType: "related",+ });+ expect(created.status).toBe(200);+ const relation = (await created.json()) as { id: string };+ for (const task of [own.task, target]) {+ const response = await request(`/${task.id}`, "GET");+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject([+ {+ id: relation.id,+ sourceTask: { id: own.task.id },+ targetTask: { id: target.id },+ },+ ]);+ }+ expect((await request(`/${relation.id}`, "DELETE")).status).toBe(200);+ expect(await db.query.taskRelationTable.findMany()).toHaveLength(0);+ expect(m.publish).toHaveBeenCalledWith(+ "task-relation.deleted",+ expect.objectContaining({+ sourceTaskId: own.task.id,+ targetTaskId: target.id,+ }),+ );+ });+});diff --git a/tests/api-integration/tenant-resource-boundaries.test.ts b/tests/api-integration/tenant-resource-boundaries.test.tsnew file mode 100644index 000000000..f5382bdcc--- /dev/null+++ b/tests/api-integration/tenant-resource-boundaries.test.ts@@ -0,0 +1,197 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import deleteLabel from "../../apps/api/src/label/controllers/delete-label";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const { syncGithub, syncGitea, removeGithub, removeGitea, publish } =+ vi.hoisted(() => ({+ syncGithub: vi.fn(async () => undefined),+ syncGitea: vi.fn(async () => undefined),+ removeGithub: vi.fn(async () => undefined),+ removeGitea: vi.fn(async () => undefined),+ publish: vi.fn(async () => undefined),+ }));+vi.mock("../../apps/api/src/plugins/github/utils/sync-label-to-github", () => ({+ syncLabelToGitHub: syncGithub,+ removeLabelFromGitHub: removeGithub,+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/sync-label-to-gitea", () => ({+ syncLabelToGitea: syncGitea,+ removeLabelFromGitea: removeGitea,+}));+vi.mock("../../apps/api/src/events", async (original) => ({+ ...(await original<object>()),+ publishEvent: publish,+}));++async function context() {+ const member = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ title: "Private task",+ projectId: project.id,+ number: 1,+ })+ .returning();+ return { ...member, project, task };+}+function request(path: string, method: string, body?: unknown) {+ return createApp().app.request(`/api${path}`, {+ method,+ ...(body === undefined+ ? {}+ : {+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ }),+ });+}+async function label(workspaceId: string, taskId: string | null) {+ const [row] = await db+ .insert(schema.labelTable)+ .values({+ workspaceId,+ taskId,+ name: "bug",+ color: "#ff0000",+ })+ .returning();+ return row;+}++describe("tenant resource boundaries", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+ });++ it("rejects foreign and nonexistent task IDs before creating or syncing a label", async () => {+ const own = await context();+ const foreign = await context();+ mockAuthenticatedSession(own.user);+ for (const taskId of [foreign.task.id, "missing-task"]) {+ const response = await request("/label", "POST", {+ name: "bug",+ color: "#ff0000",+ workspaceId: own.workspace.id,+ taskId,+ });+ expect(response.status).toBe(404);+ expect(await response.text()).toBe("Task not found");+ }+ expect(await db.select().from(schema.labelTable)).toHaveLength(0);+ expect(syncGithub).not.toHaveBeenCalled();+ expect(syncGitea).not.toHaveBeenCalled();+ expect(publish).not.toHaveBeenCalled();+ expect(+ (+ await request("/label", "POST", {+ name: "bug",+ color: "#ff0000",+ workspaceId: own.workspace.id,+ taskId: own.task.id,+ })+ ).status,+ ).toBe(200);+ expect(syncGithub).toHaveBeenCalledWith(own.task.id, "bug", "#ff0000");+ expect(syncGitea).toHaveBeenCalledWith(own.task.id, "bug", "#ff0000");+ });++ it("rejects legacy cross-workspace label rows at every label-ID endpoint", async () => {+ const own = await context();+ const foreign = await context();+ const forged = await label(own.workspace.id, foreign.task.id);+ mockAuthenticatedSession(own.user);+ for (const [suffix, method, body] of [+ ["", "GET", undefined],+ ["", "DELETE", undefined],+ ["", "PUT", { name: "changed", color: "#ffffff" }],+ ["/task", "DELETE", undefined],+ ["/task", "PUT", { taskId: own.task.id }],+ ] as const) {+ expect(+ (await request(`/label/${forged.id}${suffix}`, method, body)).status,+ ).toBe(400);+ }+ await expect(deleteLabel(forged.id, own.user.id)).rejects.toMatchObject({+ status: 404,+ });+ expect(await db.select().from(schema.labelTable)).toEqual([forged]);+ expect(syncGithub).not.toHaveBeenCalled();+ expect(syncGitea).not.toHaveBeenCalled();+ expect(removeGithub).not.toHaveBeenCalled();+ expect(removeGitea).not.toHaveBeenCalled();+ expect(publish).not.toHaveBeenCalled();+ });++ it("does not sync or publish foreign tasks when cleaning up a workspace label", async () => {+ const own = await context();+ const foreign = await context();+ const root = await label(own.workspace.id, null);+ await label(own.workspace.id, own.task.id);+ await label(own.workspace.id, foreign.task.id);+ const untouched = await label(foreign.workspace.id, null);+ mockAuthenticatedSession(own.user);+ expect((await request(`/label/${root.id}`, "DELETE")).status).toBe(200);+ expect(await db.select().from(schema.labelTable)).toEqual([untouched]);+ expect(removeGithub.mock.calls).toEqual([[own.task.id, "bug"]]);+ expect(removeGitea.mock.calls).toEqual([[own.task.id, "bug"]]);+ expect(publish).toHaveBeenCalledTimes(1);+ expect(publish).toHaveBeenCalledWith(+ "task.label_deleted",+ expect.objectContaining({ taskId: own.task.id }),+ { waitForHandlers: true },+ );+ });++ it("uses the same response for missing and foreign move destinations and still permits local moves", async () => {+ const own = await context();+ const foreign = await context();+ mockAuthenticatedSession(own.user);+ const responses = [];+ for (const destinationProjectId of [+ "missing-project",+ foreign.project.id,+ ]) {+ const response = await request(`/task/move/${own.task.id}`, "PUT", {+ destinationProjectId,+ });+ responses.push({ status: response.status, body: await response.text() });+ }+ expect(responses).toEqual([+ { status: 404, body: "Project not found" },+ { status: 404, body: "Project not found" },+ ]);+ expect(+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, own.task.id),+ }),+ ).toEqual(own.task);+ expect(publish).not.toHaveBeenCalled();+ const { project } = await createProjectFixture({+ workspaceId: own.workspace.id,+ });+ const response = await request(`/task/move/${own.task.id}`, "PUT", {+ destinationProjectId: project.id,+ });+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ task: { id: own.task.id, projectId: project.id },+ });+ expect(publish).toHaveBeenCalledWith(+ "task.moved",+ expect.objectContaining({ toProjectId: project.id }),+ );+ });+});diff --git a/tests/api-integration/trial-reminders.test.ts b/tests/api-integration/trial-reminders.test.tsindex 43d9775e4..047092780 100644--- a/tests/api-integration/trial-reminders.test.ts+++ b/tests/api-integration/trial-reminders.test.ts@@ -189,6 +189,37 @@ describe("trial reminder emails", () => {expect(sendTrialReminderEmail).toHaveBeenCalledTimes(2);});+ it("shares one cap across both reminder types and leaves unsent rows for the next run", async () => {+ for (let i = 0; i < 2; i++) {+ await seedTrial(new Date(Date.now() + 2.5 * DAY));+ await seedTrial(new Date(Date.now() - DAY));+ }+ await checkTrialReminders();+ expect(sendTrialReminderEmail).toHaveBeenCalledTimes(2);+ expect(+ await db.select().from(schema.billingReminderSentTable),+ ).toHaveLength(2);+ await checkTrialReminders();+ expect(sendTrialReminderEmail).toHaveBeenCalledTimes(4);+ expect(new Set(recipients()).size).toBe(4);+ expect(+ await db.select().from(schema.billingReminderSentTable),+ ).toHaveLength(4);+ });++ it("spends only the remaining budget on the second reminder type", async () => {+ const ending = await seedTrial(new Date(Date.now() + 2.5 * DAY));+ for (let i = 0; i < 3; i++) await seedTrial(new Date(Date.now() - DAY));+ await checkTrialReminders();+ expect(sendTrialReminderEmail).toHaveBeenCalledTimes(2);+ expect(recipients()).toContain(ending.user.email);+ const rows = await db.select().from(schema.billingReminderSentTable);+ expect(rows.map((row) => row.reminderType).sort()).toEqual([+ "trial_ending",+ "trial_expired",+ ]);+ });+it("sends the most urgent trials first", async () => {const soonest = await seedTrial(new Date(Date.now() - 9 * DAY));await seedTrial(new Date(Date.now() - 2 * DAY));diff --git a/tests/api-integration/websocket-security.test.ts b/tests/api-integration/websocket-security.test.tsnew file mode 100644index 000000000..4182c1d14--- /dev/null+++ b/tests/api-integration/websocket-security.test.ts@@ -0,0 +1,218 @@+import { once } from "node:events";+import type { IncomingMessage } from "node:http";+import { createRequire } from "node:module";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { serve } from "../../apps/api/node_modules/@hono/node-server";+import type { NodeWebSocket } from "../../apps/api/node_modules/@hono/node-ws";+import { auth } from "../../apps/api/src/auth";+import { createApp } from "../../apps/api/src/index";+import { broadcastToUser } from "../../apps/api/src/ws";+import { handleWebSocketMessage } from "../../apps/api/src/ws/security";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++// Use the actual client from node-ws's installed dependency, without adding a+// production dependency or connecting to any remote server.+type Socket = NodeWebSocket["wss"]["clients"] extends Set<infer S> ? S : never;+const apiRequire = createRequire(+ new URL("../../apps/api/package.json", import.meta.url),+);+const nodeWsRequire = createRequire(apiRequire.resolve("@hono/node-ws"));+const WebSocket: new (+ url: string,+ options: { headers: Record<string, string> },+) => Socket = nodeWsRequire("ws").WebSocket;++vi.mock("../../apps/api/src/ws/security", async (original) => {+ const actual =+ await original<typeof import("../../apps/api/src/ws/security")>();+ return {+ ...actual,+ handleWebSocketMessage: vi.fn(actual.handleWebSocketMessage),+ };+});++let server: ReturnType<typeof serve>;+let baseUrl: string;+let userId: string;+let projectId: string;+const sockets: Socket[] = [];+async function connect(path: string, headers: Record<string, string>) {+ const socket = new WebSocket(`${baseUrl}/api/ws/${path}`, { headers });+ sockets.push(socket);+ socket.on("error", () => {});+ const status = await new Promise<number>((resolve) => {+ socket.once("open", () => resolve(101));+ socket.once(+ "unexpected-response",+ (_request: unknown, response: IncomingMessage) => {+ response.resume();+ resolve(response.statusCode ?? 0);+ socket.terminate();+ },+ );+ });+ return { socket, status };+}++beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+ vi.stubEnv("CORS_ORIGINS", "https://extra.example.test");+ const member = await createWorkspaceMember();+ userId = member.user.id;+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ projectId = project.id;+ const sessionMock = mockAuthenticatedSession(member.user);+ const session = await auth.api.getSession({ headers: new Headers() });+ sessionMock.mockImplementation(async ({ headers }) => {+ const h = new Headers(headers);+ return h.get("authorization") === "Bearer valid-test-session" ||+ h.get("cookie") === "test-session=valid"+ ? session+ : null;+ });+ const created = createApp();+ server = serve({ fetch: created.app.fetch, hostname: "127.0.0.1", port: 0 });+ created.injectWebSocket(server);+ if (!server.listening) await once(server, "listening");+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("No test port");+ baseUrl = `ws://127.0.0.1:${address.port}`;+});++afterEach(async () => {+ for (const socket of sockets.splice(0)) socket.terminate();+ if (server)+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ vi.unstubAllEnvs();+});++describe.each(["project", "user"])("%s WebSocket", (endpoint) => {+ const path = () => (endpoint === "user" ? "user" : projectId);+ it("rejects missing, null, hostile and lookalike browser origins", async () => {+ for (const origin of [+ undefined,+ "null",+ "https://evil.example.test",+ "http://localhost:5173.evil.test",+ "http://localhost:5173/",+ "http://localhost:5174",+ ]) {+ const { status } = await connect(path(), {+ cookie: "test-session=valid",+ ...(origin === undefined ? {} : { origin }),+ });+ expect(status, String(origin)).toBe(403);+ }+ });+ it("allows configured origins and explicit native sessions, retaining authentication", async () => {+ for (const origin of [+ "http://localhost:5173",+ "http://localhost:1337",+ "https://extra.example.test",+ ]) {+ expect(+ (await connect(path(), { cookie: "test-session=valid", origin }))+ .status,+ ).toBe(101);+ }+ expect(+ (await connect(path(), { authorization: "Bearer valid-test-session" }))+ .status,+ ).toBe(101);+ expect(+ (+ await connect(path(), {+ authorization: "Bearer invalid",+ cookie: "test-session=valid",+ })+ ).status,+ ).toBe(401);+ expect(+ (await connect(path(), { origin: "http://localhost:5173" })).status,+ ).toBe(401);+ });+ it.each(["text", "binary", "fragmented"])(+ "rejects oversized %s messages before application delivery",+ async (kind) => {+ const { socket, status } = await connect(path(), {+ cookie: "test-session=valid",+ origin: "http://localhost:5173",+ });+ expect(status).toBe(101);+ const closed = once(socket, "close");+ if (kind === "fragmented") {+ socket.send("a".repeat(40), { fin: false });+ socket.send("b".repeat(40), { fin: true });+ } else {+ socket.send(kind === "binary" ? Buffer.alloc(65) : "a".repeat(65));+ }+ expect((await closed)[0]).toBe(1009);+ expect(handleWebSocketMessage).not.toHaveBeenCalled();+ },+ );+ it.each([+ ["unsupported JSON", '{"type":"other"}', 1008],+ ["malformed JSON", "{", 1008],+ ["binary ping", Buffer.from('{"type":"ping"}'), 1003],+ ] as const)(+ "closes %s and keeps valid pings working",+ async (_name, payload, code) => {+ const { socket, status } = await connect(path(), {+ cookie: "test-session=valid",+ origin: "http://localhost:5173",+ });+ expect(status).toBe(101);+ socket.send('{"type":"ping"}');+ const pong = once(socket, "pong");+ socket.ping("test");+ await pong;+ expect(socket.readyState).toBe(1);+ const closed = once(socket, "close");+ socket.send(payload);+ expect((await closed)[0]).toBe(code);+ },+ );+});++it("preserves user event delivery after keepalive", async () => {+ const { socket, status } = await connect("user", {+ cookie: "test-session=valid",+ origin: "http://localhost:5173",+ });+ expect(status).toBe(101);+ socket.send('{"type":"ping"}');+ const message = once(socket, "message");+ broadcastToUser(userId, {+ type: "NOTIFICATION_CREATED",+ notificationId: "local-only",+ });+ expect(JSON.parse((await message)[0].toString())).toEqual({+ type: "NOTIFICATION_CREATED",+ notificationId: "local-only",+ });+});++it("still rejects access to a foreign project with a valid Origin", async () => {+ const foreign = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: foreign.workspace.id,+ });+ expect(+ (+ await connect(project.id, {+ cookie: "test-session=valid",+ origin: "http://localhost:5173",+ })+ ).status,+ ).toBe(403);+});diff --git a/tests/api-integration/workspace-rbac.test.ts b/tests/api-integration/workspace-rbac.test.tsindex ecd1d3b46..d31b459b1 100644--- a/tests/api-integration/workspace-rbac.test.ts+++ b/tests/api-integration/workspace-rbac.test.ts@@ -1,6 +1,6 @@import { randomUUID } from "node:crypto";import { and, eq, inArray } from "drizzle-orm";-import { beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import db, { schema } from "../../apps/api/src/database";import { createApp } from "../../apps/api/src/index";import { mockAuthenticatedSession } from "./helpers/auth";@@ -10,6 +10,16 @@ import {createWorkspaceMember,} from "./helpers/fixtures";+// Assignment notifications run in the background and can otherwise race the+// next test's TRUNCATE. Notification access/delivery has its own DB suite;+// these tests exercise the real authorization and resource mutations.+vi.mock(+ "../../apps/api/src/notification/controllers/create-notification",+ () => ({+ default: vi.fn(async () => null),+ }),+);+type CreateTaskBody = {title: string;description: string;diff --git a/tests/api-integration/workspace-role-demotion.test.ts b/tests/api-integration/workspace-role-demotion.test.tsnew file mode 100644index 000000000..517070e20--- /dev/null+++ b/tests/api-integration/workspace-role-demotion.test.ts@@ -0,0 +1,103 @@+import { beforeEach, expect, it } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { defaultRolePayloads } from "../../packages/permissions/src";+import { resetTestDatabase } from "./helpers/database";++const origin = "http://localhost:5173";+const { app } = createApp();+async function post(path: string, body: unknown, cookie = "") {+ return app.request(`/api/auth${path}`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ Origin: origin,+ Cookie: cookie,+ },+ body: JSON.stringify(body),+ });+}+async function signup(email: string) {+ const result = await post("/sign-up/email", {+ name: "Role test",+ email,+ password: "long-password-for-tests",+ });+ expect(result.status).toBe(200);+ const body = await result.json();+ const cookie = result.headers+ .getSetCookie()+ .map((entry) => entry.split(";")[0])+ .join("; ");+ return { id: body.user.id as string, cookie };+}+beforeEach(() => resetTestDatabase());+it("revokes provider administrative permissions after the owner saves an empty role", async () => {+ const owner = await signup("[email protected]");+ const admin = await signup("[email protected]");+ const [workspace] = await db+ .insert(schema.workspaceTable)+ .values({+ id: "role-workspace",+ name: "Workspace",+ slug: "roles",+ createdAt: new Date(),+ })+ .returning();+ await db.insert(schema.workspaceUserTable).values([+ {+ workspaceId: workspace.id,+ userId: owner.id,+ role: "owner",+ joinedAt: new Date(),+ },+ {+ workspaceId: workspace.id,+ userId: admin.id,+ role: "admin",+ joinedAt: new Date(),+ },+ ]);+ await db.insert(schema.workspaceRoleTable).values({+ workspaceId: workspace.id,+ role: "admin",+ permission: JSON.stringify(defaultRolePayloads.admin),+ createdAt: new Date(),+ updatedAt: new Date(),+ });+ const canManage = () =>+ post(+ "/organization/has-permission",+ {+ organizationId: workspace.id,+ permissions: {+ ac: ["update"],+ member: ["update"],+ invitation: ["create"],+ },+ },+ admin.cookie,+ );+ expect(await (await canManage()).json()).toMatchObject({ success: true });+ const demote = await post(+ "/organization/update-role",+ {+ organizationId: workspace.id,+ roleName: "admin",+ data: { permission: {} },+ },+ owner.cookie,+ );+ expect(demote.status).toBe(200);+ expect(await (await canManage()).json()).toMatchObject({ success: false });+ const restore = await post(+ "/organization/update-role",+ {+ organizationId: workspace.id,+ roleName: "admin",+ data: { permission: defaultRolePayloads.admin },+ },+ admin.cookie,+ );+ expect(restore.status).toBe(403);+});diff --git a/tests/api/billing/session-required.test.ts b/tests/api/billing/session-required.test.tsnew file mode 100644index 000000000..4767c2f05--- /dev/null+++ b/tests/api/billing/session-required.test.ts@@ -0,0 +1,105 @@+import { Hono } from "hono";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ checkout: vi.fn(async () => ({+ checkoutUrl: "https://example.invalid/checkout",+ })),+ portal: vi.fn(async () => ({ portalUrl: "https://example.invalid/portal" })),+ token: vi.fn(async () => ({ idToken: "sensitive-id-token" })),+ access: vi.fn(async () => {}),+}));+vi.mock("../../../apps/api/src/database", () => ({+ default: {+ select: () => ({+ from: () => ({ where: async () => [{ role: "owner" }] }),+ }),+ },+}));+vi.mock("../../../apps/api/src/utils/validate-workspace-access", () => ({+ validateWorkspaceAccess: mocks.access,+}));+vi.mock("../../../apps/api/src/billing/controllers/create-checkout", () => ({+ default: mocks.checkout,+}));+vi.mock(+ "../../../apps/api/src/billing/controllers/get-workspace-billing",+ () => ({+ default: vi.fn(),+ getOrCreateWorkspaceBilling: async () => ({ creemCustomerId: "customer" }),+ }),+);+vi.mock("../../../apps/api/src/billing/controllers/handle-webhook", () => ({+ default: vi.fn(),+}));+vi.mock("../../../apps/api/src/billing/creem-client", () => ({+ createCustomerPortalLink: mocks.portal,+}));+vi.mock("../../../apps/api/src/oauth/controllers/get-id-token", () => ({+ default: mocks.token,+}));++const { default: billing } = await import("../../../apps/api/src/billing");+const { default: oauth } = await import("../../../apps/api/src/oauth");++function appFor(apiKey: object | null, session = true) {+ const app = new Hono();+ app.use("*", async (c, next) => {+ c.set("userId", "owner");+ c.set("userEmail", "[email protected]");+ if (apiKey) c.set("apiKey", apiKey);+ if (session) {+ c.set("user", { id: "owner" });+ c.set("session", { id: "session-owner" });+ }+ await next();+ });+ app.route("/billing", billing);+ app.route("/oauth", oauth);+ return app;+}++const endpoints = [+ ["/billing/workspace/checkout", "POST", mocks.checkout],+ ["/billing/workspace/portal", "POST", mocks.portal],+ ["/oauth/id-token", "GET", mocks.token],+] as const;++function request(app: ReturnType<typeof appFor>, url: string, method: string) {+ return app.request(url, {+ method,+ headers: { "content-type": "application/json" },+ ...(url.endsWith("checkout")+ ? { body: JSON.stringify({ plan: "team", interval: "monthly" }) }+ : {}),+ });+}++describe("sensitive account routes require a session", () => {+ beforeEach(() => vi.clearAllMocks());+ for (const [url, method, effect] of endpoints) {+ it.each([+ { id: "readonly-key", permissions: { task: ["read"] } },+ { id: "unrestricted-key", permissions: null },+ ])(+ `${method} ${url} rejects API keys even for an owner with a cookie`,+ async (key) => {+ const response = await request(appFor(key), url, method);+ expect(response.status).toBe(403);+ expect(effect).not.toHaveBeenCalled();+ expect(mocks.access).not.toHaveBeenCalled();+ },+ );+ it(`${method} ${url} rejects a missing session`, async () => {+ const response = await request(appFor(null, false), url, method);+ expect(response.status).toBe(403);+ expect(effect).not.toHaveBeenCalled();+ });+ it(`${method} ${url} accepts an owner session without caching its response`, async () => {+ const response = await request(appFor(null), url, method);+ expect(response.status).toBe(200);+ expect(response.headers.get("cache-control")).toBe("no-store");+ expect(effect).toHaveBeenCalledOnce();+ });+ }+});diff --git a/tests/api/client-ip.test.ts b/tests/api/client-ip.test.tsnew file mode 100644index 000000000..1728ba6b0--- /dev/null+++ b/tests/api/client-ip.test.ts@@ -0,0 +1,101 @@+import { once } from "node:events";+import type { AddressInfo } from "node:net";+import { serve } from "@hono/node-server";+import { Hono } from "hono";+import { describe, expect, it } from "vitest";+import {+ clientIpMiddleware,+ createClientIpResolver,+} from "../../apps/api/src/utils/client-ip";++describe("trusted client IP resolution", () => {+ it("does not trust headers from a direct public or private peer by default", () => {+ const resolve = createClientIpResolver("");+ expect(resolve("203.0.113.5", "1.2.3.4")).toBe("203.0.113.5");+ expect(resolve("10.0.0.5", "1.2.3.4")).toBe("10.0.0.5");+ expect(resolve(undefined, "1.2.3.4")).toBeNull();+ });+ it("stops at the first untrusted appended hop behind bundled nginx", () => {+ const resolve = createClientIpResolver("");+ expect(resolve("127.0.0.1", "1.2.3.4, 203.0.113.5")).toBe("203.0.113.5");+ expect(resolve("::ffff:127.0.0.1", "1.2.3.4, 203.0.113.5")).toBe(+ "203.0.113.5",+ );+ });+ it("supports explicit Docker proxy subnets and IPv6 chains", () => {+ const resolve = createClientIpResolver(+ "127.0.0.0/8, 172.25.0.0/24, fd00:1234::/64",+ );+ expect(resolve("127.0.0.1", "1.2.3.4, 203.0.113.5, 172.25.0.2")).toBe(+ "203.0.113.5",+ );+ expect(resolve("fd00:1234::1", "2001:db8::1, fd00:1234::2")).toBe(+ "2001:db8::1",+ );+ });+ it.each([+ "not-an-ip",+ "127.0.0.1/33",+ "::1/129",+ "127.0.0.1/-1",+ "127.0.0.1/8/8",+ "127.0.0.1,",+ ])("fails closed for invalid proxy config %s", (config) => {+ expect(() => createClientIpResolver(config)).toThrow(/TRUSTED_PROXIES/);+ });+ it("falls back to the socket peer for malformed or excessive chains", () => {+ const resolve = createClientIpResolver("");+ for (const header of [+ "1.2.3.4, invalid",+ "x".repeat(8193),+ "127.0.0.1,".repeat(65),+ ])+ expect(resolve("127.0.0.1", header)).toBe("127.0.0.1");+ });+ it("removes spoofed canonical and Cloudflare values when no socket is available", async () => {+ const app = new Hono()+ .use(clientIpMiddleware())+ .get("/", (c) => c.text(c.req.header("x-kaneo-client-ip") ?? "none"));+ const response = await app.request("/", {+ headers: {+ "x-kaneo-client-ip": "1.2.3.4",+ "cf-connecting-ip": "1.2.3.4",+ "x-forwarded-for": "1.2.3.4",+ },+ });+ expect(await response.text()).toBe("none");+ });+ it.each(["none", "127.0.0.0/8"])(+ "uses the actual Node socket with proxy policy %s",+ async (config) => {+ const app = new Hono()+ .use(clientIpMiddleware(config))+ .get("/", (c) => c.text(c.req.header("x-kaneo-client-ip") ?? "none"));+ const server = serve({+ fetch: app.fetch,+ hostname: "127.0.0.1",+ port: 0,+ });+ await once(server, "listening");+ try {+ const response = await fetch(+ `http://127.0.0.1:${(server.address() as AddressInfo).port}/`,+ {+ headers: {+ "x-kaneo-client-ip": "1.2.3.4",+ "cf-connecting-ip": "5.6.7.8",+ "x-forwarded-for": "1.2.3.4, 203.0.113.5",+ },+ },+ );+ expect(await response.text()).toBe(+ config === "none" ? "127.0.0.1" : "203.0.113.5",+ );+ } finally {+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ }+ },+ );+});diff --git a/tests/api/events/publish-event.test.ts b/tests/api/events/publish-event.test.tsindex 33a3c3a46..75de9848a 100644--- a/tests/api/events/publish-event.test.ts+++ b/tests/api/events/publish-event.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import {eventContext,publishEvent,@@ -7,6 +7,50 @@ import {} from "../../../apps/api/src/events/index";describe("publishEvent / subscribeToEvent", () => {+ it("awaits subscriber completion in sequence when requested", async () => {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const calls: string[] = [];+ await subscribeToEvent("test.bounded", async () => {+ calls.push("first-start");+ await gate;+ calls.push("first-end");+ });+ await subscribeToEvent("test.bounded", async () => {+ calls.push("second");+ });+ let completed = false;+ const operation = publishEvent(+ "test.bounded",+ {},+ { waitForHandlers: true },+ ).then(() => {+ completed = true;+ });+ expect(calls).toEqual(["first-start"]);+ expect(completed).toBe(false);+ release();+ await operation;+ expect(calls).toEqual(["first-start", "first-end", "second"]);+ });++ it("keeps best-effort error isolation for awaited subscribers", async () => {+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ const next = vi.fn(async () => {});+ try {+ await subscribeToEvent("test.failure", async () => {+ throw new Error("subscriber failed");+ });+ await subscribeToEvent("test.failure", next);+ await publishEvent("test.failure", {}, { waitForHandlers: true });+ expect(next).toHaveBeenCalledTimes(1);+ expect(log).toHaveBeenCalledTimes(1);+ } finally {+ log.mockRestore();+ }+ });afterEach(async () => {await shutdownEventBus();});diff --git a/tests/api/github-integration/bounded-fetch.test.ts b/tests/api/github-integration/bounded-fetch.test.tsnew file mode 100644index 000000000..8227190c8--- /dev/null+++ b/tests/api/github-integration/bounded-fetch.test.ts@@ -0,0 +1,175 @@+import { generateKeyPairSync } from "node:crypto";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ boundedGithubFetch,+ GITHUB_IMPORT_REQUEST_TIMEOUT_MS,+ MAX_GITHUB_IMPORT_RESPONSE_BYTES,+} from "../../../apps/api/src/utils/bounded-github-fetch";++vi.mock("dotenv-mono", () => ({ config: () => {} }));+const request = vi.fn<typeof fetch>();+beforeEach(() => {+ request.mockReset();+ vi.stubGlobal("fetch", request);+});+afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+});+const url = "https://api.github.com/graphql";++describe("bounded GitHub import transport", () => {+ it("preserves successful JSON, headers and status while disabling redirects", async () => {+ request.mockResolvedValue(+ Response.json(+ { data: { ok: true } },+ { headers: { "x-ratelimit-remaining": "5" } },+ ),+ );+ const response = await boundedGithubFetch(url, { method: "POST" });+ expect(await response.json()).toEqual({ data: { ok: true } });+ expect(response.status).toBe(200);+ expect(response.headers.get("x-ratelimit-remaining")).toBe("5");+ expect(request.mock.calls[0][1]).toMatchObject({+ redirect: "error",+ method: "POST",+ });+ });++ it.each([null, "1"])(+ "bounds actual decoded bytes with Content-Length %s and cancels the stream",+ async (length) => {+ const cancel = vi.fn();+ let chunks = 0;+ request.mockResolvedValue(+ new Response(+ new ReadableStream({+ pull(controller) {+ chunks++;+ controller.enqueue(new Uint8Array(1024 * 1024));+ },+ cancel,+ }),+ { headers: length ? { "Content-Length": length } : {} },+ ),+ );+ await expect(boundedGithubFetch(url)).rejects.toThrow("too large");+ expect(chunks).toBeLessThanOrEqual(+ MAX_GITHUB_IMPORT_RESPONSE_BYTES / (1024 * 1024) + 2,+ );+ expect(cancel).toHaveBeenCalledOnce();+ expect(request.mock.calls[0][1]?.signal?.aborted).toBe(true);+ },+ );++ it("accepts the exact byte limit without truncation", async () => {+ request.mockResolvedValue(+ new Response(new Uint8Array(MAX_GITHUB_IMPORT_RESPONSE_BYTES)),+ );+ expect(+ (await (await boundedGithubFetch(url)).arrayBuffer()).byteLength,+ ).toBe(MAX_GITHUB_IMPORT_RESPONSE_BYTES);+ });++ it("times out before headers and cancels a late response", async () => {+ vi.useFakeTimers();+ let finish!: (response: Response) => void;+ request.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const pending = boundedGithubFetch(url);+ const rejected = expect(pending).rejects.toThrow("timed out");+ await vi.advanceTimersByTimeAsync(GITHUB_IMPORT_REQUEST_TIMEOUT_MS);+ await rejected;+ expect(request.mock.calls[0][1]?.signal?.aborted).toBe(true);+ const cancel = vi.fn();+ finish(new Response(new ReadableStream({ cancel })));+ await Promise.resolve();+ await Promise.resolve();+ expect(cancel).toHaveBeenCalledOnce();+ });++ it("times out on a stalled body even after successful headers", async () => {+ vi.useFakeTimers();+ const cancel = vi.fn();+ request.mockResolvedValue(new Response(new ReadableStream({ cancel })));+ const pending = boundedGithubFetch(url);+ const rejected = expect(pending).rejects.toThrow("timed out");+ await vi.advanceTimersByTimeAsync(GITHUB_IMPORT_REQUEST_TIMEOUT_MS);+ await rejected;+ expect(cancel).toHaveBeenCalledOnce();+ });++ it("passes through the caller's abort signal", async () => {+ const controller = new AbortController();+ controller.abort();+ request.mockImplementation(async (_url, init) => {+ init?.signal?.throwIfAborted();+ return Response.json({});+ });+ await expect(+ boundedGithubFetch(url, { signal: controller.signal }),+ ).rejects.toThrow();+ });++ it("applies bounded transport to real App authentication and installation clients without SDK retries", async () => {+ vi.resetModules();+ const { privateKey } = generateKeyPairSync("rsa", {+ modulusLength: 2048,+ privateKeyEncoding: { type: "pkcs8", format: "pem" },+ publicKeyEncoding: { type: "spki", format: "pem" },+ });+ vi.stubEnv("GITHUB_APP_ID", "123");+ vi.stubEnv("GITHUB_WEBHOOK_SECRET", "test-only-secret");+ vi.stubEnv("GITHUB_PRIVATE_KEY_BASE64", "");+ vi.stubEnv("GITHUB_PRIVATE_KEY", privateKey);+ request.mockImplementation(async (input) => {+ if (String(input).includes("/access_tokens"))+ return Response.json(+ {+ token: "test-only-token",+ expires_at: new Date(Date.now() + 3600000).toISOString(),+ },+ { status: 201 },+ );+ if (String(input).includes("/repos/")) return Response.json({ id: 2 });+ return Response.json(+ { message: "rate limited" },+ {+ status: 403,+ headers: {+ "x-ratelimit-remaining": "0",+ "x-ratelimit-reset": String(Math.floor(Date.now() / 1000) + 3600),+ },+ },+ );+ });+ const { getVerifiedInstallationOctokit } = await import(+ "../../../apps/api/src/plugins/github/utils/github-app"+ );+ const octokit = await getVerifiedInstallationOctokit(+ {+ repositoryOwner: "example",+ repositoryName: "repo",+ repositoryId: 2,+ installationId: 1,+ verifiedGithubAccountId: "3",+ verifiedByUserId: "test-user",+ },+ true,+ );+ await expect(+ octokit.graphql("query { viewer { login } }"),+ ).rejects.toMatchObject({ status: 403 });+ expect(request).toHaveBeenCalledTimes(3);+ for (const [, init] of request.mock.calls)+ expect(init).toMatchObject({+ redirect: "error",+ signal: expect.any(AbortSignal),+ });+ });+});diff --git a/tests/api/github-integration/outbound-binding.test.ts b/tests/api/github-integration/outbound-binding.test.tsnew file mode 100644index 000000000..ff506e948--- /dev/null+++ b/tests/api/github-integration/outbound-binding.test.ts@@ -0,0 +1,60 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const m = vi.hoisted(() => ({ repo: vi.fn(), client: vi.fn() }));+vi.mock("../../../apps/api/node_modules/octokit", () => ({+ App: class {+ getInstallationOctokit = m.client;+ },+}));+const { getVerifiedInstallationOctokit } = await import(+ "../../../apps/api/src/plugins/github/utils/github-app"+);+const binding = {+ repositoryOwner: "owner",+ repositoryName: "repo",+ installationId: 10,+ repositoryId: 20,+ verifiedGithubAccountId: "30",+ verifiedByUserId: "user",+};+beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv("GITHUB_APP_ID", "1");+ vi.stubEnv("GITHUB_PRIVATE_KEY", "unit-test-key");+ vi.stubEnv("GITHUB_WEBHOOK_SECRET", "unit-test-secret");+ m.client.mockResolvedValue({ rest: { repos: { get: m.repo } } });+});+afterEach(() => vi.unstubAllEnvs());+describe("GitHub outgoing repository binding", () => {+ it("permits only the verified numeric repository", async () => {+ m.repo.mockResolvedValue({ data: { id: 20 } });+ await expect(+ getVerifiedInstallationOctokit(binding),+ ).resolves.toHaveProperty("rest");+ expect(m.client).toHaveBeenCalledWith(10);+ });+ it("rejects a name reused for a different repository", async () => {+ m.repo.mockResolvedValue({ data: { id: 21 } });+ await expect(getVerifiedInstallationOctokit(binding)).rejects.toThrow(+ "identity changed",+ );+ });+ it("rejects a legacy binding without contacting GitHub", async () => {+ await expect(+ getVerifiedInstallationOctokit({+ repositoryOwner: "owner",+ repositoryName: "repo",+ installationId: 10,+ }),+ ).rejects.toThrow("requires verification");+ expect(m.client).not.toHaveBeenCalled();+ });+ it("fails closed when the verified installation loses repository access", async () => {+ m.repo.mockRejectedValue(+ Object.assign(new Error("not found"), { status: 404 }),+ );+ await expect(getVerifiedInstallationOctokit(binding)).rejects.toMatchObject(+ { status: 404 },+ );+ });+});diff --git a/tests/api/github-integration/repository-binding.test.ts b/tests/api/github-integration/repository-binding.test.tsnew file mode 100644index 000000000..f37c76974--- /dev/null+++ b/tests/api/github-integration/repository-binding.test.ts@@ -0,0 +1,269 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const m = vi.hoisted(() => ({+ account: vi.fn(),+ integrations: vi.fn(),+ installation: vi.fn(),+ user: vi.fn(),+ permission: vi.fn(),+ repo: vi.fn(),+ insert: vi.fn(),+ listInstallations: vi.fn(),+ listRepos: vi.fn(),+}));+vi.mock("../../../apps/api/src/database", () => ({+ default: {+ query: {+ accountTable: { findFirst: m.account },+ projectTable: { findFirst: async () => ({ id: "project" }) },+ integrationTable: {+ findFirst: async () => null,+ findMany: m.integrations,+ },+ },+ insert: () => ({+ values: (data: unknown) => {+ m.insert(data);+ return {+ returning: async () => [{ id: "integration", projectId: "project" }],+ };+ },+ }),+ },+}));+vi.mock("../../../apps/api/src/plugins/github/utils/github-app", () => ({+ getGithubApp: () => ({+ octokit: {+ rest: {+ apps: {+ getRepoInstallation: m.installation,+ listInstallations: m.listInstallations,+ },+ },+ },+ getInstallationOctokit: async () => ({+ rest: {+ apps: { listReposAccessibleToInstallation: m.listRepos },+ users: { getById: m.user },+ repos: { getCollaboratorPermissionLevel: m.permission, get: m.repo },+ },+ }),+ }),+}));+const { verifyRepositoryOwner } = await import(+ "../../../apps/api/src/github-integration/controllers/verify-repository-owner"+);+const { default: createIntegration } = await import(+ "../../../apps/api/src/github-integration/controllers/create-github-integration"+);+const { findAllIntegrationsByRepo } = await import(+ "../../../apps/api/src/plugins/github/services/task-service"+);+const binding = {+ repositoryOwner: "Victim",+ repositoryName: "Private",+ installationId: 10,+ repositoryId: 20,+ verifiedGithubAccountId: "30",+ verifiedByUserId: "user",+};++beforeEach(() => {+ vi.clearAllMocks();+ m.account.mockResolvedValue({ accountId: "30" });+ m.installation.mockResolvedValue({ data: { id: 10 } });+ m.user.mockResolvedValue({ data: { id: 30, login: "verified-login" } });+ m.permission.mockResolvedValue({ data: { permission: "admin" } });+ m.repo.mockResolvedValue({+ data: { id: 20, owner: { login: "Victim" }, name: "Private" },+ });+});++describe("GitHub repository linking", () => {+ it("binds the repository to the completed OAuth identity and canonical IDs", async () => {+ expect(await verifyRepositoryOwner("user", "victim", "private")).toEqual(+ binding,+ );+ expect(m.permission).toHaveBeenCalledWith({+ owner: "victim",+ repo: "private",+ username: "verified-login",+ });+ });+ it.each(["read", "write", "maintain", "none"])(+ "rejects %s permission without creating a shadow integration",+ async (permission) => {+ m.permission.mockResolvedValue({ data: { permission } });+ await expect(+ createIntegration({+ userId: "user",+ projectId: "project",+ repositoryOwner: "victim",+ repositoryName: "private",+ }),+ ).rejects.toMatchObject({ status: 403 });+ expect(m.insert).not.toHaveBeenCalled();+ },+ );+ it("rejects missing linked identity before looking up a repository", async () => {+ m.account.mockResolvedValue(null);+ await expect(+ verifyRepositoryOwner("user", "victim", "private"),+ ).rejects.toMatchObject({ status: 403 });+ expect(m.installation).not.toHaveBeenCalled();+ });+ it("does not save a null installation after provider failure", async () => {+ m.installation.mockRejectedValueOnce(new Error("private provider error"));+ await expect(+ createIntegration({+ userId: "user",+ projectId: "project",+ repositoryOwner: "victim",+ repositoryName: "private",+ }),+ ).rejects.toMatchObject({ status: 403 });+ expect(m.insert).not.toHaveBeenCalled();+ });+ it("does not consult another tenant's integrations when linking", async () => {+ await createIntegration({+ userId: "user",+ projectId: "project",+ repositoryOwner: "victim",+ repositoryName: "private",+ });+ expect(m.integrations).not.toHaveBeenCalled();+ expect(JSON.parse(m.insert.mock.calls[0][0].config)).toMatchObject(binding);+ });+ it("rejects an unexpected identity response", async () => {+ m.user.mockResolvedValueOnce({ data: { id: 31, login: "somebody-else" } });+ await expect(+ verifyRepositoryOwner("user", "victim", "private"),+ ).rejects.toMatchObject({ status: 403 });+ expect(m.permission).not.toHaveBeenCalled();+ });+});++describe("GitHub webhook binding", () => {+ const source = { repository: { id: 20 }, installation: { id: 10 } };+ it("delivers only to verified bindings for both immutable identifiers", async () => {+ const entries = [+ { id: "legitimate", config: JSON.stringify(binding) },+ {+ id: "different-installation",+ config: JSON.stringify({ ...binding, installationId: 11 }),+ },+ {+ id: "same-name-different-repo",+ config: JSON.stringify({ ...binding, repositoryId: 21 }),+ },+ {+ id: "legacy-name-only",+ config: JSON.stringify({+ repositoryOwner: "Victim",+ repositoryName: "Private",+ installationId: 10,+ }),+ },+ {+ id: "unverified-ids",+ config: JSON.stringify({+ repositoryOwner: "Victim",+ repositoryName: "Private",+ installationId: 10,+ repositoryId: 20,+ }),+ },+ { id: "malformed", config: "invalid" },+ ];+ m.integrations.mockResolvedValue(entries);+ expect(await findAllIntegrationsByRepo(source)).toEqual([entries[0]]);+ });+ it("ignores events without an installation before querying tenant data", async () => {+ expect(await findAllIntegrationsByRepo({ repository: { id: 20 } })).toEqual(+ [],+ );+ expect(m.integrations).not.toHaveBeenCalled();+ });+});++const { default: listUserRepositories } = await import(+ "../../../apps/api/src/github-integration/controllers/list-user-repositories"+);+describe("authorized bounded repository listing", () => {+ const candidate = (id: number) => ({+ id,+ name: `repo-${id}`,+ full_name: `owner/repo-${id}`,+ private: true,+ owner: { login: "owner", avatar_url: "", type: "User" },+ description: "private description",+ html_url: `https://github.com/owner/repo-${id}`,+ updated_at: "2026-01-01",+ });+ beforeEach(() => {+ m.listInstallations.mockResolvedValue({+ data: [{ id: 10, account: { login: "owner" } }],+ });+ m.listRepos.mockResolvedValue({+ data: { repositories: [candidate(20), candidate(21)] },+ });+ });+ it("returns only repositories the caller administers", async () => {+ m.permission.mockImplementation(async ({ repo }) => ({+ data: { permission: repo === "repo-20" ? "admin" : "read" },+ }));+ const page = await listUserRepositories("user", {+ installationPage: 1,+ repositoryPage: 1,+ });+ expect(page.repositories.map((repo) => repo.id)).toEqual([20]);+ expect(JSON.stringify(page)).not.toContain("repo-21");+ expect(m.listInstallations).toHaveBeenCalledWith(+ expect.objectContaining({ per_page: 1, page: 1 }),+ );+ expect(m.listRepos).toHaveBeenCalledWith(+ expect.objectContaining({ per_page: 20, page: 1 }),+ );+ });+ it("does not expose an unauthorized installation's metadata", async () => {+ m.permission.mockResolvedValue({ data: { permission: "read" } });+ const page = await listUserRepositories("user", {+ installationPage: 1,+ repositoryPage: 1,+ });+ expect(page.repositories).toEqual([]);+ expect(page.installations).toEqual([]);+ expect(JSON.stringify(page)).not.toContain("owner");+ });+ it("does not traverse additional pages in the same request", async () => {+ m.listRepos.mockResolvedValue({+ data: {+ repositories: Array.from({ length: 20 }, (_, i) => candidate(i + 1)),+ },+ });+ const page = await listUserRepositories("user", {+ installationPage: 2,+ repositoryPage: 3,+ });+ expect(m.listInstallations).toHaveBeenCalledTimes(1);+ expect(m.listRepos).toHaveBeenCalledTimes(1);+ expect(m.permission).toHaveBeenCalledTimes(20);+ expect(page.nextPage).toEqual({ installationPage: 2, repositoryPage: 4 });+ });+ it("stops when all installations have been visited", async () => {+ m.listInstallations.mockResolvedValue({ data: [] });+ const page = await listUserRepositories("user", {+ installationPage: 3,+ repositoryPage: 1,+ });+ expect(page.nextPage).toBeNull();+ expect(m.listRepos).not.toHaveBeenCalled();+ });+ it("rejects unlinked callers before any provider enumeration", async () => {+ m.account.mockResolvedValue(null);+ await expect(+ listUserRepositories("user", { installationPage: 1, repositoryPage: 1 }),+ ).rejects.toMatchObject({ status: 403 });+ expect(m.listInstallations).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/label/assign-and-unassign-label.test.ts b/tests/api/label/assign-and-unassign-label.test.tsindex 4d243692d..c5fde47b9 100644--- a/tests/api/label/assign-and-unassign-label.test.ts+++ b/tests/api/label/assign-and-unassign-label.test.ts@@ -296,13 +296,19 @@ describe("assignLabelToTask", () => {const insertChain = makeInsertMock(undefined);mockInsert.mockReturnValue(insertChain);mockFindFirst.mockResolvedValueOnce(WORKSPACE_LABEL);- mockFindFirst.mockResolvedValueOnce(WORKSPACE_LABEL);+ mockFindFirst.mockResolvedValueOnce(TASK_LABEL);- await assignLabelToTask("label-ws-1", "task-1", "user-1");+ const result = await assignLabelToTask("label-ws-1", "task-1", "user-1");+ expect(result).toEqual(TASK_LABEL);+ expect(result.taskId).toBe("task-1");expect(mockTransaction).toHaveBeenCalledTimes(1);expect(mockInsert).toHaveBeenCalledTimes(1);expect(mockFindFirst).toHaveBeenCalledTimes(3);+ expect(mockDelete).not.toHaveBeenCalled();+ expect(mockSyncLabelToGitHub).not.toHaveBeenCalled();+ expect(mockSyncLabelToGitea).not.toHaveBeenCalled();+ expect(mockPublishEvent).not.toHaveBeenCalled();});it("throws HTTP 500 when the insert and fallback lookup both return no row", async () => {diff --git a/tests/api/label/delete-label.test.ts b/tests/api/label/delete-label.test.tsdeleted file mode 100644index 11c944b9e..000000000--- a/tests/api/label/delete-label.test.ts+++ /dev/null@@ -1,218 +0,0 @@-import {- afterEach,- beforeEach,- describe,- expect,- it,- type Mock,- vi,-} from "vitest";--const mockFindFirst = vi.fn();-const mockSelect = vi.fn();-const mockDelete = vi.fn();-const mockPublishEvent = vi.fn();-const mockRemoveLabelFromGitHub = vi.fn();-const mockRemoveLabelFromGitea = vi.fn();--vi.mock("../../../apps/api/src/database", () => ({- default: {- query: {- labelTable: {- findFirst: (...args: unknown[]) => mockFindFirst(...args),- },- },- select: (...args: unknown[]) => mockSelect(...args),- delete: (...args: unknown[]) => mockDelete(...args),- },-}));--vi.mock("../../../apps/api/src/events", () => ({- publishEvent: (...args: unknown[]) => mockPublishEvent(...args),-}));--vi.mock(- "../../../apps/api/src/plugins/github/utils/sync-label-to-github",- () => ({- removeLabelFromGitHub: (...args: unknown[]) =>- mockRemoveLabelFromGitHub(...args),- }),-);--vi.mock(- "../../../apps/api/src/plugins/gitea/utils/sync-label-to-gitea",- () => ({- removeLabelFromGitea: (...args: unknown[]) =>- mockRemoveLabelFromGitea(...args),- }),-);--import deleteLabel from "../../../apps/api/src/label/controllers/delete-label";--const WORKSPACE_LABEL = {- id: "label-ws-1",- name: "bug",- color: "EF4444",- createdAt: new Date(),- updatedAt: new Date(),- taskId: null,- workspaceId: "ws-1",-};--const DELETED_WORKSPACE_LABEL = { ...WORKSPACE_LABEL };--const TASK_LABEL_1 = {- id: "label-task-1",- name: "bug",- color: "EF4444",- createdAt: new Date(),- updatedAt: new Date(),- taskId: "task-1",- workspaceId: "ws-1",-};--const TASK_LABEL_2 = {- id: "label-task-2",- name: "bug",- color: "EF4444",- createdAt: new Date(),- updatedAt: new Date(),- taskId: "task-2",- workspaceId: "ws-1",-};--/**- * Build a mock chain for `db.select().from().innerJoin().innerJoin().where()`.- * The terminal `.where()` returns a Promise resolved to `rows`.- */-function makeSelectMock(rows: unknown[]) {- const chain: Record<string, Mock> = {- from: vi.fn(() => chain),- innerJoin: vi.fn(() => chain),- where: vi.fn(() => Promise.resolve(rows)),- };- return chain;-}--/**- * Build a mock chain for `db.delete().where().returning()` and- * `db.delete().where()` (no returning).- *- * - `.where()` returns a sub-chain that supports `.returning()` and is thenable.- */-function makeDeleteMock(deletedRow: unknown) {- const chain: Record<string, Mock> = {};-- // Sub-chain returned by .where():- // - Native Promise.then so `await db.delete().where(...)` works- // - .returning() attached for the returning-delete path- const whereResult = Object.assign(Promise.resolve(undefined), {- returning: vi.fn(() => Promise.resolve([deletedRow])),- });-- chain.where = vi.fn(() => whereResult);-- return chain;-}--describe("deleteLabel", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- afterEach(() => {- vi.restoreAllMocks();- });-- describe("workspace-level label deletion (taskId is null)", () => {- it("emits task.label_deleted events for each affected task-level label", async () => {- mockRemoveLabelFromGitHub.mockResolvedValue(undefined);- mockRemoveLabelFromGitea.mockResolvedValue(undefined);- mockFindFirst.mockResolvedValue(WORKSPACE_LABEL);- mockSelect.mockReturnValue(- makeSelectMock([- {- label: TASK_LABEL_1,- taskId: "task-1",- projectId: "proj-1",- workspaceId: "ws-1",- },- {- label: TASK_LABEL_2,- taskId: "task-2",- projectId: "proj-2",- workspaceId: "ws-1",- },- ]),- );- mockDelete.mockReturnValue(makeDeleteMock(DELETED_WORKSPACE_LABEL));-- await deleteLabel("label-ws-1", "user-1");-- expect(mockPublishEvent).toHaveBeenCalledTimes(2);- expect(mockPublishEvent).toHaveBeenCalledWith("task.label_deleted", {- label: TASK_LABEL_1,- task: { id: "task-1", projectId: "proj-1" },- projectId: "proj-1",- taskId: "task-1",- userId: "user-1",- type: "label_deleted",- });- expect(mockPublishEvent).toHaveBeenCalledWith("task.label_deleted", {- label: TASK_LABEL_2,- task: { id: "task-2", projectId: "proj-2" },- projectId: "proj-2",- taskId: "task-2",- userId: "user-1",- type: "label_deleted",- });- });-- it("calls removeLabelFromGitHub and removeLabelFromGitea for each affected task", async () => {- mockRemoveLabelFromGitHub.mockResolvedValue(undefined);- mockRemoveLabelFromGitea.mockResolvedValue(undefined);- mockFindFirst.mockResolvedValue(WORKSPACE_LABEL);- mockSelect.mockReturnValue(- makeSelectMock([- {- label: TASK_LABEL_1,- taskId: "task-1",- projectId: "proj-1",- workspaceId: "ws-1",- },- {- label: TASK_LABEL_2,- taskId: "task-2",- projectId: "proj-2",- workspaceId: "ws-1",- },- ]),- );- mockDelete.mockReturnValue(makeDeleteMock(DELETED_WORKSPACE_LABEL));-- await deleteLabel("label-ws-1", "user-1");-- expect(mockRemoveLabelFromGitHub).toHaveBeenCalledTimes(2);- expect(mockRemoveLabelFromGitHub).toHaveBeenCalledWith("task-1", "bug");- expect(mockRemoveLabelFromGitHub).toHaveBeenCalledWith("task-2", "bug");-- expect(mockRemoveLabelFromGitea).toHaveBeenCalledTimes(2);- expect(mockRemoveLabelFromGitea).toHaveBeenCalledWith("task-1", "bug");- expect(mockRemoveLabelFromGitea).toHaveBeenCalledWith("task-2", "bug");- });-- it("fires no events when no task-level labels are affected", async () => {- mockRemoveLabelFromGitHub.mockResolvedValue(undefined);- mockRemoveLabelFromGitea.mockResolvedValue(undefined);- mockFindFirst.mockResolvedValue(WORKSPACE_LABEL);- mockSelect.mockReturnValue(makeSelectMock([]));- mockDelete.mockReturnValue(makeDeleteMock(DELETED_WORKSPACE_LABEL));-- await deleteLabel("label-ws-1", "user-1");-- expect(mockPublishEvent).not.toHaveBeenCalled();- expect(mockRemoveLabelFromGitHub).not.toHaveBeenCalled();- expect(mockRemoveLabelFromGitea).not.toHaveBeenCalled();- });- });-});diff --git a/tests/api/mcp-oauth-security.test.ts b/tests/api/mcp-oauth-security.test.tsindex 5b53419d4..67d64435e 100644--- a/tests/api/mcp-oauth-security.test.ts+++ b/tests/api/mcp-oauth-security.test.ts@@ -1,4 +1,5 @@import { createHash } from "node:crypto";+import { HTTPException } from "hono/http-exception";import { describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => {@@ -43,7 +44,12 @@ vi.mock("../../apps/api/src/mcp/oauth-store", () => {key: string,payload: unknown,expiresAt: Date,+ requestId?: string,) => {+ if (requestId) {+ if (!rows.delete(keyOf("request", requestId)))+ throw new HTTPException(404);+ }rows.set(keyOf(kind, key), { payload, expiresAt });},getState: async (kind: string, key: string) => {@@ -59,7 +65,6 @@ vi.mock("../../apps/api/src/mcp/oauth-store", () => {if (row.expiresAt.getTime() < Date.now()) return null;return row.payload;},- enforceStateCap: async () => {},deleteExpiredStates: async () => {const now = Date.now();for (const [key, row] of rows) {diff --git a/tests/api/mcp-request-bounds.test.ts b/tests/api/mcp-request-bounds.test.tsnew file mode 100644index 000000000..7a620033e--- /dev/null+++ b/tests/api/mcp-request-bounds.test.ts@@ -0,0 +1,87 @@+import { Hono } from "hono";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ OAUTH_BODY_BYTES,+ OAUTH_MAX_IN_FLIGHT,+ oauthRequestBounds,+} from "../../apps/api/src/mcp/request-bounds";++const parse = vi.fn(async (text: string) => text);+const app = new Hono().post("/register", oauthRequestBounds, async (c) =>+ c.text(await parse(await c.req.text())),+);+afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe("OAuth bounded body reader", () => {+ it("cancels an over-limit chunked stream without invoking the parser", async () => {+ const cancel = vi.fn();+ const body = new ReadableStream({+ pull(controller) {+ controller.enqueue(new Uint8Array(16 * 1024));+ },+ cancel,+ });+ const response = await app.request(+ new Request("http://localhost/register", {+ method: "POST",+ body,+ duplex: "half",+ } as RequestInit),+ );+ expect(response.status).toBe(413);+ expect(cancel).toHaveBeenCalledOnce();+ expect(parse).not.toHaveBeenCalled();+ });+ it("accepts a body exactly at the byte limit", async () => {+ const body = "x".repeat(OAUTH_BODY_BYTES);+ const response = await app.request("/register", { method: "POST", body });+ expect(response.status).toBe(200);+ expect(await response.text()).toBe(body);+ });+ it("bounds simultaneous slow requests and releases capacity after their deadlines", async () => {+ vi.useFakeTimers();+ const pending = Array.from({ length: OAUTH_MAX_IN_FLIGHT }, () =>+ app.request(+ new Request("http://localhost/register", {+ method: "POST",+ body: new ReadableStream(),+ duplex: "half",+ } as RequestInit),+ ),+ );+ const denied = await app.request("/register", {+ method: "POST",+ body: "small",+ });+ expect(denied.status).toBe(429);+ expect(denied.headers.get("retry-after")).toBe("1");+ await vi.advanceTimersByTimeAsync(5_001);+ expect(+ (await Promise.all(pending)).every((response) => response.status === 408),+ ).toBe(true);+ expect(+ (await app.request("/register", { method: "POST", body: "small" }))+ .status,+ ).toBe(200);+ });++ it("uses a deadline for a stream that never finishes", async () => {+ vi.useFakeTimers();+ const cancel = vi.fn();+ const body = new ReadableStream({ start() {}, cancel });+ const pending = app.request(+ new Request("http://localhost/register", {+ method: "POST",+ body,+ duplex: "half",+ } as RequestInit),+ );+ await vi.advanceTimersByTimeAsync(5_001);+ expect((await pending).status).toBe(408);+ expect(cancel).toHaveBeenCalledOnce();+ expect(parse).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/plugins/generic-webhook/events.test.ts b/tests/api/plugins/generic-webhook/events.test.tsindex 7f195d879..2dc8d094d 100644--- a/tests/api/plugins/generic-webhook/events.test.ts+++ b/tests/api/plugins/generic-webhook/events.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { postToGenericWebhook } from "../../../../apps/api/src/plugins/generic-webhook/client";import {handleTaskDeleted,@@ -59,6 +59,7 @@ const deletedEvent = {};describe("generic webhook event handlers", () => {+ afterEach(() => vi.restoreAllMocks());beforeEach(() => {vi.mocked(postToGenericWebhook).mockClear();selectMock.mockReset();@@ -112,6 +113,30 @@ describe("generic webhook event handlers", () => {});});+ it("does not log a credential-bearing URL or unknown transport error", async () => {+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ const secretUrl =+ "https://example.com/hooks/private-token?key=secret-value";+ selectMock+ .mockImplementationOnce(() =>+ selectChain([+ { id: "project-1", name: "Roadmap", workspaceId: "workspace-1" },+ ]),+ )+ .mockImplementationOnce(() =>+ selectChain([{ id: "user-1", name: "User" }]),+ );+ vi.mocked(postToGenericWebhook).mockRejectedValueOnce(new Error(secretUrl));+ await handleTaskDeleted(deletedEvent, {+ ...enabledContext,+ config: { ...enabledContext.config, webhookUrl: secretUrl },+ });+ expect(log).toHaveBeenCalled();+ expect(JSON.stringify(log.mock.calls)).not.toContain("private-token");+ expect(JSON.stringify(log.mock.calls)).not.toContain("secret-value");+ expect(JSON.stringify(log.mock.calls)).toContain("Outbound request failed");+ });+it("skips task.deleted when the project row no longer exists", async () => {selectMock.mockImplementationOnce(() => selectChain([]));diff --git a/tests/api/plugins/github/issue-reopened.test.ts b/tests/api/plugins/github/issue-reopened.test.tsnew file mode 100644index 000000000..b90096554--- /dev/null+++ b/tests/api/plugins/github/issue-reopened.test.ts@@ -0,0 +1,85 @@+import { beforeEach, expect, it, vi } from "vitest";+import { handleIssueReopened } from "../../../../apps/api/src/plugins/github/webhooks/issue-reopened";++const m = vi.hoisted(() => ({+ links: vi.fn(),+ tasks: vi.fn(),+ find: vi.fn(),+ update: vi.fn(),+ status: vi.fn(),+ publish: vi.fn(),+}));+vi.mock("../../../../apps/api/src/database", () => ({+ default: {+ query: {+ externalLinkTable: { findFirst: m.links },+ taskTable: { findFirst: m.tasks },+ },+ },+}));+vi.mock("../../../../apps/api/src/events", () => ({ publishEvent: m.publish }));+vi.mock(+ "../../../../apps/api/src/plugins/github/services/task-service",+ () => ({ findAllIntegrationsByRepo: m.find, updateTaskStatus: m.status }),+);+vi.mock(+ "../../../../apps/api/src/plugins/github/services/link-manager",+ () => ({ updateExternalLink: m.update }),+);+vi.mock("../../../../apps/api/src/plugins/github/utils/resolve-column", () => ({+ resolveTargetStatus: async () => "to-do",+}));+const payload = {+ action: "reopened",+ installation: { id: 10 },+ repository: {+ id: 20,+ owner: { login: "example" },+ name: "repo",+ full_name: "example/repo",+ },+ issue: {+ number: 1,+ title: "Issue",+ html_url: "https://github.com/example/repo/issues/1",+ state: "open",+ },+};+beforeEach(() => {+ vi.resetAllMocks();+ m.find.mockResolvedValue([{ id: "integration-1" }, { id: "integration-2" }]);+ m.tasks.mockResolvedValue({ id: "task", projectId: "project" });+ m.status.mockResolvedValue({ applied: false });+});+it.each(["null", "[]", "42", '"text"', "invalid JSON"])(+ "continues through all linked rows when metadata is %s",+ async (metadata) => {+ m.links+ .mockResolvedValueOnce({ id: "first", taskId: "task", metadata })+ .mockResolvedValueOnce({+ id: "second",+ taskId: "task",+ metadata: '{"custom":"keep"}',+ });+ await handleIssueReopened(payload);+ expect(m.find).toHaveBeenCalledWith(payload);+ expect(m.update).toHaveBeenCalledWith("first", {+ metadata: { state: "open" },+ });+ expect(m.update).toHaveBeenCalledWith("second", {+ metadata: { custom: "keep", state: "open" },+ });+ expect(m.status).toHaveBeenCalledTimes(2);+ },+);+it("retains the Kaneo-origin skip rule for valid metadata", async () => {+ m.find.mockResolvedValue([{ id: "integration-1" }]);+ m.links.mockResolvedValue({+ id: "first",+ taskId: "task",+ metadata: '{"createdFrom":"kaneo"}',+ });+ await handleIssueReopened(payload);+ expect(m.update).not.toHaveBeenCalled();+ expect(m.status).not.toHaveBeenCalled();+});diff --git a/tests/api/plugins/github/utils/format.test.ts b/tests/api/plugins/github/utils/format.test.tsindex 5970ea345..39c8eb68f 100644--- a/tests/api/plugins/github/utils/format.test.ts+++ b/tests/api/plugins/github/utils/format.test.ts@@ -26,6 +26,31 @@ describe("github format helpers", () => {expect(formatTaskDescriptionFromIssue(null)).toBe("");});+ it.each([+ "",+ "A description",+ " whitespace around text ",+ "Details\n\n---\nA manual separator",+ ])(+ "round trips generated footers without changing description content: %s",+ (description) => {+ expect(+ formatTaskDescriptionFromIssue(+ formatIssueBody(description, "task_123"),+ "task_123",+ ),+ ).toBe(description);+ },+ );++ it("preserves arbitrary imports and Task mentions inside a description", () => {+ const body = "Text\n\n---\n<sub>Task: task_123</sub>\nMore text";+ expect(formatTaskDescriptionFromIssue(body, "task_123")).toBe(body);+ expect(+ formatTaskDescriptionFromIssue(formatIssueBody("Imported", "task_123")),+ ).toBe(formatIssueBody("Imported", "task_123"));+ });+it("builds labels while skipping no-priority", () => {expect(getLabelsForIssue("high", "in-review")).toEqual(["priority:high",diff --git a/tests/api/plugins/github/webhooks/issue-opened.test.ts b/tests/api/plugins/github/webhooks/issue-opened.test.tsindex 9b257ee7c..47ed481d2 100644--- a/tests/api/plugins/github/webhooks/issue-opened.test.ts+++ b/tests/api/plugins/github/webhooks/issue-opened.test.ts@@ -13,10 +13,15 @@ const mocks = vi.hoisted(() => {const mockGetInstallationOctokit = vi.fn();const mockColumnFindFirst = vi.fn();const mockProjectFindFirst = vi.fn();+ const mockLockedIntegration = vi.fn();const insertedValues: Array<Record<string, unknown>> = [];const mockDb = {+ transaction: async (run: (tx: unknown) => Promise<unknown>) => run(mockDb),+ select: () => ({+ from: () => ({ where: () => ({ for: mockLockedIntegration }) }),+ }),insert: () => ({values: (values: Record<string, unknown>) => {insertedValues.push(values);@@ -56,6 +61,7 @@ const mocks = vi.hoisted(() => {mockColumnFindFirst,mockProjectFindFirst,mockDb,+ mockLockedIntegration,insertedValues,mockOctokit,mockGithubApp,@@ -153,6 +159,7 @@ beforeEach(() => {mocks.mockGetGithubApp.mockReturnValue(mocks.mockGithubApp);mocks.mockFindAllIntegrationsByRepo.mockResolvedValue([integration]);mocks.mockFindExternalLink.mockResolvedValue(null);+ mocks.mockLockedIntegration.mockResolvedValue([integration]);mocks.mockClaimTaskNumber.mockResolvedValue(7);mocks.mockResolveTargetStatus.mockResolvedValue("to-do");mocks.mockColumnFindFirst.mockResolvedValue(null);diff --git a/tests/api/plugins/telegram-logging.test.ts b/tests/api/plugins/telegram-logging.test.tsnew file mode 100644index 000000000..4566e5846--- /dev/null+++ b/tests/api/plugins/telegram-logging.test.ts@@ -0,0 +1,82 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { handleTaskCreated } from "../../../apps/api/src/plugins/telegram/events";++const m = vi.hoisted(() => ({ select: vi.fn(), send: vi.fn() }));+vi.mock("../../../apps/api/src/database", () => ({+ default: { select: m.select },+}));+vi.mock("../../../apps/api/src/plugins/telegram/client", () => ({+ postToTelegram: m.send,+}));+afterEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++const event = {+ taskId: "task",+ projectId: "project",+ userId: "user",+ title: "Task",+ description: null,+ priority: null,+ status: "to-do",+ number: 1,+};+const token = `12345678:${"x".repeat(35)}`;+describe("Telegram logging", () => {+ it("does not log secret-bearing invalid configuration", async () => {+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ await handleTaskCreated(event, {+ integrationId: "integration",+ projectId: "project",+ config: { botToken: token, chatId: "" },+ });+ expect(log).toHaveBeenCalled();+ expect(JSON.stringify(log.mock.calls)).not.toContain(token);+ expect(JSON.stringify(log.mock.calls)).not.toContain("botToken");+ expect(m.select).not.toHaveBeenCalled();+ expect(m.send).not.toHaveBeenCalled();+ });+ it("discards unknown errors with token-bearing causes", async () => {+ const log = vi.spyOn(console, "error").mockImplementation(() => {});+ function chain(rows: unknown[]) {+ const value = {+ from: () => value,+ innerJoin: () => value,+ where: () => value,+ limit: async () => rows,+ };+ return value;+ }+ m.select+ .mockReturnValueOnce(+ chain([+ {+ title: "Task",+ number: 1,+ status: "to-do",+ priority: "low",+ projectName: "Project",+ workspaceId: "workspace",+ projectId: "project",+ },+ ]),+ )+ .mockReturnValueOnce(chain([{ name: "User" }]));+ m.send.mockRejectedValue(+ new Error(`Failed https://api.telegram.org/bot${token}`, {+ cause: { token },+ }),+ );+ await handleTaskCreated(event, {+ integrationId: "integration",+ projectId: "project",+ config: { botToken: token, chatId: "chat" },+ });+ expect(m.send).toHaveBeenCalled();+ expect(log).toHaveBeenCalled();+ expect(JSON.stringify(log.mock.calls)).not.toContain(token);+ expect(JSON.stringify(log.mock.calls)).toContain("Outbound request failed");+ });+});diff --git a/tests/api/storage/s3.test.ts b/tests/api/storage/s3.test.tsindex adb95b6ea..bdc3a1f26 100644--- a/tests/api/storage/s3.test.ts+++ b/tests/api/storage/s3.test.ts@@ -218,7 +218,7 @@ describe("S3 helpers", () => {"A valid content type is required.",);expect(() => validateTaskAssetUploadInput("image/png", 0)).toThrow(- "Upload size must be greater than zero.",+ "Upload size must be a positive safe integer.",);expect(() =>validateTaskAssetUploadInput("image/png", 2 * 1024 * 1024),@@ -226,6 +226,19 @@ describe("S3 helpers", () => {expect(() => validateTaskAssetUploadInput("image/png", 512)).not.toThrow();});+ it.each([+ Number.NaN,+ Number.POSITIVE_INFINITY,+ Number.NEGATIVE_INFINITY,+ -1,+ 0.5,+ Number.MAX_SAFE_INTEGER + 1,+ ])("rejects invalid byte length %s before signing", (size) => {+ expect(() => validateTaskAssetUploadInput("image/png", size)).toThrow(+ "Upload size must be a positive safe integer.",+ );+ });+it("creates presigned upload URLs without hoisted checksum query params", async () => {process.env.S3_ENDPOINT = "https://storage.example.test";process.env.S3_BUCKET = "kaneo";@@ -242,9 +255,14 @@ describe("S3 helpers", () => {surface: "description",filename: "report.png",contentType: "image/png",+ size: 512,});const searchParams = new URL(upload.uploadUrl).searchParams;+ expect(searchParams.get("X-Amz-SignedHeaders")?.split(";")).toEqual(+ expect.arrayContaining(["content-length", "content-type", "host"]),+ );+ expect(upload.headers).not.toHaveProperty("Content-Length");expect(searchParams.has("x-amz-checksum-crc32")).toBe(false);expect(searchParams.has("x-amz-sdk-checksum-algorithm")).toBe(false);});@@ -359,6 +377,7 @@ describe("S3 credential provider chain (IAM role)", () => {surface: "description",filename: "report.png",contentType: "image/png",+ size: 512,});const searchParams = new URL(upload.uploadUrl).searchParams;diff --git a/tests/api/user/avatar.test.ts b/tests/api/user/avatar.test.tsindex 277b7cda5..dad9f1495 100644--- a/tests/api/user/avatar.test.ts+++ b/tests/api/user/avatar.test.ts@@ -1,8 +1,9 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import {buildAvatarUrl,decodeAvatarUpload,MAX_AVATAR_BYTES,+ MAX_AVATAR_INPUT_CHARS,normalizeAvatarMimeType,} from "../../../apps/api/src/user/avatar";@@ -104,6 +105,44 @@ describe("decodeAvatarUpload", () => {).toThrow(/maximum avatar size/);});+ it("accepts an avatar at the exact decoded byte limit", () => {+ expect(+ decodeAvatarUpload({+ contentType: "image/png",+ data: pngOfSize(MAX_AVATAR_BYTES),+ }).bytes.length,+ ).toBe(MAX_AVATAR_BYTES);+ });++ it.each([" ", "A"])(+ "rejects oversized raw %s data before cleanup or decoding",+ (character) => {+ const data = character.repeat(MAX_AVATAR_INPUT_CHARS + 1);+ const from = vi.spyOn(Buffer, "from");+ try {+ expect(() =>+ decodeAvatarUpload({ contentType: "image/png", data }),+ ).toThrow(/maximum avatar size/);+ expect(from).not.toHaveBeenCalled();+ } finally {+ from.mockRestore();+ }+ },+ );++ it("rejects a decoded-size overflow before allocating its Buffer", () => {+ const data = pngOfSize(MAX_AVATAR_BYTES + 1);+ const from = vi.spyOn(Buffer, "from");+ try {+ expect(() =>+ decodeAvatarUpload({ contentType: "image/png", data }),+ ).toThrow(/maximum avatar size/);+ expect(from).not.toHaveBeenCalled();+ } finally {+ from.mockRestore();+ }+ });+it("rejects bytes that do not match the declared type", () => {expect(() =>decodeAvatarUpload({diff --git a/tests/api/utils/authorize-asset-access.test.ts b/tests/api/utils/authorize-asset-access.test.tsindex 45b8010d6..75cfb7e7d 100644--- a/tests/api/utils/authorize-asset-access.test.ts+++ b/tests/api/utils/authorize-asset-access.test.ts@@ -33,7 +33,7 @@ vi.mock("../../../apps/api/src/utils/validate-workspace-access", () => ({},}));-const { authorizeAssetAccess } = await import(+const { authorizeAssetAccess, isPublicAsset } = await import("../../../apps/api/src/utils/authorize-asset-access");@@ -59,6 +59,7 @@ describe("authorizeAssetAccess", () => {const status = await statusOf(authorizeAssetAccess(context, {workspaceId: "workspace-1",+ surface: "description",isPublic: true,}),);@@ -73,6 +74,7 @@ describe("authorizeAssetAccess", () => {const status = await statusOf(authorizeAssetAccess(context, {workspaceId: "workspace-1",+ surface: "description",isPublic: false,}),);@@ -86,6 +88,7 @@ describe("authorizeAssetAccess", () => {const status = await statusOf(authorizeAssetAccess(context, {workspaceId: "workspace-1",+ surface: "description",isPublic: null,}),);@@ -99,6 +102,7 @@ describe("authorizeAssetAccess", () => {const status = await statusOf(authorizeAssetAccess(context, {workspaceId: "workspace-1",+ surface: "description",isPublic: false,}),);@@ -108,4 +112,16 @@ describe("authorizeAssetAccess", () => {{ userId: "user-member", workspaceId: "workspace-1" },]);});+ it.each(["comment", "unknown"])(+ "keeps %s assets private even in a public project",+ async (surface) => {+ const asset = { workspaceId: "workspace-1", isPublic: true, surface };+ expect(isPublicAsset(asset)).toBe(false);+ expect(await statusOf(authorizeAssetAccess(context, asset))).toBe(401);+ state.caller = "outsider";+ expect(await statusOf(authorizeAssetAccess(context, asset))).toBe(403);+ state.caller = "member";+ expect(await statusOf(authorizeAssetAccess(context, asset))).toBe(200);+ },+ );});diff --git a/tests/api/utils/outbound-request.test.ts b/tests/api/utils/outbound-request.test.tsnew file mode 100644index 000000000..a596b9cfe--- /dev/null+++ b/tests/api/utils/outbound-request.test.ts@@ -0,0 +1,159 @@+import { createHmac } from "node:crypto";+import { createServer, type Server } from "node:http";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { postToGenericWebhook } from "../../../apps/api/src/plugins/generic-webhook/client";+import { postToTelegram } from "../../../apps/api/src/plugins/telegram/client";+import {+ safeOutboundError,+ sendOutboundRequest,+} from "../../../apps/api/src/utils/outbound-request";++let server: Server;+let base: string;+let redirected = 0;+let receivedSignature: string | string[] | undefined;+let receivedBody = "";+beforeEach(async () => {+ redirected = 0;+ receivedSignature = undefined;+ receivedBody = "";+ server = createServer((request, response) => {+ if (request.url === "/signed") {+ receivedSignature = request.headers["x-kaneo-signature"];+ request.on("data", (chunk) => {+ receivedBody += chunk.toString();+ });+ request.on("end", () => response.end());+ return;+ }+ if (request.url === "/hang") return;+ if (request.url === "/redirect") {+ response.writeHead(307, { Location: `${base}/target` });+ response.end();+ return;+ }+ if (request.url === "/target") redirected++;+ if (request.url === "/slow-json") {+ response.writeHead(200);+ response.write('{"ok":');+ return;+ }+ if (request.url === "/error") {+ response.writeHead(500);+ response.write("secret echoed by server");+ return;+ }+ if (request.url === "/big-json") {+ response.end(JSON.stringify({ ok: true, data: "x".repeat(32_768) }));+ return;+ }+ response.end('{"ok":true}');+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const address = server.address();+ if (!address || typeof address === "string")+ throw new Error("Missing test port");+ base = `http://127.0.0.1:${address.port}`;+ vi.stubEnv("KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS", "true");+});+afterEach(async () => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+});++describe("outbound notification transport", () => {+ it("accepts success and preserves HMAC-signed webhook payloads", async () => {+ await expect(+ postToGenericWebhook(`${base}/signed`, { title: "test" }, "secret"),+ ).resolves.toBeUndefined();+ expect(receivedBody).toBe(JSON.stringify({ title: "test" }));+ expect(receivedSignature).toBe(+ createHmac("sha256", "secret").update(receivedBody).digest("hex"),+ );+ await expect(+ sendOutboundRequest(`${base}/ok`, {}, { readJson: true }),+ ).resolves.toEqual({ ok: true });+ });+ it("refuses a redirect without sending any payload to its target", async () => {+ await expect(+ sendOutboundRequest(`${base}/redirect`, {+ body: "private",+ headers: { Authorization: "Bearer secret" },+ }),+ ).rejects.toMatchObject({ reason: "network" });+ expect(redirected).toBe(0);+ });+ it("rejects private destinations by default before fetching", async () => {+ vi.stubEnv("KANEO_ALLOW_PRIVATE_WEBHOOK_DESTINATIONS", "false");+ const fetchSpy = vi.spyOn(globalThis, "fetch");+ await expect(postToGenericWebhook(`${base}/ok`, {})).rejects.toMatchObject({+ reason: "destination",+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ });+ it.each(["/hang", "/slow-json"])(+ "times out both headers and body reads: %s",+ async (path) => {+ await expect(+ sendOutboundRequest(+ `${base}${path}`,+ {},+ { readJson: true, timeoutMs: 80 },+ ),+ ).rejects.toMatchObject({ reason: "timeout" });+ },+ );+ it("ignores an error body even when the peer never finishes it", async () => {+ await expect(+ sendOutboundRequest(`${base}/error`, {}, { timeoutMs: 500 }),+ ).rejects.toMatchObject({+ reason: "http",+ status: 500,+ message: "Outbound request failed: http (HTTP 500)",+ });+ });+ it("caps JSON response size", async () => {+ await expect(+ sendOutboundRequest(`${base}/big-json`, {}, { readJson: true }),+ ).rejects.toMatchObject({ reason: "response" });+ });+ it("drops credential-bearing fetch errors, causes and URLs", async () => {+ const secret = "private-bot-token";+ vi.stubGlobal(+ "fetch",+ vi.fn().mockRejectedValue(+ new Error(`Cannot reach https://api.telegram.org/bot${secret}`, {+ cause: { token: secret },+ }),+ ),+ );+ try {+ await postToTelegram(secret, { chat_id: "chat", text: "private" });+ expect.fail("Request should fail");+ } catch (error) {+ expect(error).toMatchObject({ reason: "network" });+ expect(error).not.toHaveProperty("cause");+ expect(String(error)).not.toContain(secret);+ expect(safeOutboundError(error)).toBe("Outbound request failed: network");+ }+ expect(safeOutboundError(new Error(secret))).not.toContain(secret);+ });+ it("does not expose Telegram's untrusted response description", async () => {+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockResolvedValue(+ new Response(+ JSON.stringify({ ok: false, description: "secret-value" }),+ ),+ ),+ );+ await expect(+ postToTelegram("token", { chat_id: "chat", text: "text" }),+ ).rejects.toMatchObject({ message: "Outbound request failed: response" });+ });+});diff --git a/tests/api/utils/sensitive-outbound.test.ts b/tests/api/utils/sensitive-outbound.test.tsnew file mode 100644index 000000000..d1aa18320--- /dev/null+++ b/tests/api/utils/sensitive-outbound.test.ts@@ -0,0 +1,114 @@+import { execFile } from "node:child_process";+import { createServer } from "node:http";+import { resolve } from "node:path";+import { promisify } from "node:util";+import { gunzipSync } from "node:zlib";+import { expect, it } from "vitest";+import {+ isSensitiveOutboundRequest,+ withoutOutboundTelemetry,+} from "../../../apps/api/src/utils/sensitive-outbound";++it("isolates sensitive delivery context from concurrent ordinary requests", async () => {+ let release!: () => void;+ const wait = new Promise<void>((done) => {+ release = done;+ });+ const sensitive = withoutOutboundTelemetry(async () => {+ expect(isSensitiveOutboundRequest()).toBe(true);+ await wait;+ expect(isSensitiveOutboundRequest()).toBe(true);+ });+ expect(isSensitiveOutboundRequest()).toBe(false);+ release();+ await sensitive;+ expect(isSensitiveOutboundRequest()).toBe(false);+});++it("keeps credentials out of actual Sentry events, breadcrumbs and spans while retaining ordinary HTTP telemetry", async () => {+ const envelopes: string[] = [];+ const paths: string[] = [];+ const server = createServer(async (request, response) => {+ const chunks: Buffer[] = [];+ for await (const chunk of request) chunks.push(Buffer.from(chunk));+ const bytes = Buffer.concat(chunks);+ if (request.url?.includes("/envelope/")) {+ envelopes.push(+ (request.headers["content-encoding"] === "gzip"+ ? gunzipSync(bytes)+ : bytes+ ).toString(),+ );+ response.writeHead(200, { "content-type": "application/json" }).end("{}");+ } else {+ paths.push(request.url ?? "");+ response+ .writeHead(request.url?.includes("failure") ? 500 : 200, {+ "content-type": "application/json",+ })+ .end("{}");+ }+ });+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("No test port");+ const base = `http://127.0.0.1:${address.port}`;+ try {+ await promisify(execFile)(+ process.execPath,+ [+ "--import",+ "tsx",+ "--input-type=module",+ "-e",+ `+ await import('./src/instrument.ts');+ const Sentry = await import('@sentry/node');+ const { sendOutboundRequest } = await import('./src/utils/outbound-request.ts');+ const { withoutOutboundTelemetry } = await import('./src/utils/sensitive-outbound.ts');+ const http = await import('node:http');+ const base = process.env.TELEMETRY_TEST_BASE;+ await Sentry.startSpan({ name: 'notification-test', op: 'test' }, async () => {+ await sendOutboundRequest(base + '/bot/FETCH_SECRET/sendMessage?token=QUERY_SECRET', { body: 'BODY_SECRET', headers: { Authorization: 'Bearer HEADER_SECRET' } });+ try { await sendOutboundRequest(base + '/failure/FAILURE_SECRET', {}); }+ catch (error) { Sentry.captureException(error); }+ await withoutOutboundTelemetry(() => new Promise((resolve, reject) => {+ http.get(base + '/hooks/HTTP_SECRET', (response) => { response.resume(); response.on('end', resolve); }).on('error', reject);+ }));+ await fetch(base + '/ordinary-http-marker');+ Sentry.captureMessage('safe-delivery-probe');+ });+ await Sentry.close(5000);+ `,+ ],+ {+ cwd: resolve(import.meta.dirname, "../../../apps/api"),+ env: {+ ...process.env,+ SENTRY_DSN: `${base.replace("://", "://public@")}/1`,+ SENTRY_TRACES_SAMPLE_RATE: "1",+ SENTRY_PROFILES_SAMPLE_RATE: "0",+ TELEMETRY_TEST_BASE: base,+ },+ timeout: 20000,+ },+ );+ expect(paths).toHaveLength(4);+ const telemetry = envelopes.join("\n");+ expect(telemetry).toContain("safe-delivery-probe");+ expect(telemetry).toContain("ordinary-http-marker");+ expect(telemetry).toContain("Outbound request failed: http");+ for (const secret of [+ "FETCH_SECRET",+ "QUERY_SECRET",+ "BODY_SECRET",+ "HEADER_SECRET",+ "FAILURE_SECRET",+ "HTTP_SECRET",+ ])+ expect(telemetry).not.toContain(secret);+ } finally {+ server.closeAllConnections();+ await new Promise<void>((done) => server.close(() => done()));+ }+}, 30000);diff --git a/tests/api/utils/verify-turnstile.test.ts b/tests/api/utils/verify-turnstile.test.tsindex f108d85c2..3116e481b 100644--- a/tests/api/utils/verify-turnstile.test.ts+++ b/tests/api/utils/verify-turnstile.test.ts@@ -1,87 +1,100 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { verifyTurnstile } from "../../../apps/api/src/utils/verify-turnstile";-describe("verifyTurnstile", () => {- const originalSecret = process.env.TURNSTILE_SECRET_KEY;- const originalFetch = globalThis.fetch;-- beforeEach(() => {- process.env.TURNSTILE_SECRET_KEY = "test-secret";- });-- afterEach(() => {- if (originalSecret === undefined) {- delete process.env.TURNSTILE_SECRET_KEY;- } else {- process.env.TURNSTILE_SECRET_KEY = originalSecret;- }- globalThis.fetch = originalFetch;- vi.restoreAllMocks();- });-- it("returns ok when no secret is configured (self-hosted opt-out)", async () => {- delete process.env.TURNSTILE_SECRET_KEY;- const result = await verifyTurnstile("any-token", "1.2.3.4");- expect(result.ok).toBe(true);- });-- it("fails when the token is missing", async () => {- const result = await verifyTurnstile(null);- expect(result.ok).toBe(false);- });-- it("posts the secret, token, and remoteip to Cloudflare", async () => {- const fetchMock = vi.fn().mockResolvedValue({- json: async () => ({ success: true }),- });- globalThis.fetch = fetchMock as unknown as typeof fetch;-- const result = await verifyTurnstile("good-token", "203.0.113.7");-- expect(result.ok).toBe(true);- expect(fetchMock).toHaveBeenCalledOnce();- const [url, init] = fetchMock.mock.calls[0] ?? [];- expect(url).toBe(- "https://challenges.cloudflare.com/turnstile/v0/siteverify",+beforeEach(() => {+ vi.stubEnv("TURNSTILE_SECRET_KEY", "secret");+ vi.stubEnv("KANEO_CLIENT_URL", "https://app.example.com");+});+afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+});+describe("Turnstile verification contract", () => {+ it.each([null, undefined, {}, "", "x".repeat(2049)])(+ "rejects missing or malformed tokens before network access (%s)",+ async (token) => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ expect((await verifyTurnstile(token)).ok).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ },+ );+ it.each([+ { success: true, hostname: "other.example.com", action: "auth" },+ { success: true, hostname: "app.example.com", action: "other" },+ { success: true, hostname: "app.example.com" },+ { success: "true", hostname: "app.example.com", action: "auth" },+ { success: false, hostname: "app.example.com", action: "auth" },+ ])("rejects invalid verification context %j", async (payload) => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(JSON.stringify(payload))),);- const body = (init as { body: URLSearchParams }).body;- expect(body.get("secret")).toBe("test-secret");- expect(body.get("response")).toBe("good-token");- expect(body.get("remoteip")).toBe("203.0.113.7");+ expect((await verifyTurnstile("token")).ok).toBe(false);});-- it("returns the cloudflare error codes on failure", async () => {- globalThis.fetch = vi.fn().mockResolvedValue({- json: async () => ({- success: false,- "error-codes": ["invalid-input-response"],+ it("requires strict success, the auth action and exact deployment hostname", async () => {+ const fetchMock = vi.fn(+ async (_url: unknown, _options: unknown) =>+ new Response(+ JSON.stringify({+ success: true,+ hostname: "app.example.com",+ action: "auth",+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ expect(await verifyTurnstile("token")).toEqual({ ok: true });+ expect(fetchMock).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ redirect: "error",+ signal: expect.any(AbortSignal),}),- }) as unknown as typeof fetch;-- const result = await verifyTurnstile("bad-token");- expect(result.ok).toBe(false);- if (!result.ok) {- expect(result.reason).toContain("invalid-input-response");- }+ );+ const options = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined;+ const body = options?.body;+ if (!(body instanceof URLSearchParams))+ throw new Error("Expected verification form body");+ expect(body.get("response")).toBe("token");+ expect(body.get("secret")).toBe("secret");+ expect(body.has("remoteip")).toBe(false);});-- it("fails gracefully when the fetch throws", async () => {- globalThis.fetch = vi+ it("fails closed on malformed JSON, HTTP failure or transport errors", async () => {+ const fetchMock = vi.fn()- .mockRejectedValue(new Error("network down")) as unknown as typeof fetch;-- const result = await verifyTurnstile("token");- expect(result.ok).toBe(false);+ .mockResolvedValueOnce(new Response("invalid json"))+ .mockResolvedValueOnce(new Response("upstream secret", { status: 500 }))+ .mockRejectedValueOnce(new Error("upstream secret"));+ vi.stubGlobal("fetch", fetchMock);+ for (let i = 0; i < 3; i++)+ expect(await verifyTurnstile("token")).toEqual({+ ok: false,+ reason: "Captcha verification failed.",+ });+ });+ it("preserves explicit opt-out when no secret is configured", async () => {+ vi.stubEnv("TURNSTILE_SECRET_KEY", "");+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ expect(await verifyTurnstile(null)).toEqual({ ok: true });+ expect(fetchMock).not.toHaveBeenCalled();});it.each(["5000ms", "1e3", "", "abc", "-100", "0", "5000"])(- "ignores malformed TURNSTILE_TIMEOUT_MS=%p",+ "keeps the bounded verifier contract with legacy TURNSTILE_TIMEOUT_MS=%p",async (raw) => {- process.env.TURNSTILE_TIMEOUT_MS = raw;- const fetchMock = vi.fn().mockResolvedValue({- json: async () => ({ success: true }),- });- globalThis.fetch = fetchMock as unknown as typeof fetch;+ vi.stubEnv("TURNSTILE_TIMEOUT_MS", raw);+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ success: true,+ action: "auth",+ hostname: "app.example.com",+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);const result = await verifyTurnstile("token");diff --git a/tests/api/ws/label-deletion-backpressure.test.ts b/tests/api/ws/label-deletion-backpressure.test.tsnew file mode 100644index 000000000..e35955486--- /dev/null+++ b/tests/api/ws/label-deletion-backpressure.test.ts@@ -0,0 +1,120 @@+import type { WSContext } from "hono/ws";+import { afterEach, describe, expect, it, vi } from "vitest";+import { eventContext, publishEvent } from "../../../apps/api/src/events";+import {+ addConnection,+ initializeWebSocketAdapter,+ removeConnection,+ shutdownWebSocketAdapter,+} from "../../../apps/api/src/ws";++const m = vi.hoisted(() => ({+ redis: false,+ publish: vi.fn(),+ sub: {+ on: vi.fn(),+ off: vi.fn(),+ psubscribe: vi.fn(),+ punsubscribe: vi.fn(),+ },+}));+vi.mock("../../../apps/api/src/redis", () => ({+ isRedisConfigured: () => m.redis,+ getRedisPub: () => ({ publish: m.publish }),+ getRedisSub: () => m.sub,+ closeRedis: vi.fn(),+}));+afterEach(async () => {+ await shutdownWebSocketAdapter();+ vi.clearAllMocks();+});++describe("awaited label deletion broadcasts", () => {+ it("delivers immediately through the real in-memory adapter and excludes the initiator", async () => {+ m.redis = false;+ await initializeWebSocketAdapter();+ const observer = { send: vi.fn() };+ const initiator = { send: vi.fn() };+ const foreign = { send: vi.fn() };+ const connections = [+ [+ "project",+ addConnection(+ "project",+ observer as unknown as WSContext,+ "observer",+ "other",+ ),+ ],+ [+ "project",+ addConnection(+ "project",+ initiator as unknown as WSContext,+ "initiator",+ "self",+ ),+ ],+ [+ "foreign",+ addConnection(+ "foreign",+ foreign as unknown as WSContext,+ "foreign",+ "another",+ ),+ ],+ ] as const;+ try {+ await eventContext.run({ initiatorId: "self" }, () =>+ publishEvent(+ "task.label_deleted",+ { projectId: "project", taskId: "task" },+ { waitForHandlers: true },+ ),+ );+ expect(observer.send).toHaveBeenCalledTimes(1);+ expect(JSON.parse(observer.send.mock.calls[0][0])).toEqual({+ type: "TASK_LABEL_UPDATED",+ projectId: "project",+ taskId: "task",+ });+ expect(initiator.send).not.toHaveBeenCalled();+ expect(foreign.send).not.toHaveBeenCalled();+ } finally {+ for (const [project, connection] of connections)+ removeConnection(project, connection);+ }+ });++ it("does not complete the event while the real Redis adapter is awaiting publication", async () => {+ m.redis = true;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ m.publish.mockImplementation(() => gate);+ await initializeWebSocketAdapter();+ let completed = false;+ const operation = publishEvent(+ "task.label_deleted",+ { projectId: "project", taskId: "task" },+ { waitForHandlers: true },+ ).then(() => {+ completed = true;+ });+ try {+ await vi.waitFor(() => expect(m.publish).toHaveBeenCalledTimes(1));+ expect(completed).toBe(false);+ expect(m.publish.mock.calls[0][0]).toBe("kaneo:ws:project:broadcast");+ expect(JSON.parse(m.publish.mock.calls[0][1])).toMatchObject({+ projectId: "project",+ message: { type: "TASK_LABEL_UPDATED", taskId: "task" },+ });+ } finally {+ release();+ }+ await operation;+ expect(completed).toBe(true);+ });+});diff --git a/tests/api/ws/security.test.ts b/tests/api/ws/security.test.tsnew file mode 100644index 000000000..a6a7936e9--- /dev/null+++ b/tests/api/ws/security.test.ts@@ -0,0 +1,54 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { assertWebSocketOrigin } from "../../../apps/api/src/ws/security";++afterEach(() => vi.unstubAllEnvs());++describe("WebSocket origin configuration", () => {+ it("fails closed in production without configured origins, including wildcards", () => {+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("KANEO_CLIENT_URL", "");+ vi.stubEnv("KANEO_API_URL", "");+ vi.stubEnv(+ "CORS_ORIGINS",+ "*,null,invalid,https://user:[email protected]",+ );+ for (const origin of [+ "null",+ "http://localhost:5173",+ "https://example.test",+ ]) {+ expect(() => assertWebSocketOrigin(new Headers({ origin }))).toThrow(+ "origin is not allowed",+ );+ }+ });+ it("uses configured URL origins, never request Host or forwarding headers", () => {+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("KANEO_CLIENT_URL", "https://app.example.test/");+ vi.stubEnv("KANEO_API_URL", "https://api.example.test/api");+ vi.stubEnv(+ "CORS_ORIGINS",+ "https://extra.example.test, https://other.example.test",+ );+ for (const origin of [+ "https://app.example.test",+ "https://api.example.test",+ "https://extra.example.test",+ "https://other.example.test",+ ]) {+ expect(() =>+ assertWebSocketOrigin(new Headers({ origin })),+ ).not.toThrow();+ }+ expect(() =>+ assertWebSocketOrigin(+ new Headers({+ origin: "https://evil.example.test",+ host: "evil.example.test",+ "x-forwarded-host": "evil.example.test",+ authorization: "Bearer native-token",+ }),+ ),+ ).toThrow("origin is not allowed");+ });+});diff --git a/tests/storage-integration/README.md b/tests/storage-integration/README.mdnew file mode 100644index 000000000..5c0997213--- /dev/null+++ b/tests/storage-integration/README.md@@ -0,0 +1,24 @@+# Local storage contract tests++These tests use a disposable S3-compatible service on `127.0.0.1` with the fixed, non-production credentials `local-test-access` / `local-test-secret-only`. They refuse remote endpoints, create a unique test bucket and delete only that bucket and its test objects afterwards. Never point them at an existing storage service.++Start a local MinIO test container bound to loopback with those root credentials:++```sh+docker run --rm -d --name kaneo-storage-contract-test \+ -p 127.0.0.1:59039:9000 \+ -e MINIO_ROOT_USER=local-test-access \+ -e MINIO_ROOT_PASSWORD=local-test-secret-only \+ -e MINIO_BROWSER=off -e MINIO_UPDATE=off \+ quay.io/minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e \+ server /data --address :9000+```++Once the service is ready, run:++```sh+KANEO_STORAGE_TEST_ENDPOINT=http://127.0.0.1:59039 pnpm --filter @kaneo/api exec vitest run --config vitest.storage.config.ts+docker stop kaneo-storage-contract-test+```++The suite checks signed size/content-type enforcement, chunked-transfer rejection, actual object metadata, missing objects and oversized-object cleanup. The regular API integration suite separately covers endpoint authorization and database writes with mocked storage calls. No real cloud account or email provider is required.diff --git a/tests/storage-integration/presigned-upload.test.ts b/tests/storage-integration/presigned-upload.test.tsnew file mode 100644index 000000000..0e3c7a1fd--- /dev/null+++ b/tests/storage-integration/presigned-upload.test.ts@@ -0,0 +1,169 @@+import { request } from "node:http";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import {+ CreateBucketCommand,+ DeleteBucketCommand,+ HeadObjectCommand,+ ListObjectsV2Command,+ PutObjectCommand,+ S3Client,+} from "../../apps/api/node_modules/@aws-sdk/client-s3";+import {+ createTaskImageUploadUrl,+ deleteS3Object,+ verifyTaskAssetUpload,+} from "../../apps/api/src/storage/s3";++vi.mock("dotenv-mono", () => ({ config: () => {} }));++// biome-ignore lint/suspicious/noUndeclaredEnvVars: This opt-in suite runs directly in Vitest, outside Turbo's task cache.+const endpoint = process.env.KANEO_STORAGE_TEST_ENDPOINT;+if (+ !endpoint ||+ new URL(endpoint).hostname !== "127.0.0.1" ||+ new URL(endpoint).protocol !== "http:"+) {+ throw new Error(+ "Set KANEO_STORAGE_TEST_ENDPOINT to the disposable loopback S3 service (http://127.0.0.1:PORT). Real storage endpoints are not allowed.",+ );+}+const bucket = `kaneo-security-${Date.now()}-test`;+const client = new S3Client({+ endpoint,+ region: "us-east-1",+ forcePathStyle: true,+ credentials: {+ accessKeyId: "local-test-access",+ secretAccessKey: "local-test-secret-only",+ },+});++beforeAll(async () => {+ vi.stubEnv("S3_ENDPOINT", endpoint);+ vi.stubEnv("S3_BUCKET", bucket);+ vi.stubEnv("S3_ACCESS_KEY_ID", "local-test-access");+ vi.stubEnv("S3_SECRET_ACCESS_KEY", "local-test-secret-only");+ vi.stubEnv("S3_REGION", "us-east-1");+ vi.stubEnv("S3_FORCE_PATH_STYLE", "true");+ vi.stubEnv("S3_KEY_PREFIX", "");+ vi.stubEnv("S3_MAX_IMAGE_UPLOAD_BYTES", "64");+ await client.send(new CreateBucketCommand({ Bucket: bucket }));+});+afterAll(async () => {+ try {+ const objects = await client.send(+ new ListObjectsV2Command({ Bucket: bucket }),+ );+ for (const object of objects.Contents ?? [])+ if (object.Key) await deleteS3Object(object.Key);+ await client.send(new DeleteBucketCommand({ Bucket: bucket }));+ } finally {+ client.destroy();+ vi.unstubAllEnvs();+ }+});++function presign(size = 12) {+ return createTaskImageUploadUrl({+ workspaceId: "local",+ projectId: "local",+ taskId: "local",+ surface: "description",+ filename: "test.png",+ contentType: "image/png",+ size,+ });+}+function head(key: string) {+ return client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));+}++describe("presigned uploads against real local S3 storage", () => {+ it("accepts an exact-size File upload and verifies stored metadata", async () => {+ const upload = await presign(64);+ const response = await fetch(upload.uploadUrl, {+ method: "PUT",+ headers: upload.headers,+ body: new File([new Uint8Array(64)], "test.png", { type: "image/png" }),+ });+ expect(response.status).toBe(200);+ expect(+ await verifyTaskAssetUpload(upload.key, {+ size: 64,+ contentType: "image/png",+ }),+ ).toEqual({ size: 64, contentType: "image/png" });+ });+ it.each([1, 13, 65, 4096])(+ "rejects a body of %i bytes signed for 12 bytes without storing it",+ async (size) => {+ const upload = await presign();+ const response = await fetch(upload.uploadUrl, {+ method: "PUT",+ headers: upload.headers,+ body: new Uint8Array(size),+ });+ expect(response.status).toBe(403);+ await response.body?.cancel();+ await expect(head(upload.key)).rejects.toMatchObject({+ $metadata: { httpStatusCode: 404 },+ });+ },+ );+ it("rejects a changed Content-Type without storing the object", async () => {+ const upload = await presign();+ const response = await fetch(upload.uploadUrl, {+ method: "PUT",+ headers: { "Content-Type": "text/html" },+ body: new Uint8Array(12),+ });+ expect(response.status).toBe(403);+ await response.body?.cancel();+ await expect(head(upload.key)).rejects.toMatchObject({+ $metadata: { httpStatusCode: 404 },+ });+ });+ it("rejects unsigned chunked transfer without Content-Length", async () => {+ const upload = await presign();+ const status = await new Promise<number>((resolve, reject) => {+ const req = request(+ upload.uploadUrl,+ {+ method: "PUT",+ headers: { ...upload.headers, "transfer-encoding": "chunked" },+ },+ (response) => {+ response.resume();+ response.on("end", () => resolve(response.statusCode ?? 0));+ },+ );+ req.on("error", reject);+ req.end(Buffer.alloc(4096));+ });+ expect(status).toBeGreaterThanOrEqual(400);+ expect(status).toBeLessThan(500);+ await expect(head(upload.key)).rejects.toMatchObject({+ $metadata: { httpStatusCode: 404 },+ });+ });+ it("rejects missing objects and removes old oversized objects during verification", async () => {+ const { key } = await presign();+ await expect(+ verifyTaskAssetUpload(key, { size: 12, contentType: "image/png" }),+ ).rejects.toThrow("Uploaded object was not found");+ await client.send(+ new PutObjectCommand({+ Bucket: bucket,+ Key: key,+ Body: Buffer.alloc(65),+ ContentType: "image/png",+ }),+ );+ await expect(+ verifyTaskAssetUpload(key, { size: 12, contentType: "image/png" }),+ ).rejects.toThrow("exceeds the maximum");+ await expect(head(key)).rejects.toMatchObject({+ $metadata: { httpStatusCode: 404 },+ });+ });+});