Compare commits

..
Author SHA1 Message Date
sriram veeraghantaandGitHub d0a4adc55b release: v1.3.1 #8917 2026-05-15 01:39:46 +05:30
sriram veeraghantaandGitHub 1dabc632bf fix: pnpm path for Docker builds (#9079)
Add $PNPM_HOME/bin to PATH so corepack-installed pnpm binaries are
resolvable during Docker builds.
2026-05-15 01:05:14 +05:30
sriram veeraghantaandGitHub 761c999e0c fix: add WEBHOOK_ALLOWED_HOSTS allowlist for internal webhook targets (#9078)
* fix: add WEBHOOK_ALLOWED_HOSTS allowlist for internal webhook targets

The IP-based allowlist alone isn't practical for containerised deployments
where service IPs are dynamic. Adds a hostname-based bypass for trusted
internal services (e.g. Silo via docker-compose / k8s service DNS) and
makes the previously hardcoded ["plane.so"] domain blocklist configurable
via WEBHOOK_DISALLOWED_DOMAINS.

- validate_url accepts allowed_hosts (exact, case-insensitive match;
  skips DNS lookup for trusted names)
- WebhookSerializer wires both settings through and lets allowlisted
  hosts bypass the disallowed-domain check
- Exposes WEBHOOK_ALLOWED_HOSTS in aio/cli deployment env files

* fix: default WEBHOOK_DISALLOWED_DOMAINS to empty for self-hosted

* fix: pass WEBHOOK_ALLOWED_HOSTS to send-time webhook re-validation
2026-05-15 00:57:39 +05:30
sriram veeraghantaandGitHub 32fb88ab24 chore(deps): bump axios, uuid and add security overrides (#8930)
* chore(deps): bump axios, uuid and add security overrides

Bump axios 1.15.0 → 1.15.2 and uuid 13.0.0 → 14.0.0 in the catalog,
and add pnpm overrides pinning postcss >=8.5.10, follow-redirects
>=1.16.0, and routing axios/uuid through the catalog.

* fix: overrides
2026-04-25 17:40:33 +05:30
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
03a2be84b7 chore(deps): bump lxml (#8925)
Bumps the pip group with 1 update in the /apps/api/requirements directory: [lxml](https://github.com/lxml/lxml).


Updates `lxml` from 6.0.0 to 6.1.0
- [Release notes](https://github.com/lxml/lxml/releases)
- [Changelog](https://github.com/lxml/lxml/blob/master/CHANGES.txt)
- [Commits](https://github.com/lxml/lxml/compare/lxml-6.0.0...lxml-6.1.0)

---
updated-dependencies:
- dependency-name: lxml
  dependency-version: 6.1.0
  dependency-type: direct:production
  dependency-group: pip
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-22 13:03:43 +05:30
sriramveeraghanta c62930ebcf chore: bump up the package version 2026-04-20 17:20:12 +05:30
sriram veeraghantaandGitHub f1d567accc chore: add Claude Code skills for PR descriptions and release notes (#8920)
* chore: add Claude Code skills for PR descriptions and release notes

* chore(skills): update release-notes branches to canary->master and example version to v1.3.0

* chore(skills): address PR review comments

- pr-description: infer base branch from PR metadata, fix Improvement wording, reference template's screenshot placeholder verbatim
- release-notes: add `text` language to unlabeled fenced code block
2026-04-20 17:17:54 +05:30
sriram veeraghantaandGitHub 62b2d1b207 chore: update CODEOWNERS for apps and deployments (#8919)
* chore: update CODEOWNERS for apps and deployments

Assign owners per app/area so reviews are routed to the right
maintainers.

* chore: update the codeowners
2026-04-20 17:17:34 +05:30
da41f14a05 chore(ci): suppress CodeQL file coverage deprecation warning (#8916)
* chore(ci): suppress CodeQL file coverage deprecation warning

Explicitly opt into the new default behavior where CodeQL skips
computing file coverage information on pull requests for improved
analysis performance.

* Update .github/workflows/codeql.yml

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-20 15:39:30 +05:30
sriram veeraghantaandGitHub aea66f53f4 fix: sanitize filenames in upload paths to prevent path traversal (#8879)
* fix: sanitize filenames in upload paths to prevent path traversal (GHSA-v57h-5999-w7xp)

Add server-side filename sanitization across all file upload endpoints
to prevent path traversal sequences (../) in user-supplied filenames
from being incorporated into S3 object keys. While S3 keys are flat
strings and not vulnerable to filesystem traversal, this adds
defense-in-depth and prevents S3 key pollution.

Changes:
- Add sanitize_filename() utility in path_validator.py
- Sanitize filenames in get_upload_path() for FileAsset and IssueAttachment models
- Sanitize name parameter in all upload view endpoints

* fix: address PR review feedback on filename sanitization

- Remove unused `import re`
- Normalize backslashes to forward slashes before os.path.basename()
  so Windows-style paths (e.g. ..\..\..\evil.txt) are handled on POSIX
- Strip whitespace before removing leading dots so " .env" is caught
- Return None instead of "unnamed" for empty input so existing
  `if not name` validation guards remain effective
- Add `or "unnamed"` fallback at call sites that lack a name guard

* fix: use random hex name as fallback in get_upload_path instead of "unnamed"

* fix: resolve ruff E501 line too long in DuplicateAssetEndpoint
2026-04-20 15:33:30 +05:30
Saurabh KumarandGitHub 45b4fc8932 [SILO-1158] chore: add context for project in relations API (#8860)
* add context for project in relations API

* modify issue relation serializer
2026-04-20 15:29:28 +05:30
sriram veeraghantaandGitHub a8a16c8ba0 fix: replace IS_SELF_MANAGED with WEBHOOK_ALLOWED_IPS allowlist (#8884)
* fix: replace IS_SELF_MANAGED toggle with explicit WEBHOOK_ALLOWED_IPS allowlist

Instead of blanket-allowing all private IPs on self-managed deployments,
webhook URL validation now blocks all private/internal IPs by default and
only permits specific networks listed in the WEBHOOK_ALLOWED_IPS env
variable (comma-separated IPs/CIDRs).

* fix: address PR review comments for webhook SSRF protection

- Sanitize error messages to avoid leaking internal details to clients
- Guard against TypeError with mixed IPv4/IPv6 allowlist networks
- Re-validate webhook URL at send time to prevent DNS-rebinding
- Add unit tests for mixed-version IP network allowlists
2026-04-20 15:28:33 +05:30
sriram veeraghantaandGitHub ac11c3ef79 fix: enforce workspace membership on V2 asset endpoints (#8885)
WorkspaceFileAssetEndpoint had no authorization checks beyond
authentication, allowing any logged-in user to create, read, patch,
and delete assets in any workspace by slug. DuplicateAssetEndpoint
only authorized the destination workspace, letting users copy assets
from workspaces they don't belong to.

Add @allow_permission decorators to all WorkspaceFileAssetEndpoint
methods and scope DuplicateAssetEndpoint's source asset lookup to
workspaces where the caller is an active member.

Ref: GHSA-qw87-v5w3-6vxx
2026-04-20 15:26:59 +05:30
Phạm Nguyên PhươngandGitHub 13db2f883f enhance sub-issue query performance with optimized annotations and subqueries (#8889) 2026-04-14 13:54:28 +05:30
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
bbf14fba31 chore(deps): bump pytest (#8891)
Bumps the pip group with 1 update in the /apps/api/requirements directory: [pytest](https://github.com/pytest-dev/pytest).


Updates `pytest` from 9.0.2 to 9.0.3
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/9.0.2...9.0.3)

---
updated-dependencies:
- dependency-name: pytest
  dependency-version: 9.0.3
  dependency-type: direct:production
  dependency-group: pip
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-14 13:54:04 +05:30
Anmol Singh BhatiaandGitHub db3c8f27dc [WEB-6840] feat: skip role & use-case steps for self-hosted instances (#8890) 2026-04-13 18:24:12 +05:30
sriram veeraghantaandGitHub 39325d28a6 chore: update dependencies (Django, cryptography, axios, lodash) (#8880)
* chore: update dependencies (Django, cryptography, axios, lodash)

- Django 4.2.29 → 4.2.30
- cryptography 46.0.6 → 46.0.7
- axios 1.13.5 → 1.15.0
- lodash 4.17.23 → 4.18.0

* chore: update lodash from 4.18.0 to 4.18.1
2026-04-10 01:13:02 +05:30
sriram veeraghantaandGitHub c21d2c6fb3 chore: remove Intercom integration and chat support components (#8875)
Intercom is no longer used. This removes all related frontend components,
hooks, custom events, API config, types, and i18n keys.
2026-04-10 00:16:45 +05:30
b-saikrishnakanthandGitHub e6b9d4c9ba [WEB-6785] fix: update border for project timezone (#8870) 2026-04-09 21:30:48 +05:30
b-saikrishnakanthandGitHub 6023e8cfc8 [WEB-6784] feat scrollbar in shortcuts modal (#8872)
* fix: update border for project timezone

* feat: added scrollbar in keyboard shortcuts modal

* fix: remove unnecessary changes

* fix: remove redundant overflow
2026-04-09 21:30:15 +05:30
okxintandGitHub 77c4b9c774 fix: strip whitespace and handle null values in instance configuration (#8744)
When patching instance configuration values, the raw values from
request.data were used directly without sanitization. This adds:
- Whitespace stripping via str().strip() to prevent leading/trailing
  spaces from being stored
- Explicit None handling so that null values become empty strings
  instead of the literal string "None"
2026-04-08 16:06:52 +05:30
sriram veeraghantaandGitHub 8a2579ce9b fix: prevent ORM field injection via segment parameter in analytics (GHSA-93x3-ghh7-72j3) (#8864)
* fix: prevent ORM field injection via segment parameter in analytics (GHSA-93x3-ghh7-72j3)

Centralize analytics field allowlists into VALID_ANALYTICS_FIELDS and
VALID_YAXIS constants in analytics_plot.py. Add defense-in-depth
validation in build_graph_plot() and extract_axis() so no caller can
pass arbitrary field references to Django F() expressions. Add missing
segment validation to SavedAnalyticEndpoint. Also fixes ExportAnalytics
using "estimate_point" instead of "estimate_point__value".

* fix: address PR review - remove unused imports and validate stored query params

Remove unused VALID_ANALYTICS_FIELDS and VALID_YAXIS imports from
analytic_plot_export.py. Add x_axis/y_axis allowlist validation in
SavedAnalyticEndpoint for stored query_dict values to prevent 500
errors from malformed saved analytics.
2026-04-07 16:04:48 +05:30
Niels KaspersandGitHub 7c2fc2dd7f fix: update Twitter icon and links to X (#8785) (#8790) 2026-04-07 15:34:54 +05:30
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
d1db13c3a7 chore(deps): bump vite in the npm_and_yarn group across 1 directory (#8863)
Bumps the npm_and_yarn group with 1 update in the / directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `vite` from 7.3.1 to 7.3.2
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v7.3.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 7.3.2
  dependency-type: direct:production
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-07 13:18:46 +05:30
sriram veeraghantaandGitHub cf696d200d release: v1.3.0 #8835 2026-04-06 20:00:08 +05:30
sriram veeraghantaandGitHub bb128e3e16 chore: upgrade turbo from v2.8.12 to v2.9.4 (#8859) 2026-04-06 16:04:57 +05:30
63fac3b8c4 fix: validate redirects in favicon fetching to prevent SSRF (#8858)
* fix: validate redirects in favicon fetching to prevent SSRF

The previous SSRF fix (GHSA-jcc6-f9v6-f7jw) only validated redirects for
the main page URL but not for the favicon fetch path. An attacker could
craft an HTML page with a favicon link that redirects to a private IP,
bypassing the IP validation and leaking internal network data as base64.

Extract a reusable `safe_get()` function that validates every redirect hop
against private/internal IPs and use it for both page and favicon fetches.

Resolves: GHSA-9fr2-pprw-pp9j

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review feedback for SSRF favicon fix

- Fix off-by-one in redirect limit: only raise RuntimeError when the
  response is still a redirect after MAX_REDIRECTS hops, not when the
  final response is a successful 200
- Return final URL from safe_get() so favicon href resolution uses the
  correct origin after redirects instead of the original URL
- Add unit tests for validate_url_ip and safe_get covering private IP
  blocking, redirect-following, and redirect limit enforcement

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:04:43 +05:30
587fe76032 fix: prevent privilege escalation in project member role updates (GHSA-494h-3rcq-5g3c) (#8833)
Restrict role modification in ProjectMemberViewSet.partial_update to
Admins only and enforce that requesters cannot modify or assign roles
equal to or higher than their own. Previously, Guests could demote
Admins by exploiting a missing lower-bound check on role changes.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 15:54:01 +05:30
Anmol Singh BhatiaandGitHub a18d90da86 [WEB-6813] fix: module not associated when accepting intake work items (#8839)
* fix: intake module association on accept

* chore: code refactoring
2026-03-31 23:39:34 +05:30
Akshat JainandGitHub febf98ea54 [INFRA-351] fix: correct directory and command for space program in supervisor.conf #8838 2026-03-31 18:53:51 +05:30
sriramveeraghanta 5747dc6fd8 chore: Intake snooze modal width 2026-03-31 18:26:41 +05:30
Akshat JainandGitHub d83944cc8d [INFRA-346] chore: remove artifacts.plane.so references from community deployments (#8836) 2026-03-31 17:56:32 +05:30
sriramveeraghanta 799b9cbfc5 chore: adding traget commit sha for the github release 2026-03-31 17:54:47 +05:30
sriram veeraghantaandGitHub a01b51fca5 fix: scope IssueBulkUpdateDateEndpoint query to workspace and project (#8834)
The bulk update date endpoint fetched issues by ID without filtering
by workspace or project, allowing any authenticated project member to
modify start_date and target_date of issues in any workspace/project
across the entire instance (IDOR - CWE-639).

Scoped the query to include workspace__slug and project_id filters,
consistent with other issue endpoints in the codebase.

Ref: GHSA-4q54-h4x9-m329
2026-03-31 17:43:35 +05:30
sriramveeraghanta 00a51f5e6a chore: version bump 2026-03-31 17:09:35 +05:30
b73d6344ad chore(deps): replace dotenvx with dotenv and update overrides (#8832)
* chore(deps): replace dotenvx with dotenv and update dependency overrides

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: sort devDependencies in package.json files

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 16:55:17 +05:30
f0ec84661d chore(deps): update dependency overrides (#8831)
Update brace-expansion override from 2.0.2 to 5.0.5 and add picomatch,
yaml@1, and yaml@2 overrides to pin transitive dependency versions.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 16:32:31 +05:30
Anmol Singh BhatiaandGitHub d8ed19f204 [WEB-6794] fix: align profile cover update with correct unsplash and upload handling (#8830)
* fix: profile cover update

* chore: code refactoring

* chore: code refactoring
2026-03-31 15:54:12 +05:30
Saurabh KumarandGitHub 9fa707b260 [SILO-1026] feat: add estimates external API endpoints (#8664)
* add project summary endpoint

* update response structure

* add estimates external API endpoints with migrations

* fix invalid project and workspace error
2026-03-30 15:30:02 +05:30
Saurabh KumarandGitHub d7c80885fd [SILO-1087] feat: add IssueRelations external API (#8763)
* add IssueRelations external API

* update serializer methods and filter by slug
2026-03-30 15:29:16 +05:30
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
9851fe0b8f chore(deps): bump cryptography (#8819)
Bumps the pip group with 1 update in the /apps/api/requirements directory: [cryptography](https://github.com/pyca/cryptography).


Updates `cryptography` from 46.0.5 to 46.0.6
- [Changelog](https://github.com/pyca/cryptography/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pyca/cryptography/compare/46.0.5...46.0.6)

---
updated-dependencies:
- dependency-name: cryptography
  dependency-version: 46.0.6
  dependency-type: direct:production
  dependency-group: pip
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-30 12:28:39 +05:30
Anmol Singh BhatiaandGitHub 5e237938ff [WEB-6783] fix: crash when deleting work item from peek view in workspace spreadsheet (#8821)
* fix: guard against undefined issue in SpreadsheetIssueRow

* fix: add defensive guard for isIssueNew in list block-root
2026-03-30 12:20:39 +05:30
b-saikrishnakanthandGitHub f0468a9173 [WEB-6763] fix: date range dropdown clipped in sub-issues list #8809 2026-03-27 16:01:24 +05:30
b-saikrishnakanthandGitHub c53968a7f8 [WEB-6762] fix: missing profile icons for recent activities on "Your Work" Page #8812 2026-03-27 16:00:51 +05:30
AaronandGitHub 97b4abd693 fix: tsdown watch (#8813)
closes #8791
2026-03-27 15:59:55 +05:30
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
130ba5ee6c chore(deps): bump requests (#8804)
Bumps the pip group with 1 update in the /apps/api/requirements directory: [requests](https://github.com/psf/requests).


Updates `requests` from 2.32.4 to 2.33.0
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.32.4...v2.33.0)

---
updated-dependencies:
- dependency-name: requests
  dependency-version: 2.33.0
  dependency-type: direct:production
  dependency-group: pip
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-03-27 00:11:02 +05:30
M. PalanikannanandGitHub 113bba46ea fix: migrate page navigation pane tabs from headless ui to propel (#8805) 2026-03-26 20:43:03 +05:30
b-saikrishnakanthandGitHub ce401c723e [WEB-6734] fix: circular progress indicator stroke color#8802 2026-03-26 18:13:57 +05:30
b-saikrishnakanthandGitHub 5396d438a3 Open [WEB-6739] fix: color inside of active projects of analytics overview tab #8803 2026-03-26 18:13:30 +05:30
Anmol Singh BhatiaandGitHub 942d2b98ef [WEB-6702] feat: redesign intake action buttons and use design tokens (#8801)
* feat: intake action buttons redesign

* chore: code refactoring
2026-03-26 18:12:24 +05:30
140 changed files with 2998 additions and 1669 deletions
+58
View File
@@ -0,0 +1,58 @@
---
name: pr-description
description: Generate a PR description following the project's GitHub PR template. Analyzes the current branch's changes against the base branch to produce a complete, filled-out PR description.
user_invocable: true
---
# PR Description Generator
Generate a pull request description based on the project's PR template at `.github/pull_request_template.md`.
## Steps
1. **Determine the base branch**: Prefer the PR's actual `baseRefName` (via `gh pr view <PR> --json baseRefName`) when a PR exists. Otherwise default by intent — feature PRs target `preview`, release PRs target `master`. If still ambiguous, ask the user.
2. **Analyze changes**: Run the following to understand what changed:
- `git log <base>...HEAD --oneline` to see all commits on this branch
- `git diff <base>...HEAD --stat` to see which files changed
- `git diff <base>...HEAD` to read the actual diff (use `--no-color`)
- If the diff is very large, focus on the most important files first
3. **Fill out the PR template** with the following sections:
### Description
Write a clear, concise summary of what the PR does and why. Focus on the "what" and "why", not line-by-line changes. Mention any important implementation decisions.
### Type of Change
Check the appropriate box(es) based on the changes:
- Bug fix (non-breaking change which fixes an issue)
- Feature (non-breaking change which adds functionality)
- Improvement (non-breaking change that improves existing functionality)
- Code refactoring
- Performance improvements
- Documentation update
### Screenshots and Media
Leave this section for the user to fill in, preserving the existing placeholder comment from `.github/pull_request_template.md` verbatim rather than introducing different text.
### Test Scenarios
Based on the code changes, suggest specific test scenarios that should be verified. Be concrete (e.g., "Navigate to project settings and verify the new toggle works") rather than generic.
### References
- If commit messages or branch name reference a work item identifier (e.g., `WEB-1234`), include it
- If the user provides a linked issue, include it
- If Sentry issue links or IDs (e.g., `SENTRY-ABC123`, Sentry URLs) were mentioned earlier in the conversation, include them as references
4. **Output format**: Print the filled-out markdown template so the user can copy it directly. Do NOT wrap it in a code fence — output the raw markdown.
## Guidelines
- Keep the description concise but informative
- Use bullet points for multiple changes
- Focus on user-facing impact, not implementation details
- If the branch has a Plane work item ID in its name (e.g., `WEB-1234`), reference it
- Don't fabricate test scenarios that aren't relevant to the actual changes
+147
View File
@@ -0,0 +1,147 @@
---
name: release-notes
description: "Generate release notes for a Plane release PR in `makeplane/plane` (semver, e.g. `release: vX.Y.Z`). Reads PR commits, filters out noise, categorizes by conventional-commit type, optionally enriches via Plane MCP, and writes the result as the PR description."
user_invocable: true
---
# Release Notes Generator
Generate structured release notes from a Plane release PR by parsing its commit list, then update the PR description.
## Versioning
Plane community uses **semver** (`vX.Y.Z`, major.minor.patch) for releases.
- PR title format: `release: vX.Y.Z`
- Source branch: `canary`
- Target branch: `master`
## When to Use
- User links/mentions a Plane release PR (e.g. `release: v1.3.0`) and asks for release notes
- User asks to "create release notes" / "update PR description" for a release PR in `makeplane/plane`
- The branch is named `canary` or `release/x.y.z` and the base is `master`
## Steps
### 1. Fetch commits
```bash
gh pr view <PR_NUM> --json title,body,baseRefName,headRefName,commits \
--jq '.commits[] | .messageHeadline + "\n---BODY---\n" + .messageBody + "\n===END==="'
```
For a quick scan first:
```bash
gh pr view <PR_NUM> --json commits \
--jq '.commits[] | {oid: .oid[0:10], message: .messageHeadline}'
```
### 2. Filter out noise
**Always exclude** these commits — mechanical, not user-facing:
| Pattern | Reason |
| -------------------------------------------- | -------------- |
| `fix: merge conflicts` | Merge artifact |
| `Merge branch '...' of github.com:...` | Merge artifact |
| `Revert "..."` (when immediately re-applied) | Internal churn |
### 3. Parse work item IDs
Most meaningful commits begin with a Plane work item identifier in brackets:
- `[WEB-XXXX]` — web/frontend product items
- `[SILO-XXXX]` — Silo (integrations: Slack, GitHub, GitLab, Jira/Linear)
- `[MOBILE-XXXX]`, `[API-XXXX]`, etc.
Always preserve these IDs in the release notes — they let readers click through to the source ticket.
### 4. (Optional) Enrich via Plane MCP
For larger features where the commit headline is terse, fetch the work item:
```text
mcp__plane__retrieve_work_item_by_identifier(project_identifier="WEB", issue_identifier=6874)
```
Use the returned `name` and `description_stripped` to flesh out the bullet. Skip this for routine fixes — commit body is usually enough. Don't enrich every item (slow + work item descriptions are often empty).
### 5. Categorize by conventional-commit type
| Commit prefix | Section |
| -------------------------------- | ------------------- |
| `feat:`, `feat(scope):` | ✨ New Features |
| `fix:`, `fix(scope):` | 🐛 Bug Fixes |
| `refactor:` | 🔧 Refactor & Chore |
| `chore:`, `chore(scope):` | 🔧 Refactor & Chore |
| `chore(deps):`, dependabot bumps | 📦 Dependencies |
### 6. Format
```markdown
# Release vX.Y.Z
## ✨ New Features
- **<Short title>** — [WEB-XXXX] (#PR_NUM)
Optional 12 sentence elaboration drawn from commit body.
## 🐛 Bug Fixes
- **<Short title>** — [WEB-XXXX] (#PR_NUM)
## 🔧 Refactor & Chore
- **<Short title>** — [WEB-XXXX] (#PR_NUM)
## 📦 Dependencies
- Bump `<package>` X.Y.Z → A.B.C (#PR_NUM)
```
Rules:
- Lead with a bold human-readable title (rewrite the commit subject if cryptic)
- Always include the work item ID in brackets and the merge PR number in parens
- Add a sub-line elaboration only when the commit body has substance worth surfacing (acceptance criteria, scope notes, gotchas like "behind feature flag", "requires migration", "requires Vercel setting")
- Drop empty sections
### 7. Update the PR description
```bash
gh pr edit <PR_NUM> --body "$(cat <<'EOF'
<release notes markdown>
EOF
)"
```
Always use a HEREDOC with single-quoted `'EOF'` so backticks/dollars in the notes are preserved.
## Quick Reference: end-to-end
```bash
PR=2498
gh pr view $PR --json commits --jq '.commits[] | .messageHeadline + "\n---\n" + .messageBody + "\n==="' > /tmp/commits.txt
# read /tmp/commits.txt, filter, categorize, draft notes
gh pr edit $PR --body "$(cat <<'EOF'
... release notes ...
EOF
)"
```
## Common Mistakes
- **Including `fix: merge conflicts`** — merge artifact, no functional content
- **Dropping the work item ID** — readers rely on `[WEB-XXXX]` to navigate to the ticket
- **Over-enriching with MCP lookups** — work item descriptions are often empty; commit body is usually richer
- **Missing the merge PR number** — always include `(#NNNN)` from the commit subject so reviewers can audit the source PR
- **Using `--body` without HEREDOC** — backticks/dollar signs get shell-interpreted and corrupt the notes
- **Editing the title** — release PR titles are version markers; only edit the body
## Plane-Specific Conventions
- Release PRs go from `canary``master`
- PR title format: `release: vX.Y.Z` semver (major.minor.patch)
- Commits coming from feature branches always carry a work item ID; commits without one are usually infra/chores
+1
View File
@@ -397,6 +397,7 @@ jobs:
with:
tag_name: ${{ env.REL_VERSION }}
name: ${{ env.REL_VERSION }}
target_commitish: ${{ github.sha }}
draft: false
prerelease: ${{ env.IS_PRERELEASE }}
generate_release_notes: true
+3
View File
@@ -16,6 +16,9 @@ jobs:
contents: read
security-events: write
env:
CODEQL_ACTION_FILE_COVERAGE_ON_PRS: "false"
strategy:
fail-fast: false
matrix:
+8 -1
View File
@@ -1 +1,8 @@
eslint.config.mjs @lifeiscontent
.oxlintrc.json @sriramveeraghanta @lifeiscontent
.oxfmtrc.json @sriramveeraghanta @lifeiscontent
apps/api/ @dheeru0198 @pablohashescobar
apps/web/ @sriramveeraghanta
apps/space/ @sriramveeraghanta
apps/admin/ @sriramveeraghanta
apps/live/ @Palanikannan1437
deployments/ @mguptahub
+1 -1
View File
@@ -10,7 +10,7 @@
<p align="center">
<a href="https://plane.so/"><b>Website</b></a> •
<a href="https://forum.plane.so"><b>Forum</b></a> •
<a href="https://twitter.com/planepowers"><b>Twitter</b></a> •
<a href="https://x.com/planepowers"><b>X</b></a> •
<a href="https://docs.plane.so/"><b>Documentation</b></a>
</p>
+2 -2
View File
@@ -4,7 +4,7 @@ WORKDIR /app
ENV TURBO_TELEMETRY_DISABLED=1
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV PATH="$PNPM_HOME:$PNPM_HOME/bin:$PATH"
ENV CI=1
RUN corepack enable pnpm
@@ -13,7 +13,7 @@ RUN corepack enable pnpm
FROM base AS builder
RUN pnpm add -g turbo@2.8.12
RUN pnpm add -g turbo@2.9.4
COPY . .
@@ -16,8 +16,6 @@ import { Input, ToggleSwitch } from "@plane/ui";
import { ControllerInput } from "@/components/common/controller-input";
// hooks
import { useInstance } from "@/hooks/store";
// components
import { IntercomConfig } from "./intercom";
export interface IGeneralConfigurationForm {
instance: IInstance;
@@ -27,14 +25,13 @@ export interface IGeneralConfigurationForm {
export const GeneralConfigurationForm = observer(function GeneralConfigurationForm(props: IGeneralConfigurationForm) {
const { instance, instanceAdmins } = props;
// hooks
const { instanceConfigurations, updateInstanceInfo, updateInstanceConfigurations } = useInstance();
const { updateInstanceInfo } = useInstance();
// form data
const {
handleSubmit,
control,
formState: { errors, isSubmitting },
watch,
} = useForm<Partial<IInstance>>({
defaultValues: {
instance_name: instance?.instance_name,
@@ -45,17 +42,6 @@ export const GeneralConfigurationForm = observer(function GeneralConfigurationFo
const onSubmit = async (formData: Partial<IInstance>) => {
const payload: Partial<IInstance> = { ...formData };
// update the intercom configuration
const isIntercomEnabled =
instanceConfigurations?.find((config) => config.key === "IS_INTERCOM_ENABLED")?.value === "1";
if (!payload.is_telemetry_enabled && isIntercomEnabled) {
try {
await updateInstanceConfigurations({ IS_INTERCOM_ENABLED: "0" });
} catch (error) {
console.error(error);
}
}
await updateInstanceInfo(payload)
.then(() =>
setToast({
@@ -112,8 +98,7 @@ export const GeneralConfigurationForm = observer(function GeneralConfigurationFo
</div>
<div className="space-y-6">
<div className="border-b border-subtle pb-1.5 text-16 font-medium text-primary">Chat + telemetry</div>
<IntercomConfig isTelemetryEnabled={watch("is_telemetry_enabled") ?? false} />
<div className="border-b border-subtle pb-1.5 text-16 font-medium text-primary">Telemetry</div>
<div className="flex items-center gap-14">
<div className="flex grow items-center gap-4">
<div className="shrink-0">
@@ -1,86 +0,0 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { useState } from "react";
import { observer } from "mobx-react";
import useSWR from "swr";
import { MessageSquare } from "lucide-react";
import type { IFormattedInstanceConfiguration } from "@plane/types";
import { ToggleSwitch } from "@plane/ui";
// hooks
import { useInstance } from "@/hooks/store";
type TIntercomConfig = {
isTelemetryEnabled: boolean;
};
export const IntercomConfig = observer(function IntercomConfig(props: TIntercomConfig) {
const { isTelemetryEnabled } = props;
// hooks
const { instanceConfigurations, updateInstanceConfigurations, fetchInstanceConfigurations } = useInstance();
// states
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
// derived values
const isIntercomEnabled = isTelemetryEnabled
? instanceConfigurations
? instanceConfigurations?.find((config) => config.key === "IS_INTERCOM_ENABLED")?.value === "1"
? true
: false
: undefined
: false;
const { isLoading } = useSWR(isTelemetryEnabled ? "INSTANCE_CONFIGURATIONS" : null, () =>
isTelemetryEnabled ? fetchInstanceConfigurations() : null
);
const initialLoader = isLoading && isIntercomEnabled === undefined;
const submitInstanceConfigurations = async (payload: Partial<IFormattedInstanceConfiguration>) => {
try {
await updateInstanceConfigurations(payload);
} catch (error) {
console.error(error);
} finally {
setIsSubmitting(false);
}
};
const enableIntercomConfig = () => {
void submitInstanceConfigurations({ IS_INTERCOM_ENABLED: isIntercomEnabled ? "0" : "1" });
};
return (
<>
<div className="flex items-center gap-14">
<div className="flex grow items-center gap-4">
<div className="shrink-0">
<div className="flex size-11 items-center justify-center rounded-lg bg-layer-1">
<MessageSquare className="size-5 p-0.5 text-tertiary" />
</div>
</div>
<div className="grow">
<div className="text-13 leading-5 font-medium text-primary">Chat with us</div>
<div className="text-11 leading-5 font-regular text-tertiary">
Let your users chat with us via Intercom or another service. Toggling Telemetry off turns this off
automatically.
</div>
</div>
<div className="ml-auto">
<ToggleSwitch
value={isIntercomEnabled ? true : false}
onChange={enableIntercomConfig}
size="sm"
disabled={!isTelemetryEnabled || isSubmitting || initialLoader}
/>
</div>
</div>
</div>
</>
);
});
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "admin",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"description": "Admin UI for Plane",
"license": "AGPL-3.0",
@@ -49,7 +49,6 @@
"uuid": "catalog:"
},
"devDependencies": {
"@dotenvx/dotenvx": "catalog:",
"@plane/tailwind-config": "workspace:*",
"@plane/typescript-config": "workspace:*",
"@react-router/dev": "catalog:",
@@ -57,6 +56,7 @@
"@types/node": "catalog:",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"dotenv": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vite-tsconfig-paths": "^5.1.4"
+1 -1
View File
@@ -1,5 +1,5 @@
import path from "node:path";
import * as dotenv from "@dotenvx/dotenvx";
import * as dotenv from "dotenv";
import { reactRouter } from "@react-router/dev/vite";
import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "plane-api",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"description": "API server powering Plane's backend",
"license": "AGPL-3.0"
+5 -1
View File
@@ -25,6 +25,10 @@ from .issue import (
IssueCommentCreateSerializer,
IssueLinkCreateSerializer,
IssueLinkUpdateSerializer,
IssueRelationCreateSerializer,
IssueRelationResponseSerializer,
IssueRelationSerializer,
RelatedIssueSerializer,
)
from .state import StateLiteSerializer, StateSerializer
from .cycle import (
@@ -49,7 +53,7 @@ from .intake import (
IntakeIssueCreateSerializer,
IntakeIssueUpdateSerializer,
)
from .estimate import EstimatePointSerializer
from .estimate import EstimateSerializer, EstimatePointSerializer
from .asset import (
UserAssetUploadSerializer,
AssetUpdateSerializer,
+25 -9
View File
@@ -2,20 +2,36 @@
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.
# Third party imports
from rest_framework import serializers
# Module imports
from plane.db.models import EstimatePoint
from plane.db.models import Estimate, EstimatePoint
from .base import BaseSerializer
class EstimatePointSerializer(BaseSerializer):
"""
Serializer for project estimation points and story point values.
class EstimateSerializer(BaseSerializer):
class Meta:
model = Estimate
fields = "__all__"
read_only_fields = ["workspace", "project", "deleted_at"]
Handles numeric estimation data for work item sizing and sprint planning,
providing standardized point values for project velocity calculations.
"""
def create(self, validated_data):
validated_data["workspace"] = self.context["workspace"]
validated_data["project"] = self.context["project"]
return super().create(validated_data)
class EstimatePointSerializer(BaseSerializer):
def validate(self, data):
if not data:
raise serializers.ValidationError("Estimate points are required")
value = data.get("value")
if value and len(value) > 20:
raise serializers.ValidationError("Value can't be more than 20 characters")
return data
class Meta:
model = EstimatePoint
fields = ["id", "value"]
read_only_fields = fields
fields = "__all__"
read_only_fields = ["estimate", "workspace", "project"]
+187
View File
@@ -20,6 +20,7 @@ from plane.db.models import (
IssueComment,
IssueLabel,
IssueLink,
IssueRelation,
Label,
ProjectMember,
State,
@@ -479,6 +480,192 @@ class IssueLinkSerializer(BaseSerializer):
]
class IssueRelationRefSerializer(serializers.Serializer):
"""Project-scoped reference to a related work item."""
project_id = serializers.UUIDField(help_text="Project containing the related work item")
issue_id = serializers.UUIDField(help_text="ID of the related work item")
class IssueRelationResponseSerializer(serializers.Serializer):
"""
Serializer for issue relations response showing grouped relation types.
Each list contains project_id and issue_id pairs so clients can resolve
cross-project relations.
"""
blocking = serializers.ListField(
child=IssueRelationRefSerializer(),
help_text="Work items blocking this issue",
)
blocked_by = serializers.ListField(
child=IssueRelationRefSerializer(),
help_text="Work items this issue is blocked by",
)
duplicate = serializers.ListField(
child=IssueRelationRefSerializer(),
help_text="Duplicate work items",
)
relates_to = serializers.ListField(
child=IssueRelationRefSerializer(),
help_text="Related work items",
)
start_after = serializers.ListField(
child=IssueRelationRefSerializer(),
help_text="Work items that start after this issue",
)
start_before = serializers.ListField(
child=IssueRelationRefSerializer(),
help_text="Work items that start before this issue",
)
finish_after = serializers.ListField(
child=IssueRelationRefSerializer(),
help_text="Work items that finish after this issue",
)
finish_before = serializers.ListField(
child=IssueRelationRefSerializer(),
help_text="Work items that finish before this issue",
)
class IssueRelationCreateSerializer(serializers.Serializer):
"""
Serializer for creating issue relations.
Creates issue relations with the specified relation type and issues.
Validates relation types and ensures proper issue ID format.
"""
RELATION_TYPE_CHOICES = [
("blocking", "Blocking"),
("blocked_by", "Blocked By"),
("duplicate", "Duplicate"),
("relates_to", "Relates To"),
("start_before", "Start Before"),
("start_after", "Start After"),
("finish_before", "Finish Before"),
("finish_after", "Finish After"),
]
relation_type = serializers.ChoiceField(
choices=RELATION_TYPE_CHOICES,
required=True,
help_text="Type of relationship between work items",
)
issues = serializers.ListField(
child=serializers.UUIDField(),
required=True,
min_length=1,
help_text="Array of work item IDs to create relations with",
)
def validate_issues(self, value):
"""Validate that issues list is not empty and contains valid UUIDs."""
if not value:
raise serializers.ValidationError("At least one issue ID is required.")
return value
class IssueRelationRemoveSerializer(serializers.Serializer):
"""
Serializer for removing issue relations.
Removes existing relationships between work items by specifying
the related issue ID.
"""
related_issue = serializers.UUIDField(
required=True, help_text="ID of the related work item to remove relation with"
)
class IssueRelationSerializer(BaseSerializer):
"""
Serializer for issue relationships showing related issue details.
Provides comprehensive information about related issues including
project context, sequence ID, and relationship type.
"""
id = serializers.UUIDField(source="related_issue.id", read_only=True)
project_id = serializers.UUIDField(source="related_issue.project_id", read_only=True)
sequence_id = serializers.IntegerField(source="related_issue.sequence_id", read_only=True)
name = serializers.CharField(source="related_issue.name", read_only=True)
relation_type = serializers.CharField(read_only=True)
state_id = serializers.UUIDField(source="related_issue.state.id", read_only=True)
priority = serializers.CharField(source="related_issue.priority", read_only=True)
class Meta:
model = IssueRelation
fields = [
"id",
"project_id",
"sequence_id",
"relation_type",
"name",
"state_id",
"priority",
"created_by",
"created_at",
"updated_at",
"updated_by",
]
read_only_fields = [
"workspace",
"project",
"created_by",
"created_at",
"updated_by",
"updated_at",
]
class RelatedIssueSerializer(BaseSerializer):
"""
Serializer for reverse issue relationships showing issue details.
Provides comprehensive information about the source issue in a relationship
including project context, sequence ID, and relationship type.
"""
id = serializers.UUIDField(source="issue.id", read_only=True)
project_id = serializers.PrimaryKeyRelatedField(source="issue.project_id", read_only=True)
sequence_id = serializers.IntegerField(source="issue.sequence_id", read_only=True)
name = serializers.CharField(source="issue.name", read_only=True)
type_id = serializers.UUIDField(source="issue.type.id", read_only=True)
relation_type = serializers.CharField(read_only=True)
is_epic = serializers.BooleanField(source="issue.type.is_epic", read_only=True)
state_id = serializers.UUIDField(source="issue.state.id", read_only=True)
priority = serializers.CharField(source="issue.priority", read_only=True)
class Meta:
model = IssueRelation
fields = [
"id",
"project_id",
"sequence_id",
"relation_type",
"name",
"type_id",
"is_epic",
"state_id",
"priority",
"created_by",
"created_at",
"updated_by",
"updated_at",
]
read_only_fields = [
"workspace",
"project",
"created_by",
"created_at",
"updated_by",
"updated_at",
]
class IssueAttachmentSerializer(BaseSerializer):
"""
Serializer for work item file attachments.
+29
View File
@@ -0,0 +1,29 @@
# Copyright (c) 2023-present Plane Software, Inc. and contributors
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.
from django.urls import path
from plane.api.views.estimate import (
ProjectEstimateAPIEndpoint,
EstimatePointListCreateAPIEndpoint,
EstimatePointDetailAPIEndpoint,
)
urlpatterns = [
path(
"workspaces/<str:slug>/projects/<uuid:project_id>/estimates/",
ProjectEstimateAPIEndpoint.as_view(http_method_names=["get", "post", "patch", "delete"]),
name="project-estimate",
),
path(
"workspaces/<str:slug>/projects/<uuid:project_id>/estimates/<uuid:estimate_id>/estimate-points/",
EstimatePointListCreateAPIEndpoint.as_view(http_method_names=["get", "post"]),
name="estimate-point-list-create",
),
path(
"workspaces/<str:slug>/projects/<uuid:project_id>/estimates/<uuid:estimate_id>/estimate-points/<uuid:estimate_point_id>/",
EstimatePointDetailAPIEndpoint.as_view(http_method_names=["patch", "delete"]),
name="estimate-point-detail",
),
]
+6
View File
@@ -17,6 +17,7 @@ from plane.api.views import (
IssueAttachmentDetailAPIEndpoint,
WorkspaceIssueAPIEndpoint,
IssueSearchEndpoint,
IssueRelationListCreateAPIEndpoint,
)
# Deprecated url patterns
@@ -145,6 +146,11 @@ new_url_patterns = [
IssueAttachmentDetailAPIEndpoint.as_view(http_method_names=["get", "patch", "delete"]),
name="work-item-attachment-detail",
),
path(
"workspaces/<str:slug>/projects/<uuid:project_id>/work-items/<uuid:issue_id>/relations/",
IssueRelationListCreateAPIEndpoint.as_view(http_method_names=["get", "post"]),
name="work-item-relation-list",
),
]
urlpatterns = old_url_patterns + new_url_patterns
+1
View File
@@ -29,6 +29,7 @@ from .issue import (
IssueAttachmentListCreateAPIEndpoint,
IssueAttachmentDetailAPIEndpoint,
IssueSearchEndpoint,
IssueRelationListCreateAPIEndpoint,
)
from .cycle import (
+4 -3
View File
@@ -17,6 +17,7 @@ from drf_spectacular.utils import OpenApiExample, OpenApiRequest
# Module Imports
from plane.bgtasks.storage_metadata_task import get_asset_object_metadata
from plane.settings.storage import S3Storage
from plane.utils.path_validator import sanitize_filename
from plane.db.models import FileAsset, User, Workspace
from plane.api.views.base import BaseAPIView
from plane.api.serializers import (
@@ -114,7 +115,7 @@ class UserAssetEndpoint(BaseAPIView):
This endpoint generates the necessary credentials for direct S3 upload.
"""
# get the asset key
name = request.data.get("name")
name = sanitize_filename(request.data.get("name")) or "unnamed"
type = request.data.get("type", "image/jpeg")
size = int(request.data.get("size", settings.FILE_SIZE_LIMIT))
entity_type = request.data.get("entity_type", False)
@@ -287,7 +288,7 @@ class UserServerAssetEndpoint(BaseAPIView):
necessary credentials for direct S3 upload with server-side authentication.
"""
# get the asset key
name = request.data.get("name")
name = sanitize_filename(request.data.get("name")) or "unnamed"
type = request.data.get("type", "image/jpeg")
size = int(request.data.get("size", settings.FILE_SIZE_LIMIT))
entity_type = request.data.get("entity_type", False)
@@ -498,7 +499,7 @@ class GenericAssetEndpoint(BaseAPIView):
Create a presigned URL for uploading generic assets that can be bound to entities like work items.
Supports various file types and includes external source tracking for integrations.
"""
name = request.data.get("name")
name = sanitize_filename(request.data.get("name"))
type = request.data.get("type")
size = int(request.data.get("size", settings.FILE_SIZE_LIMIT))
project_id = request.data.get("project_id")
+291
View File
@@ -0,0 +1,291 @@
# Copyright (c) 2023-present Plane Software, Inc. and contributors
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.
# Third party imports
from rest_framework.response import Response
from rest_framework import status
from drf_spectacular.utils import OpenApiRequest, OpenApiResponse
# Module imports
from plane.app.permissions.project import ProjectEntityPermission
from plane.api.views.base import BaseAPIView
from plane.db.models import Estimate, EstimatePoint, Project, Workspace
from plane.api.serializers import EstimateSerializer, EstimatePointSerializer
from plane.utils.openapi.decorators import estimate_docs, estimate_point_docs
from plane.utils.openapi import (
ESTIMATE_CREATE_EXAMPLE,
ESTIMATE_UPDATE_EXAMPLE,
ESTIMATE_POINT_CREATE_EXAMPLE,
ESTIMATE_POINT_UPDATE_EXAMPLE,
ESTIMATE_EXAMPLE,
ESTIMATE_POINT_EXAMPLE,
DELETED_RESPONSE,
WORKSPACE_SLUG_PARAMETER,
PROJECT_ID_PARAMETER,
ESTIMATE_ID_PARAMETER,
)
class ProjectEstimateAPIEndpoint(BaseAPIView):
permission_classes = [ProjectEntityPermission]
model = Estimate
serializer_class = EstimateSerializer
def get_queryset(self):
return self.model.objects.filter(workspace__slug=self.workspace_slug, project_id=self.project_id)
@estimate_docs(
operation_id="create_estimate",
summary="Create an estimate",
description="Create an estimate for a project",
request=OpenApiRequest(
request=EstimateSerializer,
examples=[ESTIMATE_CREATE_EXAMPLE],
),
)
def post(self, request, slug, project_id):
project = Project.objects.filter(id=project_id, workspace__slug=slug).first()
if not project:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Project not found"})
workspace = Workspace.objects.filter(slug=slug).first()
if not workspace:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Workspace not found"})
project_estimate = self.get_queryset().first()
if project_estimate:
# return 409 if the project estimate already exists
return Response(
status=status.HTTP_409_CONFLICT,
data={"error": "An estimate already exists for this project", "id": str(project_estimate.id)},
)
# create the project estimate
serializer = self.serializer_class(data=request.data, context={"workspace": workspace, "project": project})
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
@estimate_docs(
operation_id="get_estimate",
summary="Get an estimate",
description="Get an estimate for a project",
responses={
200: OpenApiResponse(
description="Estimate",
response=EstimateSerializer,
examples=[ESTIMATE_EXAMPLE],
),
},
)
def get(self, request, slug, project_id):
estimate = self.get_queryset().first()
if not estimate:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Estimate not found"})
serializer = self.serializer_class(estimate)
return Response(serializer.data, status=status.HTTP_200_OK)
@estimate_docs(
operation_id="update_estimate",
summary="Update an estimate",
description="Update an estimate for a project",
request=OpenApiRequest(
request=EstimateSerializer,
examples=[ESTIMATE_UPDATE_EXAMPLE],
),
responses={
200: OpenApiResponse(
description="Estimate",
response=EstimateSerializer,
examples=[ESTIMATE_EXAMPLE],
),
},
)
def patch(self, request, slug, project_id):
ALLOWED_FIELDS = ["name", "description"]
estimate = self.get_queryset().first()
if not estimate:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Estimate not found"})
filtered_data = {k: v for k, v in request.data.items() if k in ALLOWED_FIELDS}
if not filtered_data:
serializer = self.serializer_class(estimate)
return Response(serializer.data, status=status.HTTP_200_OK)
serializer = self.serializer_class(estimate, data=filtered_data, partial=True)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
@estimate_docs(
operation_id="delete_estimate",
summary="Delete an estimate",
description="Delete an estimate for a project",
responses={
204: DELETED_RESPONSE,
},
)
def delete(self, request, slug, project_id):
estimate = self.get_queryset().first()
if not estimate:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Estimate not found"})
estimate.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class EstimatePointListCreateAPIEndpoint(BaseAPIView):
"""List and bulk create estimate points for an estimate."""
permission_classes = [ProjectEntityPermission]
model = EstimatePoint
serializer_class = EstimatePointSerializer
def get_queryset(self):
return self.model.objects.filter(
estimate_id=self.kwargs["estimate_id"],
workspace__slug=self.kwargs["slug"],
project_id=self.kwargs["project_id"],
).select_related("estimate", "workspace", "project")
@estimate_point_docs(
operation_id="get_estimate_points",
summary="Get estimate points",
description="Get estimate points for an estimate",
parameters=[
WORKSPACE_SLUG_PARAMETER,
PROJECT_ID_PARAMETER,
ESTIMATE_ID_PARAMETER,
],
responses={
200: OpenApiResponse(
description="Estimate points",
response=EstimatePointSerializer(many=True),
examples=[ESTIMATE_POINT_EXAMPLE],
),
},
)
def get(self, request, slug, project_id, estimate_id):
estimate = Estimate.objects.filter(
id=estimate_id,
workspace__slug=slug,
project_id=project_id,
).first()
if not estimate:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Estimate not found"})
estimate_points = self.get_queryset()
serializer = self.serializer_class(estimate_points, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@estimate_point_docs(
operation_id="create_estimate_points",
summary="Create estimate points",
description="Create estimate points for an estimate",
request=OpenApiRequest(
request=EstimatePointSerializer,
examples=[ESTIMATE_POINT_CREATE_EXAMPLE],
),
responses={
201: OpenApiResponse(
description="Estimate points",
response=EstimatePointSerializer(many=True),
examples=[ESTIMATE_POINT_EXAMPLE],
),
},
)
def post(self, request, slug, project_id, estimate_id):
estimate = Estimate.objects.filter(
id=estimate_id,
workspace__slug=slug,
project_id=project_id,
).first()
if not estimate:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Estimate not found"})
estimate_points_data = (
request.data if isinstance(request.data, list) else request.data.get("estimate_points", [])
)
if not estimate_points_data:
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"error": "Estimate points are required"},
)
serializer = self.serializer_class(data=estimate_points_data, many=True)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
estimate_points = [
EstimatePoint(
estimate=estimate,
workspace=estimate.workspace,
project=estimate.project,
**item,
)
for item in serializer.validated_data
]
created = EstimatePoint.objects.bulk_create(estimate_points)
return Response(
self.serializer_class(created, many=True).data,
status=status.HTTP_201_CREATED,
)
class EstimatePointDetailAPIEndpoint(BaseAPIView):
"""Update and delete a single estimate point."""
permission_classes = [ProjectEntityPermission]
model = EstimatePoint
serializer_class = EstimatePointSerializer
def get_queryset(self):
return self.model.objects.filter(
estimate_id=self.kwargs["estimate_id"],
workspace__slug=self.kwargs["slug"],
project_id=self.kwargs["project_id"],
)
@estimate_point_docs(
operation_id="update_estimate_point",
summary="Update an estimate point",
description="Update an estimate point for an estimate",
request=OpenApiRequest(
request=EstimatePointSerializer,
examples=[ESTIMATE_POINT_UPDATE_EXAMPLE],
),
responses={
200: OpenApiResponse(
description="Estimate point",
response=EstimatePointSerializer,
examples=[ESTIMATE_POINT_EXAMPLE],
),
},
)
def patch(self, request, slug, project_id, estimate_id, estimate_point_id):
estimate_point = self.get_queryset().filter(id=estimate_point_id).first()
if not estimate_point:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Estimate point not found"})
ALLOWED_FIELDS = ["key", "value", "description"]
filtered_data = {k: v for k, v in request.data.items() if k in ALLOWED_FIELDS}
if not filtered_data:
return Response(self.serializer_class(estimate_point).data, status=status.HTTP_200_OK)
serializer = self.serializer_class(estimate_point, data=filtered_data, partial=True)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
@estimate_point_docs(
operation_id="delete_estimate_point",
summary="Delete an estimate point",
description="Delete an estimate point for an estimate",
responses={
204: DELETED_RESPONSE,
},
)
def delete(self, request, slug, project_id, estimate_id, estimate_point_id):
estimate_point = self.get_queryset().filter(id=estimate_point_id).first()
if not estimate_point:
return Response(status=status.HTTP_404_NOT_FOUND, data={"error": "Estimate point not found"})
estimate_point.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
+303 -13
View File
@@ -24,6 +24,7 @@ from django.db.models import (
When,
Subquery,
)
from django.utils import timezone
from django.conf import settings
@@ -45,6 +46,9 @@ from plane.api.serializers import (
IssueActivitySerializer,
IssueCommentSerializer,
IssueLinkSerializer,
IssueRelationCreateSerializer,
IssueRelationResponseSerializer,
IssueRelationSerializer,
IssueSerializer,
LabelSerializer,
IssueAttachmentUploadSerializer,
@@ -53,6 +57,7 @@ from plane.api.serializers import (
IssueLinkCreateSerializer,
IssueLinkUpdateSerializer,
LabelCreateUpdateSerializer,
RelatedIssueSerializer,
)
from plane.app.permissions import (
ProjectEntityPermission,
@@ -66,6 +71,7 @@ from plane.db.models import (
FileAsset,
IssueComment,
IssueLink,
IssueRelation,
Label,
Project,
ProjectMember,
@@ -73,13 +79,16 @@ from plane.db.models import (
Workspace,
)
from plane.settings.storage import S3Storage
from plane.utils.path_validator import sanitize_filename
from plane.bgtasks.storage_metadata_task import get_asset_object_metadata
from .base import BaseAPIView
from plane.utils.host import base_host
from plane.utils.issue_relation_mapper import get_actual_relation
from plane.bgtasks.webhook_task import model_activity
from plane.app.permissions import ROLE
from plane.utils.openapi import (
work_item_docs,
work_item_relation_docs,
label_docs,
issue_link_docs,
issue_comment_docs,
@@ -1119,9 +1128,9 @@ class IssueLinkListCreateAPIEndpoint(BaseAPIView):
return self.paginate(
request=request,
queryset=(self.get_queryset()),
on_results=lambda issue_links: IssueLinkSerializer(
issue_links, many=True, fields=self.fields, expand=self.expand
).data,
on_results=lambda issue_links: (
IssueLinkSerializer(issue_links, many=True, fields=self.fields, expand=self.expand).data
),
)
@issue_link_docs(
@@ -1226,9 +1235,9 @@ class IssueLinkDetailAPIEndpoint(BaseAPIView):
return self.paginate(
request=request,
queryset=(self.get_queryset()),
on_results=lambda issue_links: IssueLinkSerializer(
issue_links, many=True, fields=self.fields, expand=self.expand
).data,
on_results=lambda issue_links: (
IssueLinkSerializer(issue_links, many=True, fields=self.fields, expand=self.expand).data
),
)
issue_link = self.get_queryset().get(pk=pk)
serializer = IssueLinkSerializer(issue_link, fields=self.fields, expand=self.expand)
@@ -1377,9 +1386,9 @@ class IssueCommentListCreateAPIEndpoint(BaseAPIView):
return self.paginate(
request=request,
queryset=(self.get_queryset()),
on_results=lambda issue_comments: IssueCommentSerializer(
issue_comments, many=True, fields=self.fields, expand=self.expand
).data,
on_results=lambda issue_comments: (
IssueCommentSerializer(issue_comments, many=True, fields=self.fields, expand=self.expand).data
),
)
@issue_comment_docs(
@@ -1688,9 +1697,9 @@ class IssueActivityListAPIEndpoint(BaseAPIView):
return self.paginate(
request=request,
queryset=(issue_activities),
on_results=lambda issue_activity: IssueActivitySerializer(
issue_activity, many=True, fields=self.fields, expand=self.expand
).data,
on_results=lambda issue_activity: (
IssueActivitySerializer(issue_activity, many=True, fields=self.fields, expand=self.expand).data
),
)
@@ -1850,7 +1859,7 @@ class IssueAttachmentListCreateAPIEndpoint(BaseAPIView):
status=status.HTTP_403_FORBIDDEN,
)
name = request.data.get("name")
name = sanitize_filename(request.data.get("name"))
type = request.data.get("type", False)
size = request.data.get("size")
external_id = request.data.get("external_id")
@@ -2250,3 +2259,284 @@ class IssueSearchEndpoint(BaseAPIView):
)[: int(limit)]
return Response({"issues": issue_results}, status=status.HTTP_200_OK)
class IssueRelationListCreateAPIEndpoint(BaseAPIView):
"""Issue Relation List and Create Endpoint"""
serializer_class = IssueRelationSerializer
model = IssueRelation
permission_classes = [ProjectEntityPermission]
use_read_replica = True
@work_item_relation_docs(
operation_id="list_work_item_relations",
summary="List work item relations",
description="Retrieve all relationships for a work item including blocking, blocked_by, duplicate, relates_to, start_before, start_after, finish_before, and finish_after relations.", # noqa E501
parameters=[
ISSUE_ID_PARAMETER,
CURSOR_PARAMETER,
PER_PAGE_PARAMETER,
ORDER_BY_PARAMETER,
FIELDS_PARAMETER,
EXPAND_PARAMETER,
],
responses={
200: OpenApiResponse(
description="Work item relations grouped by relation type",
response=IssueRelationResponseSerializer,
examples=[
OpenApiExample(
name="Work Item Relations Response",
value={
"blocking": [
{
"project_id": "550e8400-e29b-41d4-a716-446655440010",
"issue_id": "550e8400-e29b-41d4-a716-446655440000",
},
{
"project_id": "550e8400-e29b-41d4-a716-446655440010",
"issue_id": "550e8400-e29b-41d4-a716-446655440001",
},
],
"blocked_by": [
{
"project_id": "550e8400-e29b-41d4-a716-446655440011",
"issue_id": "550e8400-e29b-41d4-a716-446655440002",
},
],
"duplicate": [],
"relates_to": [
{
"project_id": "550e8400-e29b-41d4-a716-446655440010",
"issue_id": "550e8400-e29b-41d4-a716-446655440003",
},
],
"start_after": [],
"start_before": [
{
"project_id": "550e8400-e29b-41d4-a716-446655440012",
"issue_id": "550e8400-e29b-41d4-a716-446655440004",
},
],
"finish_after": [],
"finish_before": [],
},
)
],
),
400: INVALID_REQUEST_RESPONSE,
404: ISSUE_NOT_FOUND_RESPONSE,
},
)
def get(self, request, slug, project_id, issue_id):
"""List work item relations
Retrieve all relationships for a work item organized by relation type.
Returns a structured response with relations grouped by type.
"""
relations = IssueRelation.objects.filter(
Q(issue_id=issue_id) | Q(related_issue_id=issue_id),
workspace__slug=slug,
).values(
"relation_type",
"issue_id",
"related_issue_id",
issue_project_id=F("issue__project_id"),
related_issue_project_id=F("related_issue__project_id"),
)
response_data = {
"blocking": [],
"blocked_by": [],
"duplicate": [],
"relates_to": [],
"start_after": [],
"start_before": [],
"finish_after": [],
"finish_before": [],
}
seen_duplicate = set()
seen_relates_to = set()
for rel in relations:
rt = rel["relation_type"]
if rt == "blocked_by":
if str(rel["related_issue_id"]) == str(issue_id):
response_data["blocking"].append(
{"project_id": str(rel["issue_project_id"]), "issue_id": str(rel["issue_id"])}
)
if str(rel["issue_id"]) == str(issue_id):
response_data["blocked_by"].append(
{"project_id": str(rel["related_issue_project_id"]), "issue_id": str(rel["related_issue_id"])}
)
elif rt == "duplicate":
if str(rel["issue_id"]) == str(issue_id) and rel["related_issue_id"] not in seen_duplicate:
seen_duplicate.add(rel["related_issue_id"])
response_data["duplicate"].append(
{"project_id": str(rel["related_issue_project_id"]), "issue_id": str(rel["related_issue_id"])}
)
if str(rel["related_issue_id"]) == str(issue_id) and rel["issue_id"] not in seen_duplicate:
seen_duplicate.add(rel["issue_id"])
response_data["duplicate"].append(
{"project_id": str(rel["issue_project_id"]), "issue_id": str(rel["issue_id"])}
)
elif rt == "relates_to":
if str(rel["issue_id"]) == str(issue_id) and rel["related_issue_id"] not in seen_relates_to:
seen_relates_to.add(rel["related_issue_id"])
response_data["relates_to"].append(
{"project_id": str(rel["related_issue_project_id"]), "issue_id": str(rel["related_issue_id"])}
)
if str(rel["related_issue_id"]) == str(issue_id) and rel["issue_id"] not in seen_relates_to:
seen_relates_to.add(rel["issue_id"])
response_data["relates_to"].append(
{"project_id": str(rel["issue_project_id"]), "issue_id": str(rel["issue_id"])}
)
elif rt == "start_before":
if str(rel["related_issue_id"]) == str(issue_id):
response_data["start_after"].append(
{"project_id": str(rel["issue_project_id"]), "issue_id": str(rel["issue_id"])}
)
if str(rel["issue_id"]) == str(issue_id):
response_data["start_before"].append(
{"project_id": str(rel["related_issue_project_id"]), "issue_id": str(rel["related_issue_id"])}
)
elif rt == "finish_before":
if str(rel["related_issue_id"]) == str(issue_id):
response_data["finish_after"].append(
{"project_id": str(rel["issue_project_id"]), "issue_id": str(rel["issue_id"])}
)
if str(rel["issue_id"]) == str(issue_id):
response_data["finish_before"].append(
{"project_id": str(rel["related_issue_project_id"]), "issue_id": str(rel["related_issue_id"])}
)
return Response(response_data, status=status.HTTP_200_OK)
@work_item_relation_docs(
operation_id="create_work_item_relation",
summary="Create work item relation",
description="Create relationships between work items. Supports various relation types including blocking, blocked_by, duplicate, relates_to, start_before, start_after, finish_before, and finish_after.", # noqa E501
parameters=[
ISSUE_ID_PARAMETER,
],
request=OpenApiRequest(
request=IssueRelationCreateSerializer,
examples=[
OpenApiExample(
name="Create blocking relation",
value={
"relation_type": "blocking",
"issues": [
"550e8400-e29b-41d4-a716-446655440000",
"550e8400-e29b-41d4-a716-446655440001",
],
},
)
],
),
responses={
201: OpenApiResponse(
description="Work item relations created successfully",
response=IssueRelationSerializer(many=True),
examples=[
OpenApiExample(
name="Relations created",
value=[
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Fix authentication bug",
"sequence_id": 42,
"project_id": "550e8400-e29b-41d4-a716-446655440001",
"relation_type": "blocked_by",
"state_id": "550e8400-e29b-41d4-a716-446655440002",
"priority": "high",
"created_at": "2024-01-15T10:00:00Z",
"updated_at": "2024-01-15T10:00:00Z",
"created_by": "550e8400-e29b-41d4-a716-446655440004",
"updated_by": "550e8400-e29b-41d4-a716-446655440004",
}
],
)
],
),
400: INVALID_REQUEST_RESPONSE,
404: ISSUE_NOT_FOUND_RESPONSE,
},
)
def post(self, request, slug, project_id, issue_id):
"""Create work item relation
Create relationships between work items with specified relation type.
Automatically tracks relation creation activity.
"""
# Validate request data using serializer
serializer = IssueRelationCreateSerializer(data=request.data)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
relation_type = serializer.validated_data["relation_type"]
issues = serializer.validated_data["issues"]
project = Project.objects.get(pk=project_id, workspace__slug=slug)
actual_relation = get_actual_relation(relation_type)
is_reverse = relation_type in ["blocking", "start_after", "finish_after"]
IssueRelation.objects.bulk_create(
[
IssueRelation(
issue_id=(issue if is_reverse else issue_id),
related_issue_id=(issue_id if is_reverse else issue),
relation_type=actual_relation,
project_id=project_id,
workspace_id=project.workspace_id,
created_by=request.user,
updated_by=request.user,
)
for issue in issues
],
batch_size=10,
ignore_conflicts=True,
)
issue_activity.delay(
type="issue_relation.activity.created",
requested_data=json.dumps(request.data, cls=DjangoJSONEncoder),
actor_id=str(request.user.id),
issue_id=str(issue_id),
project_id=str(project_id),
current_instance=None,
epoch=int(timezone.now().timestamp()),
notification=True,
origin=base_host(request=request, is_app=True),
)
# Re-fetch with select_related to avoid N+1 queries in serializers.
# bulk_create with ignore_conflicts=True may not return PKs,
# so query by the issue/related_issue pairs and relation type.
if is_reverse:
refetch_filter = Q(
issue_id__in=issues,
related_issue_id=issue_id,
relation_type=actual_relation,
)
else:
refetch_filter = Q(
issue_id=issue_id,
related_issue_id__in=issues,
relation_type=actual_relation,
)
refetched_relations = IssueRelation.objects.filter(
refetch_filter,
workspace__slug=slug,
).select_related(
"issue__state",
"related_issue__state",
)
serializer_class = RelatedIssueSerializer if is_reverse else IssueRelationSerializer
return Response(
serializer_class(refetched_relations, many=True).data,
status=status.HTTP_201_CREATED,
)
+30 -54
View File
@@ -3,90 +3,66 @@
# See the LICENSE file for details.
# Python imports
import socket
import ipaddress
import logging
from urllib.parse import urlparse
# Third party imports
from rest_framework import serializers
# Django imports
from django.conf import settings
# Module imports
from .base import DynamicBaseSerializer
from plane.db.models import Webhook, WebhookLog
from plane.db.models.webhook import validate_domain, validate_schema
from plane.utils.ip_address import validate_url
logger = logging.getLogger(__name__)
class WebhookSerializer(DynamicBaseSerializer):
url = serializers.URLField(validators=[validate_schema, validate_domain])
def create(self, validated_data):
url = validated_data.get("url", None)
# Extract the hostname from the URL
hostname = urlparse(url).hostname
if not hostname:
raise serializers.ValidationError({"url": "Invalid URL: No hostname found."})
# Resolve the hostname to IP addresses
def _validate_webhook_url(self, url):
"""Validate a webhook URL against SSRF and disallowed domain rules."""
try:
ip_addresses = socket.getaddrinfo(hostname, None)
except socket.gaierror:
raise serializers.ValidationError({"url": "Hostname could not be resolved."})
validate_url(
url,
allowed_ips=settings.WEBHOOK_ALLOWED_IPS,
allowed_hosts=settings.WEBHOOK_ALLOWED_HOSTS,
)
except ValueError as e:
logger.warning("Webhook URL validation failed for %s: %s", url, e)
raise serializers.ValidationError({"url": "Invalid or disallowed webhook URL."})
if not ip_addresses:
raise serializers.ValidationError({"url": "No IP addresses found for the hostname."})
hostname = (urlparse(url).hostname or "").rstrip(".").lower()
for addr in ip_addresses:
ip = ipaddress.ip_address(addr[4][0])
if ip.is_private or ip.is_loopback or ip.is_reserved or ip.is_link_local:
raise serializers.ValidationError({"url": "URL resolves to a blocked IP address."})
# Hosts explicitly trusted via WEBHOOK_ALLOWED_HOSTS bypass the
# disallowed-domain check — they're already trusted for SSRF, so
# the loop-back guard would only get in the way of legitimate
# sibling services that share a parent domain with Plane.
if hostname in settings.WEBHOOK_ALLOWED_HOSTS:
return
# Additional validation for multiple request domains and their subdomains
request = self.context.get("request")
disallowed_domains = ["plane.so"] # Add your disallowed domains here
disallowed_domains = list(settings.WEBHOOK_DISALLOWED_DOMAINS)
if request:
request_host = request.get_host().split(":")[0] # Remove port if present
request_host = request.get_host().split(":")[0].rstrip(".").lower()
disallowed_domains.append(request_host)
# Check if hostname is a subdomain or exact match of any disallowed domain
if any(hostname == domain or hostname.endswith("." + domain) for domain in disallowed_domains):
raise serializers.ValidationError({"url": "URL domain or its subdomain is not allowed."})
def create(self, validated_data):
url = validated_data.get("url", None)
self._validate_webhook_url(url)
return Webhook.objects.create(**validated_data)
def update(self, instance, validated_data):
url = validated_data.get("url", None)
if url:
# Extract the hostname from the URL
hostname = urlparse(url).hostname
if not hostname:
raise serializers.ValidationError({"url": "Invalid URL: No hostname found."})
# Resolve the hostname to IP addresses
try:
ip_addresses = socket.getaddrinfo(hostname, None)
except socket.gaierror:
raise serializers.ValidationError({"url": "Hostname could not be resolved."})
if not ip_addresses:
raise serializers.ValidationError({"url": "No IP addresses found for the hostname."})
for addr in ip_addresses:
ip = ipaddress.ip_address(addr[4][0])
if ip.is_private or ip.is_loopback or ip.is_reserved or ip.is_link_local:
raise serializers.ValidationError({"url": "URL resolves to a blocked IP address."})
# Additional validation for multiple request domains and their subdomains
request = self.context.get("request")
disallowed_domains = ["plane.so"] # Add your disallowed domains here
if request:
request_host = request.get_host().split(":")[0] # Remove port if present
disallowed_domains.append(request_host)
# Check if hostname is a subdomain or exact match of any disallowed domain
if any(hostname == domain or hostname.endswith("." + domain) for domain in disallowed_domains):
raise serializers.ValidationError({"url": "URL domain or its subdomain is not allowed."})
self._validate_webhook_url(url)
return super().update(instance, validated_data)
class Meta:
+14 -41
View File
@@ -29,7 +29,7 @@ from plane.db.models import (
Module,
)
from plane.utils.analytics_plot import build_graph_plot
from plane.utils.analytics_plot import build_graph_plot, VALID_ANALYTICS_FIELDS, VALID_YAXIS
from plane.utils.issue_filters import issue_filters
from plane.app.permissions import allow_permission, ROLE
@@ -41,32 +41,15 @@ class AnalyticsEndpoint(BaseAPIView):
y_axis = request.GET.get("y_axis", False)
segment = request.GET.get("segment", False)
valid_xaxis_segment = [
"state_id",
"state__group",
"labels__id",
"assignees__id",
"estimate_point__value",
"issue_cycle__cycle_id",
"issue_module__module_id",
"priority",
"start_date",
"target_date",
"created_at",
"completed_at",
]
valid_yaxis = ["issue_count", "estimate"]
# Check for x-axis and y-axis as thery are required parameters
if not x_axis or not y_axis or x_axis not in valid_xaxis_segment or y_axis not in valid_yaxis:
if not x_axis or not y_axis or x_axis not in VALID_ANALYTICS_FIELDS or y_axis not in VALID_YAXIS:
return Response(
{"error": "x-axis and y-axis dimensions are required and the values should be valid"},
status=status.HTTP_400_BAD_REQUEST,
)
# If segment is present it cannot be same as x-axis
if segment and (segment not in valid_xaxis_segment or x_axis == segment):
if segment and (segment not in VALID_ANALYTICS_FIELDS or x_axis == segment):
return Response(
{"error": "Both segment and x axis cannot be same and segment should be valid"},
status=status.HTTP_400_BAD_REQUEST,
@@ -214,13 +197,20 @@ class SavedAnalyticEndpoint(BaseAPIView):
x_axis = analytic_view.query_dict.get("x_axis", False)
y_axis = analytic_view.query_dict.get("y_axis", False)
if not x_axis or not y_axis:
if not x_axis or not y_axis or x_axis not in VALID_ANALYTICS_FIELDS or y_axis not in VALID_YAXIS:
return Response(
{"error": "x-axis and y-axis dimensions are required"},
{"error": "x-axis and y-axis dimensions are required and the values should be valid"},
status=status.HTTP_400_BAD_REQUEST,
)
segment = request.GET.get("segment", False)
if segment and (segment not in VALID_ANALYTICS_FIELDS or x_axis == segment):
return Response(
{"error": "Both segment and x axis cannot be same and segment should be valid"},
status=status.HTTP_400_BAD_REQUEST,
)
distribution = build_graph_plot(queryset=queryset, x_axis=x_axis, y_axis=y_axis, segment=segment)
total_issues = queryset.count()
return Response(
@@ -236,32 +226,15 @@ class ExportAnalyticsEndpoint(BaseAPIView):
y_axis = request.data.get("y_axis", False)
segment = request.data.get("segment", False)
valid_xaxis_segment = [
"state_id",
"state__group",
"labels__id",
"assignees__id",
"estimate_point",
"issue_cycle__cycle_id",
"issue_module__module_id",
"priority",
"start_date",
"target_date",
"created_at",
"completed_at",
]
valid_yaxis = ["issue_count", "estimate"]
# Check for x-axis and y-axis as thery are required parameters
if not x_axis or not y_axis or x_axis not in valid_xaxis_segment or y_axis not in valid_yaxis:
if not x_axis or not y_axis or x_axis not in VALID_ANALYTICS_FIELDS or y_axis not in VALID_YAXIS:
return Response(
{"error": "x-axis and y-axis dimensions are required and the values should be valid"},
status=status.HTTP_400_BAD_REQUEST,
)
# If segment is present it cannot be same as x-axis
if segment and (segment not in valid_xaxis_segment or x_axis == segment):
if segment and (segment not in VALID_ANALYTICS_FIELDS or x_axis == segment):
return Response(
{"error": "Both segment and x axis cannot be same and segment should be valid"},
status=status.HTTP_400_BAD_REQUEST,
+21 -6
View File
@@ -18,10 +18,11 @@ from rest_framework.permissions import AllowAny
# Module imports
from ..base import BaseAPIView
from plane.db.models import FileAsset, Workspace, Project, User
from plane.db.models import FileAsset, Workspace, Project, User, WorkspaceMember
from plane.settings.storage import S3Storage
from plane.app.permissions import allow_permission, ROLE
from plane.utils.cache import invalidate_cache_directly
from plane.utils.path_validator import sanitize_filename
from plane.bgtasks.storage_metadata_task import get_asset_object_metadata
from plane.throttles.asset import AssetRateThrottle
@@ -108,7 +109,7 @@ class UserAssetsV2Endpoint(BaseAPIView):
def post(self, request):
# get the asset key
name = request.data.get("name")
name = sanitize_filename(request.data.get("name")) or "unnamed"
type = request.data.get("type", "image/jpeg")
size = int(request.data.get("size", settings.FILE_SIZE_LIMIT))
entity_type = request.data.get("entity_type", False)
@@ -311,8 +312,9 @@ class WorkspaceFileAssetEndpoint(BaseAPIView):
else:
return
@allow_permission([ROLE.ADMIN, ROLE.MEMBER, ROLE.GUEST], level="WORKSPACE")
def post(self, request, slug):
name = request.data.get("name")
name = sanitize_filename(request.data.get("name")) or "unnamed"
type = request.data.get("type", "image/jpeg")
size = int(request.data.get("size", settings.FILE_SIZE_LIMIT))
entity_type = request.data.get("entity_type")
@@ -376,6 +378,7 @@ class WorkspaceFileAssetEndpoint(BaseAPIView):
status=status.HTTP_200_OK,
)
@allow_permission([ROLE.ADMIN, ROLE.MEMBER, ROLE.GUEST], level="WORKSPACE")
def patch(self, request, slug, asset_id):
# get the asset id
asset = FileAsset.objects.get(id=asset_id, workspace__slug=slug)
@@ -397,6 +400,7 @@ class WorkspaceFileAssetEndpoint(BaseAPIView):
asset.save(update_fields=["is_uploaded", "attributes"])
return Response(status=status.HTTP_204_NO_CONTENT)
@allow_permission([ROLE.ADMIN, ROLE.MEMBER, ROLE.GUEST], level="WORKSPACE")
def delete(self, request, slug, asset_id):
asset = FileAsset.objects.get(id=asset_id, workspace__slug=slug)
asset.is_deleted = True
@@ -406,6 +410,7 @@ class WorkspaceFileAssetEndpoint(BaseAPIView):
asset.save(update_fields=["is_deleted", "deleted_at"])
return Response(status=status.HTTP_204_NO_CONTENT)
@allow_permission([ROLE.ADMIN, ROLE.MEMBER, ROLE.GUEST], level="WORKSPACE")
def get(self, request, slug, asset_id):
# get the asset id
asset = FileAsset.objects.get(id=asset_id, workspace__slug=slug)
@@ -511,7 +516,7 @@ class ProjectAssetEndpoint(BaseAPIView):
@allow_permission([ROLE.ADMIN, ROLE.MEMBER, ROLE.GUEST])
def post(self, request, slug, project_id):
name = request.data.get("name")
name = sanitize_filename(request.data.get("name")) or "unnamed"
type = request.data.get("type", "image/jpeg")
size = int(request.data.get("size", settings.FILE_SIZE_LIMIT))
entity_type = request.data.get("entity_type", "")
@@ -752,12 +757,22 @@ class DuplicateAssetEndpoint(BaseAPIView):
return Response({"error": "Project not found"}, status=status.HTTP_404_NOT_FOUND)
storage = S3Storage(request=request)
original_asset = FileAsset.objects.filter(id=asset_id, is_uploaded=True).first()
# Scope the source asset lookup to workspaces the caller is a member of
user_workspace_ids = WorkspaceMember.objects.filter(
member=request.user,
is_active=True,
).values_list("workspace_id", flat=True)
original_asset = FileAsset.objects.filter(
id=asset_id,
is_uploaded=True,
workspace_id__in=user_workspace_ids,
).first()
if not original_asset:
return Response({"error": "Asset not found"}, status=status.HTTP_404_NOT_FOUND)
destination_key = f"{workspace.id}/{uuid.uuid4().hex}-{original_asset.attributes.get('name')}"
sanitized_name = sanitize_filename(original_asset.attributes.get("name")) or "unnamed"
destination_key = f"{workspace.id}/{uuid.uuid4().hex}-{sanitized_name}"
duplicated_asset = FileAsset.objects.create(
attributes={
"name": original_asset.attributes.get("name"),
+2 -1
View File
@@ -24,6 +24,7 @@ from plane.db.models import FileAsset, Workspace
from plane.bgtasks.issue_activities_task import issue_activity
from plane.app.permissions import allow_permission, ROLE
from plane.settings.storage import S3Storage
from plane.utils.path_validator import sanitize_filename
from plane.bgtasks.storage_metadata_task import get_asset_object_metadata
from plane.utils.host import base_host
@@ -97,7 +98,7 @@ class IssueAttachmentV2Endpoint(BaseAPIView):
@allow_permission([ROLE.ADMIN, ROLE.MEMBER, ROLE.GUEST])
def post(self, request, slug, project_id, issue_id):
name = request.data.get("name")
name = sanitize_filename(request.data.get("name")) or "unnamed"
type = request.data.get("type", False)
size = int(request.data.get("size", settings.FILE_SIZE_LIMIT))
+1 -1
View File
@@ -1118,7 +1118,7 @@ class IssueBulkUpdateDateEndpoint(BaseAPIView):
epoch = int(timezone.now().timestamp())
# Fetch all relevant issues in a single query
issues = list(Issue.objects.filter(id__in=issue_ids))
issues = list(Issue.objects.filter(id__in=issue_ids, workspace__slug=slug, project_id=project_id))
issues_dict = {str(issue.id): issue for issue in issues}
issues_to_update = []
+100 -69
View File
@@ -7,7 +7,7 @@ import json
# Django imports
from django.utils import timezone
from django.db.models import OuterRef, Func, F, Q, Value, UUIDField, Subquery
from django.db.models import OuterRef, Func, F, Q, Value, UUIDField, Subquery, Count, IntegerField
from django.utils.decorators import method_decorator
from django.views.decorators.gzip import gzip_page
from django.contrib.postgres.aggregates import ArrayAgg
@@ -22,7 +22,7 @@ from rest_framework import status
from .. import BaseAPIView
from plane.app.serializers import IssueSerializer
from plane.app.permissions import ProjectEntityPermission
from plane.db.models import Issue, IssueLink, FileAsset, CycleIssue
from plane.db.models import Issue, IssueLink, FileAsset, CycleIssue, IssueLabel, IssueAssignee, ModuleIssue
from plane.bgtasks.issue_activities_task import issue_activity
from plane.utils.timezone_converter import user_timezone_converter
from collections import defaultdict
@@ -37,70 +37,97 @@ class SubIssuesEndpoint(BaseAPIView):
def get(self, request, slug, project_id, issue_id):
sub_issues = (
Issue.issue_objects.filter(parent_id=issue_id, workspace__slug=slug)
.select_related("workspace", "project", "state", "parent")
.prefetch_related("assignees", "labels", "issue_module__module")
.annotate(
cycle_id=Subquery(
CycleIssue.objects.filter(issue=OuterRef("id"), deleted_at__isnull=True).values("cycle_id")[:1]
)
)
.annotate(
link_count=IssueLink.objects.filter(issue=OuterRef("id"))
.order_by()
.annotate(count=Func(F("id"), function="Count"))
.values("count")
)
.annotate(
attachment_count=FileAsset.objects.filter(
issue_id=OuterRef("id"),
entity_type=FileAsset.EntityTypeContext.ISSUE_ATTACHMENT,
link_count=Coalesce(
Subquery(
IssueLink.objects.filter(issue=OuterRef("id"))
.order_by()
.values("issue")
.annotate(count=Count("id"))
.values("count"),
output_field=IntegerField(),
),
0,
)
.order_by()
.annotate(count=Func(F("id"), function="Count"))
.values("count")
)
.annotate(
sub_issues_count=Issue.issue_objects.filter(parent=OuterRef("id"))
.order_by()
.annotate(count=Func(F("id"), function="Count"))
.values("count")
attachment_count=Coalesce(
Subquery(
FileAsset.objects.filter(
issue_id=OuterRef("id"),
entity_type=FileAsset.EntityTypeContext.ISSUE_ATTACHMENT,
)
.order_by()
.values("issue_id")
.annotate(count=Count("id"))
.values("count"),
output_field=IntegerField(),
),
0,
)
)
.annotate(
sub_issues_count=Coalesce(
Subquery(
Issue.issue_objects.filter(parent=OuterRef("id"))
.order_by()
.values("parent")
.annotate(count=Count("id"))
.values("count"),
output_field=IntegerField(),
),
0,
)
)
.annotate(
label_ids=Coalesce(
ArrayAgg(
"labels__id",
distinct=True,
filter=Q(~Q(labels__id__isnull=True) & Q(label_issue__deleted_at__isnull=True)),
Subquery(
IssueLabel.objects.filter(issue_id=OuterRef("id"), deleted_at__isnull=True)
.order_by()
.values("issue_id")
.annotate(arr=ArrayAgg("label_id", distinct=True))
.values("arr"),
output_field=ArrayField(UUIDField()),
),
Value([], output_field=ArrayField(UUIDField())),
),
assignee_ids=Coalesce(
ArrayAgg(
"assignees__id",
distinct=True,
filter=Q(
~Q(assignees__id__isnull=True)
& Q(assignees__member_project__is_active=True)
& Q(issue_assignee__deleted_at__isnull=True)
),
Subquery(
IssueAssignee.objects.filter(
issue_id=OuterRef("id"),
assignee__member_project__is_active=True,
deleted_at__isnull=True,
)
.order_by()
.values("issue_id")
.annotate(arr=ArrayAgg("assignee_id", distinct=True))
.values("arr"),
output_field=ArrayField(UUIDField()),
),
Value([], output_field=ArrayField(UUIDField())),
),
module_ids=Coalesce(
ArrayAgg(
"issue_module__module_id",
distinct=True,
filter=Q(
~Q(issue_module__module_id__isnull=True)
& Q(issue_module__module__archived_at__isnull=True)
& Q(issue_module__deleted_at__isnull=True)
),
Subquery(
ModuleIssue.objects.filter(
issue_id=OuterRef("id"),
module__archived_at__isnull=True,
deleted_at__isnull=True,
)
.order_by()
.values("issue_id")
.annotate(arr=ArrayAgg("module_id", distinct=True))
.values("arr"),
output_field=ArrayField(UUIDField()),
),
Value([], output_field=ArrayField(UUIDField())),
),
)
.annotate(state_group=F("state__group"))
.order_by("-created_at")
)
# Ordering
@@ -110,38 +137,42 @@ class SubIssuesEndpoint(BaseAPIView):
if order_by_param:
sub_issues, order_by_param = order_issue_queryset(sub_issues, order_by_param)
sub_issues = list(
sub_issues.values(
"id",
"name",
"state_id",
"sort_order",
"completed_at",
"estimate_point",
"priority",
"start_date",
"target_date",
"sequence_id",
"project_id",
"parent_id",
"cycle_id",
"module_ids",
"label_ids",
"assignee_ids",
"sub_issues_count",
"created_at",
"updated_at",
"created_by",
"updated_by",
"attachment_count",
"link_count",
"is_draft",
"archived_at",
"state_group",
)
)
# create's a dict with state group name with their respective issue id's
result = defaultdict(list)
for sub_issue in sub_issues:
result[sub_issue.state_group].append(str(sub_issue.id))
result[sub_issue["state_group"]].append(str(sub_issue["id"]))
sub_issues = sub_issues.values(
"id",
"name",
"state_id",
"sort_order",
"completed_at",
"estimate_point",
"priority",
"start_date",
"target_date",
"sequence_id",
"project_id",
"parent_id",
"cycle_id",
"module_ids",
"label_ids",
"assignee_ids",
"sub_issues_count",
"created_at",
"updated_at",
"created_by",
"updated_by",
"attachment_count",
"link_count",
"is_draft",
"archived_at",
)
datetime_fields = ["created_at", "updated_at"]
sub_issues = user_timezone_converter(sub_issues, datetime_fields, request.user.user_timezone)
# Grouping
+29 -14
View File
@@ -226,21 +226,36 @@ class ProjectMemberViewSet(BaseViewSet):
is_active=True,
)
if workspace_role in [5] and int(request.data.get("role", project_member.role)) in [15, 20]:
return Response(
{"error": "You cannot add a user with role higher than the workspace role"},
status=status.HTTP_400_BAD_REQUEST,
)
if "role" in request.data:
# Only Admins can modify roles
if requested_project_member.role < ROLE.ADMIN.value and not is_workspace_admin:
return Response(
{"error": "You do not have permission to update roles"},
status=status.HTTP_403_FORBIDDEN,
)
if (
"role" in request.data
and int(request.data.get("role", project_member.role)) > requested_project_member.role
and not is_workspace_admin
):
return Response(
{"error": "You cannot update a role that is higher than your own role"},
status=status.HTTP_400_BAD_REQUEST,
)
# Cannot modify a member whose role is equal to or higher than your own
if project_member.role >= requested_project_member.role and not is_workspace_admin:
return Response(
{"error": "You cannot update the role of a member with a role equal to or higher than your own"},
status=status.HTTP_403_FORBIDDEN,
)
new_role = int(request.data.get("role"))
# Cannot assign a role equal to or higher than your own
if new_role >= requested_project_member.role and not is_workspace_admin:
return Response(
{"error": "You cannot assign a role equal to or higher than your own"},
status=status.HTTP_403_FORBIDDEN,
)
# Cannot assign a role higher than the target's workspace role
if workspace_role in [5] and new_role in [15, 20]:
return Response(
{"error": "You cannot add a user with role higher than the workspace role"},
status=status.HTTP_400_BAD_REQUEST,
)
serializer = ProjectMemberSerializer(project_member, data=request.data, partial=True)
+8
View File
@@ -52,6 +52,7 @@ from plane.db.models import (
from plane.license.utils.instance_value import get_email_configuration
from plane.utils.email import generate_plain_text_from_html
from plane.utils.exception_logger import log_exception
from plane.utils.ip_address import validate_url
from plane.settings.mongo import MongoConnection
@@ -325,6 +326,13 @@ def webhook_send_task(
return
try:
# Re-validate the webhook URL at send time to prevent DNS-rebinding attacks
validate_url(
webhook.url,
allowed_ips=settings.WEBHOOK_ALLOWED_IPS,
allowed_hosts=settings.WEBHOOK_ALLOWED_HOSTS,
)
# Send the webhook event
response = requests.post(webhook.url, headers=headers, json=payload, timeout=30)
+52 -24
View File
@@ -13,7 +13,7 @@ from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin
import base64
import ipaddress
from typing import Dict, Any
from typing import Dict, Any, Tuple
from typing import Optional
from plane.db.models import IssueLink
from plane.utils.exception_logger import log_exception
@@ -66,6 +66,52 @@ def validate_url_ip(url: str) -> None:
MAX_REDIRECTS = 5
def safe_get(
url: str,
headers: Optional[Dict[str, str]] = None,
timeout: int = 1,
) -> Tuple[requests.Response, str]:
"""
Perform a GET request that validates every redirect hop against private IPs.
Prevents SSRF by ensuring no redirect lands on a private/internal address.
Args:
url: The URL to fetch
headers: Optional request headers
timeout: Request timeout in seconds
Returns:
A tuple of (final Response object, final URL after redirects)
Raises:
ValueError: If any URL in the redirect chain points to a private IP
requests.RequestException: On network errors
RuntimeError: If max redirects exceeded
"""
validate_url_ip(url)
current_url = url
response = requests.get(
current_url, headers=headers, timeout=timeout, allow_redirects=False
)
redirect_count = 0
while response.is_redirect:
if redirect_count >= MAX_REDIRECTS:
raise RuntimeError(f"Too many redirects for URL: {url}")
redirect_url = response.headers.get("Location")
if not redirect_url:
break
current_url = urljoin(current_url, redirect_url)
validate_url_ip(current_url)
redirect_count += 1
response = requests.get(
current_url, headers=headers, timeout=timeout, allow_redirects=False
)
return response, current_url
def crawl_work_item_link_title_and_favicon(url: str) -> Dict[str, Any]:
"""
Crawls a URL to extract the title and favicon.
@@ -86,26 +132,8 @@ def crawl_work_item_link_title_and_favicon(url: str) -> Dict[str, Any]:
title = None
final_url = url
validate_url_ip(final_url)
try:
# Manually follow redirects to validate each URL before requesting
redirect_count = 0
response = requests.get(final_url, headers=headers, timeout=1, allow_redirects=False)
while response.is_redirect and redirect_count < MAX_REDIRECTS:
redirect_url = response.headers.get("Location")
if not redirect_url:
break
# Resolve relative redirects against current URL
final_url = urljoin(final_url, redirect_url)
# Validate the redirect target BEFORE making the request
validate_url_ip(final_url)
redirect_count += 1
response = requests.get(final_url, headers=headers, timeout=1, allow_redirects=False)
if redirect_count >= MAX_REDIRECTS:
logger.warning(f"Too many redirects for URL: {url}")
response, final_url = safe_get(url, headers=headers)
soup = BeautifulSoup(response.content, "html.parser")
title_tag = soup.find("title")
@@ -113,8 +141,10 @@ def crawl_work_item_link_title_and_favicon(url: str) -> Dict[str, Any]:
except requests.RequestException as e:
logger.warning(f"Failed to fetch HTML for title: {str(e)}")
except (ValueError, RuntimeError) as e:
logger.warning(f"URL validation failed: {str(e)}")
# Fetch and encode favicon using final URL (after redirects)
# Fetch and encode favicon using final URL (after redirects) for correct relative href resolution
favicon_base64 = fetch_and_encode_favicon(headers, soup, final_url)
# Prepare result
@@ -204,9 +234,7 @@ def fetch_and_encode_favicon(
"favicon_base64": f"data:image/svg+xml;base64,{DEFAULT_FAVICON}",
}
validate_url_ip(favicon_url)
response = requests.get(favicon_url, headers=headers, timeout=1)
response, _ = safe_get(favicon_url, headers=headers)
# Get content type
content_type = response.headers.get("content-type", "image/x-icon")
@@ -0,0 +1,18 @@
# Generated by Django 4.2.28 on 2026-02-26 14:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('db', '0120_issueview_archived_at'),
]
operations = [
migrations.AlterField(
model_name='estimate',
name='type',
field=models.CharField(choices=[('categories', 'Categories'), ('points', 'Points')], default='categories', max_length=255),
),
]
+3
View File
@@ -11,10 +11,13 @@ from django.core.exceptions import ValidationError
from django.db import models
# Module import
from plane.utils.path_validator import sanitize_filename
from .base import BaseModel
def get_upload_path(instance, filename):
filename = sanitize_filename(filename) or uuid4().hex
if instance.workspace_id is not None:
return f"{instance.workspace.id}/{uuid4().hex}-{filename}"
return f"user-{uuid4().hex}-{filename}"
+5 -1
View File
@@ -10,11 +10,15 @@ from django.db.models import Q
# Module imports
from .project import ProjectBaseModel
class EstimateType(models.TextChoices):
CATEGORIES = "categories", "Categories"
POINTS = "points", "Points"
class Estimate(ProjectBaseModel):
name = models.CharField(max_length=255)
description = models.TextField(verbose_name="Estimate Description", blank=True)
type = models.CharField(max_length=255, default="categories")
type = models.CharField(max_length=255, choices=EstimateType.choices, default=EstimateType.CATEGORIES)
last_used = models.BooleanField(default=False)
def __str__(self):
+2
View File
@@ -17,6 +17,7 @@ from django import apps
# Module imports
from plane.utils.html_processor import strip_tags
from plane.utils.path_validator import sanitize_filename
from plane.db.mixins import SoftDeletionManager
from plane.utils.exception_logger import log_exception
from .project import ProjectBaseModel
@@ -376,6 +377,7 @@ class IssueLink(ProjectBaseModel):
def get_upload_path(instance, filename):
filename = sanitize_filename(filename) or uuid4().hex
return f"{instance.workspace.id}/{uuid4().hex}-{filename}"
@@ -45,7 +45,8 @@ class InstanceConfigurationEndpoint(BaseAPIView):
bulk_configurations = []
for configuration in configurations:
value = request.data.get(configuration.key, configuration.value)
raw_value = request.data.get(configuration.key, configuration.value)
value = "" if raw_value is None else str(raw_value).strip()
if configuration.is_encrypted:
configuration.value = encrypt_data(value)
else:
@@ -63,8 +63,6 @@ class InstanceEndpoint(BaseAPIView):
POSTHOG_HOST,
UNSPLASH_ACCESS_KEY,
LLM_API_KEY,
IS_INTERCOM_ENABLED,
INTERCOM_APP_ID,
) = get_configuration_value(
[
{
@@ -124,15 +122,6 @@ class InstanceEndpoint(BaseAPIView):
"key": "LLM_API_KEY",
"default": os.environ.get("LLM_API_KEY", ""),
},
# Intercom settings
{
"key": "IS_INTERCOM_ENABLED",
"default": os.environ.get("IS_INTERCOM_ENABLED", "1"),
},
{
"key": "INTERCOM_APP_ID",
"default": os.environ.get("INTERCOM_APP_ID", ""),
},
]
)
@@ -169,10 +158,6 @@ class InstanceEndpoint(BaseAPIView):
# is smtp configured
data["is_smtp_configured"] = bool(EMAIL_HOST)
# Intercom settings
data["is_intercom_enabled"] = IS_INTERCOM_ENABLED == "1"
data["intercom_app_id"] = INTERCOM_APP_ID
# Base URL
data["admin_base_url"] = settings.ADMIN_BASE_URL
data["space_base_url"] = settings.SPACE_BASE_URL
+40
View File
@@ -5,6 +5,8 @@
"""Global Settings"""
# Python imports
import ipaddress
import logging
import os
from urllib.parse import urlparse
from urllib.parse import urljoin
@@ -32,6 +34,44 @@ DEBUG = int(os.environ.get("DEBUG", "0"))
# Self-hosted mode
IS_SELF_MANAGED = True
# Webhook IP allowlist — comma-separated IPs or CIDR ranges that are allowed as
# webhook targets even if they resolve to private networks.
# Example: "10.0.0.0/8,192.168.1.0/24,172.16.0.5"
_webhook_allowed_ips_raw = os.environ.get("WEBHOOK_ALLOWED_IPS", "")
WEBHOOK_ALLOWED_IPS = []
_logger = logging.getLogger("plane")
for _cidr in _webhook_allowed_ips_raw.split(","):
_cidr = _cidr.strip()
if not _cidr:
continue
try:
WEBHOOK_ALLOWED_IPS.append(ipaddress.ip_network(_cidr, strict=False))
except ValueError:
_logger.warning("WEBHOOK_ALLOWED_IPS: skipping invalid entry %r", _cidr)
# Webhook hostname allowlist — comma-separated hostnames that bypass the
# private-IP SSRF check. Useful for trusted internal services whose IPs are
# dynamic in containerised deployments (e.g. docker-compose service DNS,
# kubernetes service hostnames).
# Example: "silo,silo.namespace.svc.cluster.local,internal-api.lan"
_webhook_allowed_hosts_raw = os.environ.get("WEBHOOK_ALLOWED_HOSTS", "")
WEBHOOK_ALLOWED_HOSTS = [
_host.strip().rstrip(".").lower()
for _host in _webhook_allowed_hosts_raw.split(",")
if _host.strip()
]
# Webhook disallowed domains — comma-separated hostnames. Webhooks targeting
# these domains or any of their subdomains are rejected (the request host is
# always appended at validation time as a loop-back guard). Empty by default
# for self-hosted deployments; set to e.g. "plane.so" to block specific domains.
_webhook_disallowed_domains_raw = os.environ.get("WEBHOOK_DISALLOWED_DOMAINS", "")
WEBHOOK_DISALLOWED_DOMAINS = [
_d.strip().rstrip(".").lower()
for _d in _webhook_disallowed_domains_raw.split(",")
if _d.strip()
]
# Allowed Hosts
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "*").split(",")
+2 -1
View File
@@ -18,6 +18,7 @@ from rest_framework.response import Response
from plane.bgtasks.storage_metadata_task import get_asset_object_metadata
from plane.db.models import DeployBoard, FileAsset
from plane.settings.storage import S3Storage
from plane.utils.path_validator import sanitize_filename
# Module imports
from .base import BaseAPIView
@@ -73,7 +74,7 @@ class EntityAssetEndpoint(BaseAPIView):
return Response({"error": "Project is not published"}, status=status.HTTP_404_NOT_FOUND)
# Get the asset
name = request.data.get("name")
name = sanitize_filename(request.data.get("name")) or "unnamed"
type = request.data.get("type", "image/jpeg")
size = int(request.data.get("size", settings.FILE_SIZE_LIMIT))
entity_type = request.data.get("entity_type", "")
@@ -0,0 +1,214 @@
# Copyright (c) 2023-present Plane Software, Inc. and contributors
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.
import ipaddress
import pytest
from unittest.mock import patch, MagicMock
from plane.bgtasks.work_item_link_task import safe_get, validate_url_ip
from plane.utils.ip_address import validate_url
def _make_response(status_code=200, headers=None, is_redirect=False, content=b""):
"""Create a mock requests.Response."""
resp = MagicMock()
resp.status_code = status_code
resp.is_redirect = is_redirect
resp.headers = headers or {}
resp.content = content
return resp
@pytest.mark.unit
class TestValidateUrlIp:
"""Test validate_url_ip blocks private/internal IPs."""
def test_rejects_private_ip(self):
with patch("plane.bgtasks.work_item_link_task.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("192.168.1.1", 0))]
with pytest.raises(ValueError, match="private/internal"):
validate_url_ip("http://example.com")
def test_rejects_loopback(self):
with patch("plane.bgtasks.work_item_link_task.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("127.0.0.1", 0))]
with pytest.raises(ValueError, match="private/internal"):
validate_url_ip("http://example.com")
def test_rejects_non_http_scheme(self):
with pytest.raises(ValueError, match="Only HTTP and HTTPS"):
validate_url_ip("file:///etc/passwd")
def test_allows_public_ip(self):
with patch("plane.bgtasks.work_item_link_task.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("93.184.216.34", 0))]
validate_url_ip("https://example.com") # Should not raise
@pytest.mark.unit
class TestValidateUrlAllowlist:
"""Test validate_url allowlist permits specific private IPs."""
def test_allowlist_permits_private_ip(self):
allowed = [ipaddress.ip_network("192.168.1.0/24")]
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("192.168.1.50", 0))]
validate_url("http://example.com", allowed_ips=allowed) # Should not raise
def test_allowlist_does_not_permit_other_private_ip(self):
allowed = [ipaddress.ip_network("192.168.1.0/24")]
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("10.0.0.1", 0))]
with pytest.raises(ValueError, match="private/internal"):
validate_url("http://example.com", allowed_ips=allowed)
def test_allowlist_permits_loopback_when_explicitly_allowed(self):
allowed = [ipaddress.ip_network("127.0.0.0/8")]
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("127.0.0.1", 0))]
validate_url("http://example.com", allowed_ips=allowed) # Should not raise
def test_allowlist_permits_matching_ipv4_with_mixed_version_networks(self):
allowed = [
ipaddress.ip_network("2001:db8::/32"),
ipaddress.ip_network("192.168.1.0/24"),
]
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("192.168.1.50", 0))]
validate_url("http://example.com", allowed_ips=allowed) # Should not raise
def test_allowlist_blocks_non_matching_ipv4_with_mixed_version_networks(self):
allowed = [
ipaddress.ip_network("2001:db8::/32"),
ipaddress.ip_network("192.168.1.0/24"),
]
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("10.0.0.1", 0))]
with pytest.raises(ValueError, match="private/internal"):
validate_url("http://example.com", allowed_ips=allowed)
def test_allowed_hosts_bypasses_private_ip_check(self):
"""Hostnames in WEBHOOK_ALLOWED_HOSTS skip IP-based blocking — used for
trusted internal services (e.g. Silo) whose IPs are dynamic in
containerised deployments."""
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("172.18.0.5", 0))]
validate_url("http://silo:3000/hook", allowed_hosts=["silo"]) # Should not raise
def test_allowed_hosts_matches_case_insensitively(self):
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("10.0.0.1", 0))]
validate_url(
"http://Silo.Namespace.Svc.Cluster.Local/x",
allowed_hosts=["silo.namespace.svc.cluster.local"],
) # Should not raise
def test_allowed_hosts_skips_dns_lookup(self):
"""When the hostname is explicitly trusted we shouldn't even resolve it —
protects against operators who allowlist a name that isn't resolvable
from the API container."""
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
validate_url("http://silo/hook", allowed_hosts=["silo"])
mock_dns.assert_not_called()
def test_allowed_hosts_requires_exact_match(self):
"""Subdomains of an allowed host must NOT bypass — a hostile
``attacker.silo.internal`` should still be blocked when only
``silo.internal`` is allowed."""
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("192.168.1.1", 0))]
with pytest.raises(ValueError, match="private/internal"):
validate_url(
"http://attacker.silo.internal/x",
allowed_hosts=["silo.internal"],
)
def test_allowed_hosts_empty_does_not_bypass(self):
with patch("plane.utils.ip_address.socket.getaddrinfo") as mock_dns:
mock_dns.return_value = [(None, None, None, None, ("10.0.0.1", 0))]
with pytest.raises(ValueError, match="private/internal"):
validate_url("http://silo/hook", allowed_hosts=[])
@pytest.mark.unit
class TestSafeGet:
"""Test safe_get follows redirects safely and blocks SSRF."""
@patch("plane.bgtasks.work_item_link_task.requests.get")
@patch("plane.bgtasks.work_item_link_task.validate_url_ip")
def test_returns_response_for_non_redirect(self, mock_validate, mock_get):
final_resp = _make_response(status_code=200, content=b"OK")
mock_get.return_value = final_resp
response, final_url = safe_get("https://example.com")
assert response is final_resp
assert final_url == "https://example.com"
mock_validate.assert_called_once_with("https://example.com")
@patch("plane.bgtasks.work_item_link_task.requests.get")
@patch("plane.bgtasks.work_item_link_task.validate_url_ip")
def test_follows_redirect_and_validates_each_hop(self, mock_validate, mock_get):
redirect_resp = _make_response(
status_code=301,
is_redirect=True,
headers={"Location": "https://other.com/page"},
)
final_resp = _make_response(status_code=200, content=b"OK")
mock_get.side_effect = [redirect_resp, final_resp]
response, final_url = safe_get("https://example.com")
assert response is final_resp
assert final_url == "https://other.com/page"
# Should validate both the initial URL and the redirect target
assert mock_validate.call_count == 2
mock_validate.assert_any_call("https://example.com")
mock_validate.assert_any_call("https://other.com/page")
@patch("plane.bgtasks.work_item_link_task.requests.get")
@patch("plane.bgtasks.work_item_link_task.validate_url_ip")
def test_blocks_redirect_to_private_ip(self, mock_validate, mock_get):
redirect_resp = _make_response(
status_code=302,
is_redirect=True,
headers={"Location": "http://192.168.1.1:8080"},
)
mock_get.return_value = redirect_resp
# First call (initial URL) succeeds, second call (redirect target) fails
mock_validate.side_effect = [None, ValueError("Access to private/internal networks is not allowed")]
with pytest.raises(ValueError, match="private/internal"):
safe_get("https://evil.com/redirect")
@patch("plane.bgtasks.work_item_link_task.requests.get")
@patch("plane.bgtasks.work_item_link_task.validate_url_ip")
def test_raises_on_too_many_redirects(self, mock_validate, mock_get):
redirect_resp = _make_response(
status_code=302,
is_redirect=True,
headers={"Location": "https://example.com/loop"},
)
mock_get.return_value = redirect_resp
with pytest.raises(RuntimeError, match="Too many redirects"):
safe_get("https://example.com/start")
@patch("plane.bgtasks.work_item_link_task.requests.get")
@patch("plane.bgtasks.work_item_link_task.validate_url_ip")
def test_succeeds_at_exact_max_redirects(self, mock_validate, mock_get):
"""After exactly MAX_REDIRECTS hops, if the final response is 200, it should succeed."""
redirect_resp = _make_response(
status_code=302,
is_redirect=True,
headers={"Location": "https://example.com/next"},
)
final_resp = _make_response(status_code=200, content=b"OK")
# 5 redirects then a 200
mock_get.side_effect = [redirect_resp] * 5 + [final_resp]
response, final_url = safe_get("https://example.com/start")
assert response is final_resp
assert not response.is_redirect
+26
View File
@@ -22,6 +22,23 @@ from django.utils import timezone
# Module imports
from plane.db.models import Issue, Project
VALID_ANALYTICS_FIELDS = [
"state_id",
"state__group",
"labels__id",
"assignees__id",
"estimate_point__value",
"issue_cycle__cycle_id",
"issue_module__module_id",
"priority",
"start_date",
"target_date",
"created_at",
"completed_at",
]
VALID_YAXIS = ["issue_count", "estimate"]
def annotate_with_monthly_dimension(queryset, field_name, attribute):
# Get the year and the months
@@ -34,6 +51,8 @@ def annotate_with_monthly_dimension(queryset, field_name, attribute):
def extract_axis(queryset, x_axis):
if x_axis not in VALID_ANALYTICS_FIELDS:
raise ValueError(f"Invalid x_axis value: {x_axis}")
# Format the dimension when the axis is in date
if x_axis in ["created_at", "start_date", "target_date", "completed_at"]:
queryset = annotate_with_monthly_dimension(queryset, x_axis, "dimension")
@@ -52,6 +71,13 @@ def sort_data(data, temp_axis):
def build_graph_plot(queryset, x_axis, y_axis, segment=None):
if x_axis not in VALID_ANALYTICS_FIELDS:
raise ValueError(f"Invalid x_axis value: {x_axis}")
if y_axis not in VALID_YAXIS:
raise ValueError(f"Invalid y_axis value: {y_axis}")
if segment and segment not in VALID_ANALYTICS_FIELDS:
raise ValueError(f"Invalid segment value: {segment}")
# temp x_axis
temp_axis = x_axis
# Extract the x_axis and queryset
@@ -232,21 +232,6 @@ unsplash_config_variables = [
},
]
intercom_config_variables = [
{
"key": "IS_INTERCOM_ENABLED",
"value": os.environ.get("IS_INTERCOM_ENABLED", "1"),
"category": "INTERCOM",
"is_encrypted": False,
},
{
"key": "INTERCOM_APP_ID",
"value": os.environ.get("INTERCOM_APP_ID", ""),
"category": "INTERCOM",
"is_encrypted": False,
},
]
core_config_variables = [
*authentication_config_variables,
*workspace_management_config_variables,
@@ -257,5 +242,4 @@ core_config_variables = [
*smtp_config_variables,
*llm_config_variables,
*unsplash_config_variables,
*intercom_config_variables,
]
+57
View File
@@ -2,6 +2,63 @@
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.
# Python imports
import ipaddress
import socket
from urllib.parse import urlparse
def validate_url(url, allowed_ips=None, allowed_hosts=None):
"""
Validate that a URL doesn't resolve to a private/internal IP address (SSRF protection).
Args:
url: The URL to validate.
allowed_ips: Optional list of ipaddress.ip_network objects. IPs falling within
these networks are permitted even if they are private/loopback/reserved.
Typically sourced from the WEBHOOK_ALLOWED_IPS setting.
allowed_hosts: Optional iterable of hostnames that bypass IP-based blocking
(exact, case-insensitive match against the URL hostname).
Typically sourced from the WEBHOOK_ALLOWED_HOSTS setting and
used for trusted internal services (e.g. Silo) whose IPs are
dynamic in containerised deployments.
Raises:
ValueError: If the URL is invalid or resolves to a blocked IP.
"""
parsed = urlparse(url)
hostname = parsed.hostname
if not hostname:
raise ValueError("Invalid URL: No hostname found")
if parsed.scheme not in ("http", "https"):
raise ValueError("Invalid URL scheme. Only HTTP and HTTPS are allowed")
normalized_host = hostname.rstrip(".").lower()
if allowed_hosts and normalized_host in {
(h or "").rstrip(".").lower() for h in allowed_hosts if h
}:
return
try:
addr_info = socket.getaddrinfo(hostname, None)
except socket.gaierror:
raise ValueError("Hostname could not be resolved")
if not addr_info:
raise ValueError("No IP addresses found for the hostname")
for addr in addr_info:
ip = ipaddress.ip_address(addr[4][0])
if ip.is_private or ip.is_loopback or ip.is_reserved or ip.is_link_local:
if allowed_ips and any(
network.version == ip.version and ip in network for network in allowed_ips
):
continue
raise ValueError("Access to private/internal networks is not allowed")
def get_client_ip(request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
+20
View File
@@ -47,6 +47,7 @@ from .parameters import (
CYCLE_VIEW_PARAMETER,
FIELDS_PARAMETER,
EXPAND_PARAMETER,
ESTIMATE_ID_PARAMETER,
)
# Responses
@@ -126,6 +127,10 @@ from .examples import (
STATE_UPDATE_EXAMPLE,
INTAKE_ISSUE_CREATE_EXAMPLE,
INTAKE_ISSUE_UPDATE_EXAMPLE,
ESTIMATE_CREATE_EXAMPLE,
ESTIMATE_UPDATE_EXAMPLE,
ESTIMATE_POINT_CREATE_EXAMPLE,
ESTIMATE_POINT_UPDATE_EXAMPLE,
# Response Examples
CYCLE_EXAMPLE,
TRANSFER_CYCLE_ISSUE_SUCCESS_EXAMPLE,
@@ -145,6 +150,8 @@ from .examples import (
PROJECT_MEMBER_EXAMPLE,
CYCLE_ISSUE_EXAMPLE,
STICKY_EXAMPLE,
ESTIMATE_EXAMPLE,
ESTIMATE_POINT_EXAMPLE,
)
# Helper decorators
@@ -157,6 +164,7 @@ from .decorators import (
user_docs,
cycle_docs,
work_item_docs,
work_item_relation_docs,
label_docs,
issue_link_docs,
issue_comment_docs,
@@ -165,6 +173,8 @@ from .decorators import (
module_docs,
module_issue_docs,
state_docs,
estimate_docs,
estimate_point_docs,
)
# Schema processing hooks
@@ -206,6 +216,7 @@ __all__ = [
"CYCLE_VIEW_PARAMETER",
"FIELDS_PARAMETER",
"EXPAND_PARAMETER",
"ESTIMATE_ID_PARAMETER",
# Responses
"UNAUTHORIZED_RESPONSE",
"FORBIDDEN_RESPONSE",
@@ -279,6 +290,10 @@ __all__ = [
"STATE_UPDATE_EXAMPLE",
"INTAKE_ISSUE_CREATE_EXAMPLE",
"INTAKE_ISSUE_UPDATE_EXAMPLE",
"ESTIMATE_CREATE_EXAMPLE",
"ESTIMATE_UPDATE_EXAMPLE",
"ESTIMATE_POINT_CREATE_EXAMPLE",
"ESTIMATE_POINT_UPDATE_EXAMPLE",
# Response Examples
"CYCLE_EXAMPLE",
"TRANSFER_CYCLE_ISSUE_SUCCESS_EXAMPLE",
@@ -298,6 +313,8 @@ __all__ = [
"PROJECT_MEMBER_EXAMPLE",
"CYCLE_ISSUE_EXAMPLE",
"STICKY_EXAMPLE",
"ESTIMATE_EXAMPLE",
"ESTIMATE_POINT_EXAMPLE",
# Decorators
"workspace_docs",
"project_docs",
@@ -307,6 +324,7 @@ __all__ = [
"user_docs",
"cycle_docs",
"work_item_docs",
"work_item_relation_docs",
"label_docs",
"issue_link_docs",
"issue_comment_docs",
@@ -315,6 +333,8 @@ __all__ = [
"module_docs",
"module_issue_docs",
"state_docs",
"estimate_docs",
"estimate_point_docs",
# Hooks
"preprocess_filter_api_v1_paths",
"generate_operation_summary",
@@ -223,6 +223,21 @@ def issue_attachment_docs(**kwargs):
return extend_schema(**_merge_schema_options(defaults, kwargs))
def work_item_relation_docs(**kwargs):
"""Decorator for work item relation endpoints"""
defaults = {
"tags": ["Work Item Relations"],
"parameters": [WORKSPACE_SLUG_PARAMETER, PROJECT_ID_PARAMETER],
"responses": {
401: UNAUTHORIZED_RESPONSE,
403: FORBIDDEN_RESPONSE,
404: NOT_FOUND_RESPONSE,
},
}
return extend_schema(**_merge_schema_options(defaults, kwargs))
def module_docs(**kwargs):
"""Decorator for module management endpoints"""
defaults = {
@@ -282,3 +297,29 @@ def sticky_docs(**kwargs):
}
return extend_schema(**_merge_schema_options(defaults, kwargs))
def estimate_docs(**kwargs):
"""Decorator for estimate-related endpoints"""
defaults = {
"tags": ["Estimates"],
"parameters": [WORKSPACE_SLUG_PARAMETER, PROJECT_ID_PARAMETER],
"responses": {
401: UNAUTHORIZED_RESPONSE,
403: FORBIDDEN_RESPONSE,
404: NOT_FOUND_RESPONSE,
},
}
return extend_schema(**_merge_schema_options(defaults, kwargs))
def estimate_point_docs(**kwargs):
"""Decorator for estimate point-related endpoints"""
defaults = {
"tags": ["Estimate Points"],
"parameters": [WORKSPACE_SLUG_PARAMETER, PROJECT_ID_PARAMETER],
"responses": {
401: UNAUTHORIZED_RESPONSE,
403: FORBIDDEN_RESPONSE,
404: NOT_FOUND_RESPONSE,
},
}
return extend_schema(**_merge_schema_options(defaults, kwargs))
+83
View File
@@ -686,6 +686,69 @@ STICKY_EXAMPLE = OpenApiExample(
},
)
# Estimate Examples
ESTIMATE_EXAMPLE = OpenApiExample(
name="Estimate",
value={
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Estimate 1",
"description": "Estimate 1 description",
},
description="Example response for an estimate",
)
ESTIMATE_POINT_EXAMPLE = OpenApiExample(
name="EstimatePoint",
value={
"id": "550e8400-e29b-41d4-a716-446655440000",
"estimate": "550e8400-e29b-41d4-a716-446655440001",
"key": 1,
"value": "1",
},
description="Example response for an estimate point",
)
ESTIMATE_CREATE_EXAMPLE = OpenApiExample(
name="EstimateCreateSerializer",
value={
"name": "Estimate 1",
"description": "Estimate 1 description",
},
description="Example request for creating an estimate",
)
ESTIMATE_UPDATE_EXAMPLE = OpenApiExample(
name="EstimateUpdateSerializer",
value={
"name": "Estimate 1",
"description": "Estimate 1 description",
},
description="Example request for updating an estimate",
)
# Estimate Point Examples
ESTIMATE_POINT_CREATE_EXAMPLE = OpenApiExample(
name="EstimatePointCreateSerializer",
value=[
{
"value": "1",
"description": "Estimate Point 1 description",
},
{
"value": "2",
"description": "Estimate Point 2 description",
},
],
description="Example request for creating an estimate point",
)
ESTIMATE_POINT_UPDATE_EXAMPLE = OpenApiExample(
name="EstimatePointUpdateSerializer",
value={
"value": "1",
"description": "Estimate Point 1 description",
},
description="Example request for updating an estimate point",
)
# Sample data for different entity types
SAMPLE_ISSUE = {
"id": "550e8400-e29b-41d4-a716-446655440000",
@@ -801,6 +864,24 @@ SAMPLE_STICKY = {
"created_at": "2024-01-01T10:30:00Z",
}
SAMPLE_ESTIMATE = {
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Estimate 1",
"description": "Estimate 1 description",
"type": "categories",
"last_used": False,
"created_at": "2024-01-01T10:30:00Z",
}
SAMPLE_ESTIMATE_POINT = {
"id": "550e8400-e29b-41d4-a716-446655440000",
"estimate": "550e8400-e29b-41d4-a716-446655440001",
"key": 1,
"value": "1",
"description": "Estimate Point 1 description",
"created_at": "2024-01-01T10:30:00Z",
}
# Mapping of schema types to sample data
SCHEMA_EXAMPLES = {
"Issue": SAMPLE_ISSUE,
@@ -816,6 +897,8 @@ SCHEMA_EXAMPLES = {
"Intake": SAMPLE_INTAKE,
"CycleIssue": SAMPLE_CYCLE_ISSUE,
"Sticky": SAMPLE_STICKY,
"Estimate": SAMPLE_ESTIMATE,
"EstimatePoint": SAMPLE_ESTIMATE_POINT,
}
@@ -495,3 +495,11 @@ EXPAND_PARAMETER = OpenApiParameter(
),
],
)
ESTIMATE_ID_PARAMETER = OpenApiParameter(
name="estimate_id",
description="Estimate ID",
required=True,
type=OpenApiTypes.UUID,
location=OpenApiParameter.PATH,
)
+41
View File
@@ -7,9 +7,50 @@ from django.utils.http import url_has_allowed_host_and_scheme
from django.conf import settings
# Python imports
import os
from urllib.parse import urlparse
def sanitize_filename(filename):
"""
Sanitize a filename to prevent path traversal attacks.
Strips directory components, path traversal sequences, and null bytes
from user-supplied filenames used in upload paths and S3 object keys.
Returns None for empty/missing input so callers can still validate
that a filename was provided.
"""
if not filename or not isinstance(filename, str):
return None
# Strip null bytes
filename = filename.replace("\x00", "")
# Normalize backslashes so os.path.basename handles Windows-style paths on POSIX
filename = filename.replace("\\", "/")
# Take only the basename to remove any directory components
filename = os.path.basename(filename)
# Remove any remaining path traversal sequences
filename = filename.replace("..", "")
# Strip whitespace before removing leading dots so " .env" is caught
filename = filename.strip()
# Remove leading dots (hidden files)
filename = filename.lstrip(".")
# Strip any remaining whitespace
filename = filename.strip()
if not filename:
return None
return filename
def _contains_suspicious_patterns(path: str) -> bool:
"""
Check for suspicious patterns that might indicate malicious intent.
+3 -3
View File
@@ -1,7 +1,7 @@
# base requirements
# django
Django==4.2.29
Django==4.2.30
# rest framework
djangorestframework==3.15.2
# postgres
@@ -51,9 +51,9 @@ beautifulsoup4==4.12.3
# analytics
posthog==3.5.0
# crypto
cryptography==46.0.5
cryptography==46.0.7
# html validator
lxml==6.0.0
lxml==6.1.0
# s3
boto3==1.34.96
# password validator
+2 -2
View File
@@ -1,6 +1,6 @@
-r base.txt
# test framework
pytest==9.0.2
pytest==9.0.3
pytest-django==4.5.2
pytest-cov==4.1.0
pytest-xdist==3.3.1
@@ -9,4 +9,4 @@ factory-boy==3.3.0
freezegun==1.2.2
coverage==7.2.7
httpx==0.24.1
requests==2.32.4
requests==2.33.0
@@ -261,7 +261,7 @@
<td height="5" width="8" style=" font-size: 5px; line-height: 5px; " > ­ </td>
</tr>
<tr>
<td class="r26-i" style=" font-size: 0px; line-height: 0px; " > <a href="https://twitter.com/planepowers" target="_blank" style=" color: #0092ff; text-decoration: underline; " > <img src="{{ current_site }}/static/logos/twitter_32px.png" width="32" border="0" class="" style=" display: block; width: 100%; " /></a> </td>
<td class="r26-i" style=" font-size: 0px; line-height: 0px; " > <a href="https://x.com/planepowers" target="_blank" style=" color: #0092ff; text-decoration: underline; " > <img src="{{ current_site }}/static/logos/twitter_32px.png" width="32" border="0" class="" style=" display: block; width: 100%; " /></a> </td>
<td class="nl2go-responsive-hide" width="8" style=" font-size: 0px; line-height: 1px; " > ­ </td>
</tr>
<tr class="nl2go-responsive-hide" >
@@ -233,7 +233,7 @@
<td>
<div style="font-size: 0.8rem; color: #1c2024">
This email was sent to <a href="mailto:{{receiver.email}}" style="color: #3a5bc7; font-weight: 500; text-decoration: none" >{{ receiver.email }}.</a > If you'd rather not receive this kind of email, <a href="{{ issue_url }}" style="color: #3a5bc7; text-decoration: none" >you can unsubscribe to the {{entity_type}}</a > or <a href="{{ user_preference }}" style="color: #3a5bc7; text-decoration: none" >manage your email preferences</a >. <!-- Github | LinkedIn | Twitter -->
<div style="margin-top: 60px; float: right"> <a href="https://github.com/makeplane" target="_blank" style="margin-left: 10px; text-decoration: none" > <img src="https://creative-assets.mailinblue.com/editor/social-icons/rounded_colored/github_32px.png" width="25" height="25" border="0" style="display: inline-block" /> </a> <a href="https://www.linkedin.com/company/planepowers/" target="_blank" style="margin-left: 10px; text-decoration: none" > <img src="https://creative-assets.mailinblue.com/editor/social-icons/rounded_colored/linkedin_32px.png" width="25" height="25" border="0" style="display: inline-block" /> </a> <a href="https://twitter.com/planepowers" target="_blank" style="margin-left: 10px; text-decoration: none" > <img src="https://creative-assets.mailinblue.com/editor/social-icons/rounded_colored/twitter_32px.png" width="25" height="25" border="0" style="display: inline-block" /> </a> </div>
<div style="margin-top: 60px; float: right"> <a href="https://github.com/makeplane" target="_blank" style="margin-left: 10px; text-decoration: none" > <img src="https://creative-assets.mailinblue.com/editor/social-icons/rounded_colored/github_32px.png" width="25" height="25" border="0" style="display: inline-block" /> </a> <a href="https://www.linkedin.com/company/planepowers/" target="_blank" style="margin-left: 10px; text-decoration: none" > <img src="https://creative-assets.mailinblue.com/editor/social-icons/rounded_colored/linkedin_32px.png" width="25" height="25" border="0" style="display: inline-block" /> </a> <a href="https://x.com/planepowers" target="_blank" style="margin-left: 10px; text-decoration: none" > <img src="https://creative-assets.mailinblue.com/editor/social-icons/rounded_colored/twitter_32px.png" width="25" height="25" border="0" style="display: inline-block" /> </a> </div>
</div>
</td>
</tr>
@@ -155,7 +155,7 @@
<td class="nl2go-responsive-hide" width="2" style=" font-size: 0px; line-height: 1px; background-color: #efefef; " > ­ </td>
<td align="left" valign="top" class="r21-i nl2go-default-textstyle" style=" color: #3b3f44; font-family: georgia, serif; font-size: 16px; word-break: break-word; line-height: 1.5; padding-bottom: 5px; padding-left: 5px; padding-right: 5px; padding-top: 5px; text-align: left; " >
<div>
<p style="margin: 0"> <span style="font-size: 13px" >Despite our popularity, we are humbly early-stage. We are shipping fast, so please reach out to us with feature requests, major and minor nits, and anything else you find missing. We read every </span ><a href="https://forum.plane.so" title="Plane Forum" target="_blank" style=" color: #006399; text-decoration: underline; " ><span style="font-size: 13px" >message</span ></a ><span style="font-size: 13px" >, </span ><a href="http://twitter.com/planepowers" title="@planepowers" target="_blank" style=" color: #006399; text-decoration: underline; " ><span style="font-size: 13px" >tweet</span ></a ><span style="font-size: 13px" >, and </span ><a href="https://github.com/makeplane/plane/issues" title="Plane's GitHub conversations" target="_blank" style=" color: #006399; text-decoration: underline; " ><span style="font-size: 13px" >conversation</span ></a ><span style="font-size: 13px" > and update </span ><a href="https://plane.sh/plane/0b170a1c-0e55-47cb-9307-ea49a05672b5?board=kanban" title="Plane's roadmap" target="_blank" style=" color: #006399; text-decoration: underline; " ><span style="font-size: 13px" >our public roadmap</span ></a ><span style="font-size: 13px" >.</span > </p>
<p style="margin: 0"> <span style="font-size: 13px" >Despite our popularity, we are humbly early-stage. We are shipping fast, so please reach out to us with feature requests, major and minor nits, and anything else you find missing. We read every </span ><a href="https://forum.plane.so" title="Plane Forum" target="_blank" style=" color: #006399; text-decoration: underline; " ><span style="font-size: 13px" >message</span ></a ><span style="font-size: 13px" >, </span ><a href="https://x.com/planepowers" title="@planepowers" target="_blank" style=" color: #006399; text-decoration: underline; " ><span style="font-size: 13px" >tweet</span ></a ><span style="font-size: 13px" >, and </span ><a href="https://github.com/makeplane/plane/issues" title="Plane's GitHub conversations" target="_blank" style=" color: #006399; text-decoration: underline; " ><span style="font-size: 13px" >conversation</span ></a ><span style="font-size: 13px" > and update </span ><a href="https://plane.sh/plane/0b170a1c-0e55-47cb-9307-ea49a05672b5?board=kanban" title="Plane's roadmap" target="_blank" style=" color: #006399; text-decoration: underline; " ><span style="font-size: 13px" >our public roadmap</span ></a ><span style="font-size: 13px" >.</span > </p>
</div>
</td>
<td class="nl2go-responsive-hide" width="2" style=" font-size: 0px; line-height: 1px; background-color: #efefef; " > ­ </td>
@@ -220,7 +220,7 @@
<th width="40" class="r25-c mobshow resp-table" style=" font-weight: normal; " >
<table cellspacing="0" cellpadding="0" border="0" role="presentation" width="100%" class="r26-o" style=" table-layout: fixed; width: 100%; " >
<tr>
<td class="r18-i" style=" font-size: 0px; line-height: 0px; padding-bottom: 5px; padding-top: 5px; " > <a href="https://twitter.com/planepowers" target="_blank" style=" color: #006399; text-decoration: underline; " > <img src="https://creative-assets.mailinblue.com/editor/social-icons/rounded_colored/twitter_32px.png" width="32" border="0" style=" display: block; width: 100%; " /></a> </td>
<td class="r18-i" style=" font-size: 0px; line-height: 0px; padding-bottom: 5px; padding-top: 5px; " > <a href="https://x.com/planepowers" target="_blank" style=" color: #006399; text-decoration: underline; " > <img src="https://creative-assets.mailinblue.com/editor/social-icons/rounded_colored/twitter_32px.png" width="32" border="0" style=" display: block; width: 100%; " /></a> </td>
<td class="nl2go-responsive-hide" width="8" style=" font-size: 0px; line-height: 1px; " > ­ </td>
</tr>
</table>
@@ -831,7 +831,7 @@
"
>
<a
href="https://twitter.com/planepowers"
href="https://x.com/planepowers"
target="_blank"
style="
color: #006399;
@@ -973,7 +973,7 @@
><span style="font-size: 13px"
>, </span
><a
href="http://twitter.com/planepowers"
href="https://x.com/planepowers"
title="@planepowers"
target="_blank"
style="
@@ -1344,7 +1344,7 @@
"
>
<a
href="https://twitter.com/planepowers"
href="https://x.com/planepowers"
target="_blank"
style="
color: #006399;
@@ -974,7 +974,7 @@
><span style="font-size: 13px"
>, </span
><a
href="http://twitter.com/planepowers"
href="https://x.com/planepowers"
title="@planepowers"
target="_blank"
style="
@@ -1345,7 +1345,7 @@
"
>
<a
href="https://twitter.com/planepowers"
href="https://x.com/planepowers"
target="_blank"
style="
color: #006399;
+2 -2
View File
@@ -3,7 +3,7 @@ FROM node:22-alpine AS base
# Setup pnpm package manager with corepack and configure global bin directory for caching
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV PATH="$PNPM_HOME:$PNPM_HOME/bin:$PATH"
RUN corepack enable
# *****************************************************************************
@@ -15,7 +15,7 @@ RUN apk update
RUN apk add --no-cache libc6-compat
# Set working directory
WORKDIR /app
ARG TURBO_VERSION=2.8.12
ARG TURBO_VERSION=2.9.4
RUN corepack enable pnpm && pnpm add -g turbo@${TURBO_VERSION}
COPY . .
RUN turbo prune --scope=live --docker
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "live",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"description": "A realtime collaborative server powers Plane's rich text editor",
"license": "AGPL-3.0",
@@ -14,7 +14,7 @@
},
"scripts": {
"build": "tsc --noEmit && tsdown",
"dev": "tsdown --watch --onSuccess \"node --env-file=.env .\"",
"dev": "tsdown --watch --no-clean --onSuccess \"node --env-file=.env .\"",
"start": "node --env-file=.env .",
"test": "vitest run",
"test:watch": "vitest",
@@ -27,7 +27,6 @@
"clean": "rm -rf .turbo && rm -rf .next && rm -rf node_modules && rm -rf dist"
},
"dependencies": {
"@dotenvx/dotenvx": "catalog:",
"@effect/platform": "^0.94.0",
"@effect/platform-node": "^0.104.0",
"@fontsource/inter": "5.2.8",
@@ -47,6 +46,7 @@
"axios": "catalog:",
"compression": "1.8.1",
"cors": "^2.8.5",
"dotenv": "catalog:",
"effect": "3.20.0",
"express": "catalog:",
"express-ws": "^5.0.2",
+1 -1
View File
@@ -4,7 +4,7 @@
* See the LICENSE file for details.
*/
import * as dotenv from "@dotenvx/dotenvx";
import * as dotenv from "dotenv";
import { z } from "zod";
dotenv.config();
+2 -2
View File
@@ -4,7 +4,7 @@ WORKDIR /app
ENV TURBO_TELEMETRY_DISABLED=1
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV PATH="$PNPM_HOME:$PNPM_HOME/bin:$PATH"
ENV CI=1
RUN corepack enable pnpm
@@ -13,7 +13,7 @@ RUN corepack enable pnpm
FROM base AS builder
RUN pnpm add -g turbo@2.8.12
RUN pnpm add -g turbo@2.9.4
COPY . .
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "space",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"license": "AGPL-3.0",
"type": "module",
@@ -53,7 +53,6 @@
"uuid": "catalog:"
},
"devDependencies": {
"@dotenvx/dotenvx": "catalog:",
"@plane/tailwind-config": "workspace:*",
"@plane/typescript-config": "workspace:*",
"@react-router/dev": "catalog:",
@@ -62,6 +61,7 @@
"@types/node": "catalog:",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"dotenv": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vite-tsconfig-paths": "^5.1.4"
+1 -1
View File
@@ -1,5 +1,5 @@
import path from "node:path";
import * as dotenv from "@dotenvx/dotenvx";
import * as dotenv from "dotenv";
import { reactRouter } from "@react-router/dev/vite";
import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
+2 -2
View File
@@ -3,7 +3,7 @@ FROM node:22-alpine AS base
# Setup pnpm package manager with corepack and configure global bin directory for caching
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV PATH="$PNPM_HOME:$PNPM_HOME/bin:$PATH"
RUN corepack enable
# *****************************************************************************
@@ -14,7 +14,7 @@ RUN apk add --no-cache libc6-compat
# Set working directory
WORKDIR /app
ARG TURBO_VERSION=2.8.12
ARG TURBO_VERSION=2.9.4
RUN corepack enable pnpm && pnpm add -g turbo@${TURBO_VERSION}
COPY . .
@@ -23,7 +23,7 @@ type Props = {
function CompletionPercentage({ percentage }: { percentage: number }) {
const percentageColor =
percentage > 50 ? "bg-success-primary text-success-primary" : "bg-danger-primary text-danger-primary";
percentage > 50 ? "bg-success-subtle text-success-primary" : "bg-danger-subtle text-danger-primary";
return (
<div className={cn("flex items-center gap-2 rounded-sm p-1 text-11", percentageColor)}>
<span>{percentage}%</span>
@@ -77,7 +77,8 @@ export const InboxIssueActionsHeader = observer(function InboxIssueActionsHeader
const { currentTab, deleteInboxIssue, filteredInboxIssueIds } = useProjectInbox();
const { data: currentUser } = useUser();
const { allowPermissions } = useUserPermissions();
const { currentProjectDetails } = useProject();
const { getPartialProjectById } = useProject();
const currentProjectDetails = getPartialProjectById(projectId);
const { t } = useTranslation();
const router = useAppRouter();
@@ -4,7 +4,6 @@
* See the LICENSE file for details.
*/
import React from "react";
import { observer } from "mobx-react";
import { Clock, FileStack, MoreHorizontal, PanelLeft, MoveRight } from "lucide-react";
import { IconButton, getIconButtonStyling } from "@plane/propel/icon-button";
@@ -18,6 +17,7 @@ import {
CloseCircleFilledIcon,
} from "@plane/propel/icons";
import type { TNameDescriptionLoader } from "@plane/types";
import { Header, CustomMenu, EHeaderVariant } from "@plane/ui";
import { cn, findHowManyDaysLeft, generateWorkItemLink } from "@plane/utils";
// components
@@ -27,6 +27,7 @@ import { useProject } from "@/hooks/store/use-project";
import { useAppRouter } from "@/hooks/use-app-router";
// store types
import type { IInboxIssueStore } from "@/store/inbox/inbox-issue.store";
// local imports
import { InboxIssueStatus } from "../inbox-issue-status";
@@ -221,7 +222,7 @@ export const InboxIssueActionsMobileHeader = observer(function InboxIssueActions
{canDelete && !isAcceptedOrDeclined && (
<CustomMenu.MenuItem onClick={() => setDeleteIssueModal(true)}>
<div className="flex items-center gap-2 text-danger-primary">
<TrashIcon width={14} height={14} strokeWidth={2} />
<TrashIcon height={14} width={14} strokeWidth={2} />
Delete
</div>
</CustomMenu.MenuItem>
@@ -26,7 +26,13 @@ export function InboxIssueSnoozeModal(props: InboxIssueSnoozeModalProps) {
const { t } = useTranslation();
return (
<ModalCore isOpen={isOpen} handleClose={handleClose} position={EModalPosition.CENTER} width={EModalWidth.XXL}>
<ModalCore
isOpen={isOpen}
handleClose={handleClose}
position={EModalPosition.CENTER}
width={EModalWidth.SM}
className="w-auto"
>
<div className="flex h-full w-full flex-col gap-y-1 px-5 py-8 sm:p-6">
<Calendar
className="rounded-md border border-subtle p-3"
@@ -139,6 +139,7 @@ export const SubIssuesListItemProperties = observer(function SubIssuesListItemPr
from: getDate(issue.start_date) || undefined,
to: getDate(issue.target_date) || undefined,
}}
placement="top-end"
onSelect={(range) => {
handleStartDate(range?.from ?? null);
handleTargetDate(range?.to ?? null);
@@ -154,6 +155,7 @@ export const SubIssuesListItemProperties = observer(function SubIssuesListItemPr
showTooltip
customTooltipHeading="Date Range"
renderPlaceholder={false}
renderInPortal
/>
</div>
</WithDisplayPropertiesHOC>
@@ -138,7 +138,7 @@ export const IssueBlockRoot = observer(function IssueBlockRoot(props: Props) {
root={containerRef}
classNames={`relative ${isLastChild && !isExpanded ? "" : "border-b border-b-subtle"}`}
verticalOffset={100}
defaultValue={shouldRenderByDefault || isIssueNew(issuesMap[issueId])}
defaultValue={shouldRenderByDefault || (issuesMap[issueId] ? isIssueNew(issuesMap[issueId]) : false)}
placeholderChildren={<ListLoaderItemRow shouldAnimate={false} renderForPlaceHolder defaultPropertyCount={4} />}
shouldRecordHeights={isMobile}
>
@@ -81,10 +81,13 @@ export const SpreadsheetIssueRow = observer(function SpreadsheetIssueRow(props:
const { issueMap } = useIssues();
// derived values
const issue = issueMap[issueId];
const subIssues = subIssuesStore.subIssuesByIssueId(issueId);
const isIssueSelected = selectionHelpers.getIsEntitySelected(issueId);
const isIssueActive = selectionHelpers.getIsEntityActive(issueId);
if (!issue) return null;
return (
<>
{/* first column/ issue name and key column */}
@@ -104,7 +107,7 @@ export const SpreadsheetIssueRow = observer(function SpreadsheetIssueRow(props:
})}
verticalOffset={100}
shouldRecordHeights={false}
defaultValue={shouldRenderByDefault || isIssueNew(issueMap[issueId])}
defaultValue={shouldRenderByDefault || isIssueNew(issue)}
>
<IssueRowDetails
issueId={issueId}
@@ -5,7 +5,7 @@
*/
import { useEffect, useRef, useState } from "react";
import { xor } from "lodash-es";
import { isEqual, xor } from "lodash-es";
import { observer } from "mobx-react";
import { useParams } from "next/navigation";
// Plane imports
@@ -260,6 +260,67 @@ export const CreateUpdateIssueModalBase = observer(function CreateUpdateIssueMod
}
};
const handleCycleChange = async (data: Partial<TIssue> | undefined, payload: Partial<TIssue>) => {
if (!workspaceSlug || !data?.project_id || !data?.id) return;
// return if user is not trying to change the cycle, i.e
// - cycle_id is not present in payload
// - cycle_id is the same as the current cycle id
if (!("cycle_id" in payload) || isEqual(data?.cycle_id, payload.cycle_id)) return;
const slug = workspaceSlug.toString();
// Removing the cycle
const currentCycleId = data?.cycle_id;
if (currentCycleId && payload.cycle_id === null) {
await issues.removeIssueFromCycle(slug, data.project_id, currentCycleId, data.id);
fetchCycleDetails(slug, data.project_id, currentCycleId).catch((error) => {
console.error(error);
});
}
// Adding the cycle
const newCycleId = payload.cycle_id;
if (newCycleId && newCycleId !== "" && (payload.cycle_id !== cycleId || storeType !== EIssuesStoreType.CYCLE)) {
await addIssueToCycle(data as TBaseIssue, newCycleId);
}
};
const handleModuleChange = async (data: Partial<TIssue>, payload: Partial<TIssue>) => {
if (!workspaceSlug || !data?.project_id || !data?.id) return;
// return if user is not trying to change the module, i.e
// - module_ids is not present in payload
// - module_ids is not an array
// - module_ids is the same as the current module ids
if (
!("module_ids" in payload) ||
!Array.isArray(payload.module_ids) ||
isEqual(data?.module_ids, payload.module_ids)
)
return;
const updatedModuleIds = xor(data.module_ids, payload.module_ids);
const modulesToAdd: string[] = [];
const modulesToRemove: string[] = [];
for (const moduleId of updatedModuleIds) {
if (data.module_ids?.includes(moduleId)) {
modulesToRemove.push(moduleId);
} else {
modulesToAdd.push(moduleId);
}
}
// update modules if there are modules to add or remove
if (modulesToAdd.length > 0 || modulesToRemove.length > 0) {
await issues.changeModulesInIssue(
workspaceSlug.toString(),
data.project_id,
data.id,
modulesToAdd,
modulesToRemove
);
}
};
const handleUpdateIssue = async (payload: Partial<TIssue>): Promise<TIssue | undefined> => {
if (!workspaceSlug || !payload.project_id || !data?.id) return;
@@ -267,41 +328,10 @@ export const CreateUpdateIssueModalBase = observer(function CreateUpdateIssueMod
if (isDraft) await draftIssues.updateIssue(workspaceSlug.toString(), data.id, payload);
else if (updateIssue) await updateIssue(payload.project_id, data.id, payload);
// check if we should add/remove issue to/from cycle
if (
payload.cycle_id &&
payload.cycle_id !== "" &&
(payload.cycle_id !== cycleId || storeType !== EIssuesStoreType.CYCLE)
) {
await addIssueToCycle(data as TBaseIssue, payload.cycle_id);
}
if (data.cycle_id && !payload.cycle_id && data.project_id) {
await issues.removeIssueFromCycle(workspaceSlug.toString(), data.project_id, data.cycle_id, data.id);
fetchCycleDetails(workspaceSlug.toString(), data.project_id, data.cycle_id);
}
if (data.module_ids && payload.module_ids && data.project_id) {
const updatedModuleIds = xor(data.module_ids, payload.module_ids);
const modulesToAdd: string[] = [];
const modulesToRemove: string[] = [];
for (const moduleId of updatedModuleIds) {
if (data.module_ids.includes(moduleId)) {
modulesToRemove.push(moduleId);
} else {
modulesToAdd.push(moduleId);
}
}
await issues.changeModulesInIssue(
workspaceSlug.toString(),
data.project_id,
data.id,
modulesToAdd,
modulesToRemove
);
}
// add other property values
// Run cycle, module, and property changes sequentially to avoid
// optimistic store writes from racing against each other.
await handleCycleChange(data, payload);
await handleModuleChange(data, payload);
await handleCreateUpdatePropertyValues({
issueId: data.id,
issueTypeId: payload.type_id,
+14 -15
View File
@@ -12,6 +12,7 @@ import type { TOnboardingStep } from "@plane/types";
import { EOnboardingSteps } from "@plane/types";
import { cn } from "@plane/utils";
// hooks
import { useInstance } from "@/hooks/store/use-instance";
import { useUser } from "@/hooks/store/user";
// local imports
import { SwitchAccountDropdown } from "./switch-account-dropdown";
@@ -26,6 +27,8 @@ export const OnboardingHeader = observer(function OnboardingHeader(props: Onboar
const { currentStep, updateCurrentStep, hasInvitations } = props;
// store hooks
const { data: user } = useUser();
const { config: instanceConfig } = useInstance();
const isSelfManaged = instanceConfig?.is_self_managed;
// handle step back
const handleStepBack = () => {
@@ -37,7 +40,7 @@ export const OnboardingHeader = observer(function OnboardingHeader(props: Onboar
updateCurrentStep(EOnboardingSteps.ROLE_SETUP);
break;
case EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN:
updateCurrentStep(EOnboardingSteps.USE_CASE_SETUP);
updateCurrentStep(isSelfManaged ? EOnboardingSteps.PROFILE_SETUP : EOnboardingSteps.USE_CASE_SETUP);
break;
}
};
@@ -45,22 +48,18 @@ export const OnboardingHeader = observer(function OnboardingHeader(props: Onboar
// can go back
const canGoBack = ![EOnboardingSteps.PROFILE_SETUP, EOnboardingSteps.INVITE_MEMBERS].includes(currentStep);
// Get current step number for progress tracking
const getCurrentStepNumber = (): number => {
const stepOrder: TOnboardingStep[] = [
EOnboardingSteps.PROFILE_SETUP,
EOnboardingSteps.ROLE_SETUP,
EOnboardingSteps.USE_CASE_SETUP,
...(hasInvitations
? [EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN]
: [EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN, EOnboardingSteps.INVITE_MEMBERS]),
];
return stepOrder.indexOf(currentStep) + 1;
};
// step order for progress tracking — include INVITE_MEMBERS if user is currently on it
const showInviteStep = !hasInvitations || currentStep === EOnboardingSteps.INVITE_MEMBERS;
const stepOrder: TOnboardingStep[] = [
EOnboardingSteps.PROFILE_SETUP,
...(isSelfManaged ? [] : [EOnboardingSteps.ROLE_SETUP, EOnboardingSteps.USE_CASE_SETUP]),
EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN,
...(showInviteStep ? [EOnboardingSteps.INVITE_MEMBERS] : []),
];
// derived values
const currentStepNumber = getCurrentStepNumber();
const totalSteps = hasInvitations ? 4 : 5; // 4 if invites available, 5 if not
const currentStepNumber = stepOrder.indexOf(currentStep) + 1;
const totalSteps = stepOrder.length;
const userName = user?.display_name
? user?.display_name
: user?.first_name
+12 -2
View File
@@ -11,6 +11,7 @@ import { TOAST_TYPE, setToast } from "@plane/propel/toast";
import type { IWorkspaceMemberInvitation, TOnboardingStep, TOnboardingSteps, TUserProfile } from "@plane/types";
import { EOnboardingSteps } from "@plane/types";
// hooks
import { useInstance } from "@/hooks/store/use-instance";
import { useWorkspace } from "@/hooks/store/use-workspace";
import { useUser, useUserProfile } from "@/hooks/store/user";
// local components
@@ -27,8 +28,10 @@ export const OnboardingRoot = observer(function OnboardingRoot({ invitations = [
const { data: user } = useUser();
const { data: userProfile, updateUserProfile, finishUserOnboarding } = useUserProfile();
const { workspaces } = useWorkspace();
const { config: instanceConfig } = useInstance();
const workspacesList = Object.values(workspaces ?? {});
const isSelfManaged = instanceConfig?.is_self_managed;
// Calculate total steps based on whether invitations are available
const hasInvitations = invitations.length > 0;
@@ -68,7 +71,14 @@ export const OnboardingRoot = observer(function OnboardingRoot({ invitations = [
(step: EOnboardingSteps, skipInvites?: boolean) => {
switch (step) {
case EOnboardingSteps.PROFILE_SETUP:
setCurrentStep(EOnboardingSteps.ROLE_SETUP);
if (isSelfManaged) {
// Skip role & use case steps for self-hosted
stepChange({ profile_complete: true });
if (workspacesList.length > 0) finishOnboarding();
else setCurrentStep(EOnboardingSteps.WORKSPACE_CREATE_OR_JOIN);
} else {
setCurrentStep(EOnboardingSteps.ROLE_SETUP);
}
break;
case EOnboardingSteps.ROLE_SETUP:
setCurrentStep(EOnboardingSteps.USE_CASE_SETUP);
@@ -91,7 +101,7 @@ export const OnboardingRoot = observer(function OnboardingRoot({ invitations = [
break;
}
},
[stepChange, finishOnboarding, workspacesList]
[stepChange, finishOnboarding, workspacesList, isSelfManaged]
);
const updateCurrentStep = (step: EOnboardingSteps) => setCurrentStep(step);
@@ -4,13 +4,13 @@
* See the LICENSE file for details.
*/
import React, { useCallback } from "react";
import { useCallback } from "react";
import { observer } from "mobx-react";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowRightCircle } from "lucide-react";
import { Tab } from "@headlessui/react";
// plane imports
import { useTranslation } from "@plane/i18n";
import { Tabs } from "@plane/propel/tabs";
import { Tooltip } from "@plane/propel/tooltip";
// hooks
import { useQueryParams } from "@/hooks/use-query-params";
@@ -26,7 +26,6 @@ import { PageNavigationPaneTabsList } from "./tabs-list";
import type { INavigationPaneExtension } from "./types/extensions";
import {
PAGE_NAVIGATION_PANE_TAB_KEYS,
PAGE_NAVIGATION_PANE_TABS_QUERY_PARAM,
PAGE_NAVIGATION_PANE_VERSION_QUERY_PARAM,
PAGE_NAVIGATION_PANE_WIDTH,
@@ -55,7 +54,6 @@ export const PageNavigationPaneRoot = observer(function PageNavigationPaneRoot(p
PAGE_NAVIGATION_PANE_TABS_QUERY_PARAM
) as TPageNavigationPaneTab | null;
const activeTab: TPageNavigationPaneTab = navigationPaneQueryParam || "outline";
const selectedIndex = PAGE_NAVIGATION_PANE_TAB_KEYS.indexOf(activeTab);
// Check if any extension is currently active based on query parameters
const ActiveExtension = extensions.find((extension) => {
@@ -75,8 +73,8 @@ export const PageNavigationPaneRoot = observer(function PageNavigationPaneRoot(p
const { t } = useTranslation();
const handleTabChange = useCallback(
(index: number) => {
const updatedTab = PAGE_NAVIGATION_PANE_TAB_KEYS[index];
(value: string) => {
const updatedTab = value as TPageNavigationPaneTab;
const isUpdatedTabInfo = updatedTab === "info";
const updatedRoute = updateQueryParams({
paramsToAdd: { [PAGE_NAVIGATION_PANE_TABS_QUERY_PARAM]: updatedTab },
@@ -112,10 +110,10 @@ export const PageNavigationPaneRoot = observer(function PageNavigationPaneRoot(p
{ActiveExtension ? (
<ActiveExtension.component page={page} extensionData={ActiveExtension.data} storeType={storeType} />
) : showNavigationTabs ? (
<Tab.Group as={React.Fragment} selectedIndex={selectedIndex} onChange={handleTabChange}>
<Tabs value={activeTab} onValueChange={handleTabChange}>
<PageNavigationPaneTabsList />
<PageNavigationPaneTabPanelsRoot page={page} versionHistory={versionHistory} />
</Tab.Group>
</Tabs>
) : null}
</div>
</aside>
@@ -4,9 +4,9 @@
* See the LICENSE file for details.
*/
import { Tab } from "@headlessui/react";
// plane imports
import { useTranslation } from "@plane/i18n";
import { Tabs } from "@plane/propel/tabs";
// plane web components
import { ORDERED_PAGE_NAVIGATION_TABS_LIST } from "@/plane-web/components/pages/navigation-pane";
@@ -15,29 +15,15 @@ export function PageNavigationPaneTabsList() {
const { t } = useTranslation();
return (
<Tab.List className="relative mx-3.5 flex items-center rounded-md bg-layer-3 p-0.5">
{({ selectedIndex }) => (
<>
{ORDERED_PAGE_NAVIGATION_TABS_LIST.map((tab) => (
<Tab
key={tab.key}
type="button"
className="relative z-[1] flex-1 py-1.5 text-13 font-semibold outline-none"
>
{t(tab.i18n_label)}
</Tab>
))}
{/* active tab indicator */}
<div
className="pointer-events-none absolute top-1/2 -translate-y-1/2 rounded-sm bg-layer-3-selected transition-all duration-500 ease-in-out"
style={{
left: `calc(${(selectedIndex / ORDERED_PAGE_NAVIGATION_TABS_LIST.length) * 100}% + 2px)`,
height: "calc(100% - 4px)",
width: `calc(${100 / ORDERED_PAGE_NAVIGATION_TABS_LIST.length}% - 4px)`,
}}
/>
</>
)}
</Tab.List>
<div className="mx-3.5">
<Tabs.List>
{ORDERED_PAGE_NAVIGATION_TABS_LIST.map((tab) => (
<Tabs.Trigger key={tab.key} value={tab.key}>
{t(tab.i18n_label)}
</Tabs.Trigger>
))}
<Tabs.Indicator />
</Tabs.List>
</div>
);
}
@@ -9,7 +9,6 @@ import { FileText, GithubIcon, MessageSquare, Rocket } from "lucide-react";
import type { TPowerKCommandConfig } from "@/components/power-k/core/types";
// hooks
import { usePowerK } from "@/hooks/store/use-power-k";
import { useChatSupport } from "@/hooks/use-chat-support";
/**
* Help commands - Help related commands
@@ -17,7 +16,6 @@ import { useChatSupport } from "@/hooks/use-chat-support";
export const usePowerKHelpCommands = (): TPowerKCommandConfig[] => {
// store
const { toggleShortcutsListModal } = usePowerK();
const { isEnabled: isChatSupportEnabled, openChatSupport } = useChatSupport();
return [
{
@@ -71,16 +69,5 @@ export const usePowerKHelpCommands = (): TPowerKCommandConfig[] => {
isVisible: () => true,
closeOnSelect: true,
},
{
id: "chat_with_us",
type: "action",
group: "help",
i18n_title: "power_k.help_actions.chat_with_us",
icon: MessageSquare,
action: () => openChatSupport(),
isEnabled: () => isChatSupportEnabled,
isVisible: () => isChatSupportEnabled,
closeOnSelect: true,
},
];
};
@@ -8,6 +8,7 @@ import { useState, Fragment } from "react";
import { Dialog, Transition } from "@headlessui/react";
// plane imports
import { CloseIcon, SearchIcon } from "@plane/propel/icons";
import { ScrollArea } from "@plane/propel/scrollarea";
import { Input } from "@plane/ui";
// hooks
import { usePowerK } from "@/hooks/store/use-power-k";
@@ -61,28 +62,33 @@ export function ShortcutsModal(props: Props) {
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
>
<Dialog.Panel className="relative flex h-full items-center justify-center">
<div className="flex h-[61vh] w-full flex-col space-y-4 overflow-hidden rounded-lg bg-surface-1 p-5 shadow-raised-200 transition-all sm:w-[28rem]">
<Dialog.Title as="h3" className="flex justify-between">
<div className="flex h-[61vh] w-full flex-col space-y-4 overflow-hidden rounded-lg bg-surface-1 py-5 shadow-raised-200 transition-all sm:w-[28rem]">
<Dialog.Title as="h3" className="flex justify-between px-5">
<span className="text-16 font-medium">Keyboard shortcuts</span>
<button type="button" onClick={handleClose}>
<CloseIcon className="h-4 w-4 text-secondary hover:text-primary" aria-hidden="true" />
</button>
</Dialog.Title>
<div className="flex w-full items-center rounded-sm border-[0.5px] border-subtle bg-surface-2 px-2">
<SearchIcon className="h-3.5 w-3.5 text-secondary" />
<Input
id="search"
name="search"
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search for shortcuts"
className="w-full border-none bg-transparent py-1 text-11 text-secondary outline-none"
autoFocus
tabIndex={1}
/>
<div className="px-5">
<div className="flex w-full items-center rounded-sm border-[0.5px] border-subtle bg-surface-2 px-2">
<SearchIcon className="h-3.5 w-3.5 text-secondary" />
<Input
id="search"
name="search"
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search for shortcuts"
className="w-full border-none bg-transparent py-1 text-11 text-secondary outline-none"
autoFocus
tabIndex={1}
/>
</div>
</div>
<ShortcutRenderer searchQuery={query} commands={allCommandsWithShortcuts} />
<ScrollArea size="sm" rootClassName="overflow-y-scroll px-5">
<ShortcutRenderer searchQuery={query} commands={allCommandsWithShortcuts} />
</ScrollArea>
</div>
</Dialog.Panel>
</Transition.Child>
@@ -78,7 +78,7 @@ export function ShortcutRenderer(props: Props) {
const isShortcutsEmpty = groupedCommands.length === 0;
return (
<div className="flex flex-col gap-y-3 overflow-y-auto">
<div className="flex flex-col gap-y-3">
{!isShortcutsEmpty ? (
groupedCommands.map((group) => (
<div key={group.key}>
@@ -9,6 +9,7 @@ import { useParams } from "next/navigation";
import useSWR from "swr";
// ui
import { useTranslation } from "@plane/i18n";
import { Avatar } from "@plane/propel/avatar";
import { EmptyStateCompact } from "@plane/propel/empty-state";
import { Loader, Card } from "@plane/ui";
import { calculateTimeAgo, getFileURL } from "@plane/utils";
@@ -49,19 +50,12 @@ export const ProfileActivity = observer(function ProfileActivity() {
<div className="space-y-5">
{userProfileActivity.results.map((activity) => (
<div key={activity.id} className="flex gap-3">
<div className="grid h-6 w-6 flex-shrink-0 place-items-center overflow-hidden rounded-sm">
{activity.actor_detail?.avatar_url && activity.actor_detail?.avatar_url !== "" ? (
<img
src={getFileURL(activity.actor_detail?.avatar_url)}
alt={activity.actor_detail?.display_name}
className="rounded-sm"
/>
) : (
<div className="grid h-6 w-6 place-items-center rounded-sm border-2 border-strong text-11 text-on-color">
{activity.actor_detail?.display_name?.charAt(0)}
</div>
)}
</div>
<Avatar
name={activity.actor_detail?.display_name}
src={getFileURL(activity.actor_detail?.avatar_url)}
size="base"
shape="square"
/>
<div className="-mt-1 w-4/5 break-words">
<p className="inline text-13 text-secondary">
<span className="font-medium text-primary">
+1 -1
View File
@@ -418,7 +418,7 @@ export function ProjectDetailsForm(props: IProjectDetailsForm) {
onChange(value);
}}
error={Boolean(errors.timezone)}
buttonClassName="border-none"
buttonClassName="!border-subtle !shadow-none font-medium rounded-md"
disabled={!isAdmin}
/>
</>
@@ -150,13 +150,32 @@ export const GeneralProfileSettingsForm = observer(function GeneralProfileSettin
role: formData.role,
};
const updateCurrentUserDetail = updateCurrentUser(userPayload).finally(() => setIsLoading(false));
const updateCurrentUserProfile = updateUserProfile(profilePayload).finally(() => setIsLoading(false));
const updateCurrentUserDetail = updateCurrentUser(userPayload);
const promises: Promise<IUser | TUserProfile | undefined>[] = [updateCurrentUserDetail];
if (profilePayload.role !== profile.role) {
const updateCurrentUserProfile = updateUserProfile(profilePayload);
promises.push(updateCurrentUserProfile);
}
const promises = [updateCurrentUserDetail, updateCurrentUserProfile];
const updateUserAndProfile = Promise.all(promises);
const updatePromise = Promise.allSettled(promises)
.then((results) => {
const rejectedResult = results.find((result) => result.status === "rejected") as
| PromiseRejectedResult
| undefined;
if (rejectedResult) {
throw rejectedResult.reason ?? new Error("Failed to update profile");
}
const values = results.map(
(result) => (result as PromiseFulfilledResult<IUser | TUserProfile | undefined>).value
);
if (values.some((v) => v === undefined)) {
throw new Error("Failed to update profile");
}
return values;
})
.finally(() => setIsLoading(false));
setPromiseToast(updateUserAndProfile, {
setPromiseToast(updatePromise, {
loading: "Updating...",
success: {
title: "Success!",
@@ -167,11 +186,6 @@ export const GeneralProfileSettingsForm = observer(function GeneralProfileSettin
message: () => `There was some error in updating your profile. Please try again.`,
},
});
updateUserAndProfile
.then(() => {
return;
})
.catch(() => {});
};
return (
@@ -6,7 +6,7 @@
import React, { useState } from "react";
import { observer } from "mobx-react";
import { HelpCircle, MessagesSquare, User } from "lucide-react";
import { HelpCircle, User } from "lucide-react";
import { useTranslation } from "@plane/i18n";
import { PageIcon } from "@plane/propel/icons";
// ui
@@ -16,7 +16,6 @@ import { ProductUpdatesModal } from "@/components/global";
import { AppSidebarItem } from "@/components/sidebar/sidebar-item";
// hooks
import { usePowerK } from "@/hooks/store/use-power-k";
import { useChatSupport } from "@/hooks/use-chat-support";
// plane web components
import { PlaneVersionNumber } from "@/plane-web/components/global";
@@ -24,7 +23,6 @@ export const HelpMenuRoot = observer(function HelpMenuRoot() {
// store hooks
const { t } = useTranslation();
const { toggleShortcutsListModal } = usePowerK();
const { openChatSupport, isEnabled: isChatSupportEnabled } = useChatSupport();
// states
const [isNeedHelpOpen, setIsNeedHelpOpen] = useState(false);
const [isProductUpdatesModalOpen, setProductUpdatesModalOpen] = useState(false);
@@ -56,18 +54,6 @@ export const HelpMenuRoot = observer(function HelpMenuRoot() {
<span className="text-11">{t("documentation")}</span>
</div>
</CustomMenu.MenuItem>
{isChatSupportEnabled && (
<CustomMenu.MenuItem>
<button
type="button"
onClick={openChatSupport}
className="flex w-full items-center gap-x-2 rounded-sm text-11 hover:bg-layer-1"
>
<MessagesSquare className="h-3.5 w-3.5 text-secondary" />
<span className="text-11">{t("message_support")}</span>
</button>
</CustomMenu.MenuItem>
)}
<CustomMenu.MenuItem onClick={() => window.open("mailto:sales@plane.so", "_blank")}>
<div className="flex items-center gap-x-2 rounded-sm text-11">
<User className="h-3.5 w-3.5 text-secondary" size={14} />
@@ -1,19 +0,0 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
type ChatSupportType = "open";
type ChatSupportEventType = `chat-support:${ChatSupportType}`;
export const CHAT_SUPPORT_EVENTS = {
open: "chat-support:open",
} satisfies Record<ChatSupportType, ChatSupportEventType>;
export class ChatSupportEvent extends CustomEvent<ChatSupportType> {
constructor(type: ChatSupportType) {
super(CHAT_SUPPORT_EVENTS[type]);
}
}
-31
View File
@@ -1,31 +0,0 @@
/**
* Copyright (c) 2023-present Plane Software, Inc. and contributors
* SPDX-License-Identifier: AGPL-3.0-only
* See the LICENSE file for details.
*/
import { useCallback } from "react";
// custom events
import { ChatSupportEvent } from "@/custom-events/chat-support";
// hooks
import { useInstance } from "@/hooks/store/use-instance";
import { useUser } from "@/hooks/store/user";
export interface IUseChatSupport {
openChatSupport: () => void;
isEnabled: boolean;
}
export const useChatSupport = (): IUseChatSupport => {
const { data: user } = useUser();
const { config } = useInstance();
// derived values
const isEnabled = Boolean(user && config?.is_intercom_enabled && config?.intercom_app_id);
const openChatSupport = useCallback(() => {
if (!isEnabled) return;
window.dispatchEvent(new ChatSupportEvent("open"));
}, [isEnabled]);
return { openChatSupport, isEnabled };
};
+31 -38
View File
@@ -84,7 +84,7 @@ export const DEFAULT_COVER_IMAGE_URL = STATIC_COVER_IMAGES.IMAGE_1;
*/
const STATIC_COVER_IMAGES_SET = new Set<string>(Object.values(STATIC_COVER_IMAGES));
export type TCoverImageType = "local_static" | "uploaded_asset";
export type TCoverImageType = "local_static" | "uploaded_asset" | "unsplash";
export type TCoverImageResult = {
needsUpload: boolean;
@@ -114,6 +114,17 @@ export const getCoverImageType = (imageUrl: string): TCoverImageType => {
// Check against the explicit set of static images
if (isStaticCoverImage(imageUrl)) return "local_static";
// Check if it's an Unsplash image by validating the hostname
try {
const url = new URL(imageUrl);
const hostname = url.hostname.toLowerCase();
if (hostname === "unsplash.com" || hostname.endsWith(".unsplash.com")) {
return "unsplash";
}
} catch {
// If URL parsing fails (e.g., relative path), fall through to other checks
}
if (imageUrl.startsWith("http")) return "uploaded_asset";
return "uploaded_asset";
@@ -136,7 +147,7 @@ export function getCoverImageDisplayURL(
const imageType = getCoverImageType(imageUrl);
if (imageType === "local_static") {
if (imageType === "local_static" || imageType === "unsplash") {
return imageUrl;
}
@@ -149,6 +160,7 @@ export function getCoverImageDisplayURL(
/**
* Analyzes cover image change and determines what action to take
* Merged with isUnsplashImage logic - now detects unsplash images as a separate type
*/
export const analyzeCoverImageChange = (
currentImage: string | null | undefined,
@@ -164,10 +176,18 @@ export const analyzeCoverImageChange = (
};
}
const imageType = getCoverImageType(newImage ?? "");
if (!newImage) {
return {
needsUpload: false,
imageType: "uploaded_asset",
shouldUpdate: true,
};
}
const imageType = getCoverImageType(newImage);
return {
needsUpload: imageType === "local_static",
needsUpload: imageType === "local_static" || imageType === "unsplash",
imageType,
shouldUpdate: hasChanged,
};
@@ -201,7 +221,7 @@ export const uploadCoverImage = async (
throw new Error("Invalid file type. Please select an image.");
}
const fileName = imageUrl.split("/").pop() || "cover.jpg";
const fileName = imageUrl.split("/").pop()?.split("?")[0] || "image.jpg";
const file = new File([blob], fileName, { type: blob.type });
// Upload based on context
@@ -233,7 +253,6 @@ export const uploadCoverImage = async (
/**
* Main utility to handle cover image changes with upload
* Returns the payload fields that should be updated
*/
export const handleCoverImageChange = async (
currentImage: string | null | undefined,
@@ -244,46 +263,20 @@ export const handleCoverImageChange = async (
entityType: EFileAssetType;
isUserAsset?: boolean;
}
): Promise<TCoverImagePayload | null> => {
): Promise<TCoverImagePayload | undefined> => {
const analysis = analyzeCoverImageChange(currentImage, newImage);
if (!analysis.shouldUpdate) return;
// No change detected
if (!analysis.shouldUpdate) {
return null;
}
// Image removed
if (!newImage) {
return {
cover_image: null,
cover_image_url: null,
cover_image_asset: null,
};
return { cover_image: null, cover_image_url: null, cover_image_asset: null };
}
// Local static image - needs upload
if (analysis.needsUpload) {
const uploadedUrl = await uploadCoverImage(newImage, uploadConfig);
// For BOTH user assets AND project assets:
// The backend auto-links when entity_identifier is set correctly
// For project assets: auto-linked server-side, no payload needed
// For user assets: return URL for immediate UI feedback
if (uploadConfig.isUserAsset) {
return {
cover_image: uploadedUrl,
};
} else {
return null;
}
await uploadCoverImage(newImage, uploadConfig);
return;
}
// External/uploaded asset (e.g., Unsplash URL, pre-uploaded asset)
// Return the URL to be saved in the backend
return {
cover_image: newImage,
};
return { cover_image: newImage };
};
/**
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "web",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"license": "AGPL-3.0",
"type": "module",
@@ -73,7 +73,6 @@
"uuid": "catalog:"
},
"devDependencies": {
"@dotenvx/dotenvx": "catalog:",
"@plane/tailwind-config": "workspace:*",
"@plane/typescript-config": "workspace:*",
"@react-router/dev": "catalog:",
@@ -83,6 +82,7 @@
"@types/react": "catalog:",
"@types/react-color": "^3.0.6",
"@types/react-dom": "catalog:",
"dotenv": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vite-tsconfig-paths": "^5.1.4"
+1 -1
View File
@@ -1,5 +1,5 @@
import path from "node:path";
import * as dotenv from "@dotenvx/dotenvx";
import * as dotenv from "dotenv";
import { reactRouter } from "@react-router/dev/vite";
import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
+6 -6
View File
@@ -6,12 +6,12 @@ FROM --platform=$BUILDPLATFORM tonistiigi/binfmt AS binfmt
# **************************************************
FROM node:22-alpine AS node
FROM artifacts.plane.so/makeplane/plane-frontend:${PLANE_VERSION} AS web-img
FROM artifacts.plane.so/makeplane/plane-backend:${PLANE_VERSION} AS backend-img
FROM artifacts.plane.so/makeplane/plane-space:${PLANE_VERSION} AS space-img
FROM artifacts.plane.so/makeplane/plane-admin:${PLANE_VERSION} AS admin-img
FROM artifacts.plane.so/makeplane/plane-live:${PLANE_VERSION} AS live-img
FROM artifacts.plane.so/makeplane/plane-proxy:${PLANE_VERSION} AS proxy-img
FROM makeplane/plane-frontend:${PLANE_VERSION} AS web-img
FROM makeplane/plane-backend:${PLANE_VERSION} AS backend-img
FROM makeplane/plane-space:${PLANE_VERSION} AS space-img
FROM makeplane/plane-admin:${PLANE_VERSION} AS admin-img
FROM makeplane/plane-live:${PLANE_VERSION} AS live-img
FROM makeplane/plane-proxy:${PLANE_VERSION} AS proxy-img
# **************************************************
# STAGE 1: Runner
+2 -2
View File
@@ -59,7 +59,7 @@ docker run --name plane-aio --rm -it \
-e AWS_ACCESS_KEY_ID=your-access-key \
-e AWS_SECRET_ACCESS_KEY=your-secret-key \
-e AWS_S3_BUCKET_NAME=your-bucket \
artifacts.plane.so/makeplane/plane-aio-community:latest
makeplane/plane-aio-community:latest
```
### Example with IP Address
@@ -78,7 +78,7 @@ docker run --name myaio --rm -it \
-e AWS_S3_BUCKET_NAME=plane-app \
-e AWS_S3_ENDPOINT_URL=http://${MYIP}:19000 \
-e FILE_SIZE_LIMIT=10485760 \
artifacts.plane.so/makeplane/plane-aio-community:latest
makeplane/plane-aio-community:latest
```
## Configuration Options
+2 -2
View File
@@ -18,8 +18,8 @@ priority=10
[program:space]
directory=/app/space/apps/space/build/server
command=sh -c "npx react-router-serve index.js"
directory=/app/space/apps/space
command=sh -c "npx react-router-serve ./build/server/index.js"
autostart=true
autorestart=true
stdout_logfile=/app/logs/access/space.log
+9
View File
@@ -51,3 +51,12 @@ API_KEY_RATE_LIMIT=60/minute
# Live Server Secret Key
LIVE_SERVER_SECRET_KEY=htbqvBJAgpm9bzvf3r4urJer0ENReatceh
# Webhook IP allowlist — comma-separated IPs or CIDR ranges allowed as webhook targets
# even if they resolve to private networks (e.g. "10.0.0.0/8,192.168.1.0/24,172.16.0.5")
WEBHOOK_ALLOWED_IPS=
# Webhook hostname allowlist — comma-separated hostnames that bypass the private-IP
# SSRF check. Useful for trusted internal services whose container/service IPs are
# dynamic (e.g. "silo,silo.namespace.svc.cluster.local")
WEBHOOK_ALLOWED_HOSTS=
+11 -9
View File
@@ -58,10 +58,12 @@ x-app-env: &app-env
API_KEY_RATE_LIMIT: ${API_KEY_RATE_LIMIT:-60/minute}
MINIO_ENDPOINT_SSL: ${MINIO_ENDPOINT_SSL:-0}
LIVE_SERVER_SECRET_KEY: ${LIVE_SERVER_SECRET_KEY:-2FiJk1U2aiVPEQtzLehYGlTSnTnrs7LW}
WEBHOOK_ALLOWED_IPS: ${WEBHOOK_ALLOWED_IPS:-}
WEBHOOK_ALLOWED_HOSTS: ${WEBHOOK_ALLOWED_HOSTS:-}
services:
web:
image: artifacts.plane.so/makeplane/plane-frontend:${APP_RELEASE:-stable}
image: makeplane/plane-frontend:${APP_RELEASE:-stable}
deploy:
replicas: ${WEB_REPLICAS:-1}
restart_policy:
@@ -71,7 +73,7 @@ services:
- worker
space:
image: artifacts.plane.so/makeplane/plane-space:${APP_RELEASE:-stable}
image: makeplane/plane-space:${APP_RELEASE:-stable}
deploy:
replicas: ${SPACE_REPLICAS:-1}
restart_policy:
@@ -82,7 +84,7 @@ services:
- web
admin:
image: artifacts.plane.so/makeplane/plane-admin:${APP_RELEASE:-stable}
image: makeplane/plane-admin:${APP_RELEASE:-stable}
deploy:
replicas: ${ADMIN_REPLICAS:-1}
restart_policy:
@@ -92,7 +94,7 @@ services:
- web
live:
image: artifacts.plane.so/makeplane/plane-live:${APP_RELEASE:-stable}
image: makeplane/plane-live:${APP_RELEASE:-stable}
environment:
<<: [*live-env, *redis-env]
deploy:
@@ -104,7 +106,7 @@ services:
- web
api:
image: artifacts.plane.so/makeplane/plane-backend:${APP_RELEASE:-stable}
image: makeplane/plane-backend:${APP_RELEASE:-stable}
command: ./bin/docker-entrypoint-api.sh
deploy:
replicas: ${API_REPLICAS:-1}
@@ -120,7 +122,7 @@ services:
- plane-mq
worker:
image: artifacts.plane.so/makeplane/plane-backend:${APP_RELEASE:-stable}
image: makeplane/plane-backend:${APP_RELEASE:-stable}
command: ./bin/docker-entrypoint-worker.sh
deploy:
replicas: ${WORKER_REPLICAS:-1}
@@ -137,7 +139,7 @@ services:
- plane-mq
beat-worker:
image: artifacts.plane.so/makeplane/plane-backend:${APP_RELEASE:-stable}
image: makeplane/plane-backend:${APP_RELEASE:-stable}
command: ./bin/docker-entrypoint-beat.sh
deploy:
replicas: ${BEAT_WORKER_REPLICAS:-1}
@@ -154,7 +156,7 @@ services:
- plane-mq
migrator:
image: artifacts.plane.so/makeplane/plane-backend:${APP_RELEASE:-stable}
image: makeplane/plane-backend:${APP_RELEASE:-stable}
command: ./bin/docker-entrypoint-migrator.sh
deploy:
replicas: 1
@@ -216,7 +218,7 @@ services:
# Comment this if you already have a reverse proxy running
proxy:
image: artifacts.plane.so/makeplane/plane-proxy:${APP_RELEASE:-stable}
image: makeplane/plane-proxy:${APP_RELEASE:-stable}
deploy:
replicas: 1
restart_policy:
+2 -2
View File
@@ -5,7 +5,7 @@ SCRIPT_DIR=$PWD
SERVICE_FOLDER=plane-app
PLANE_INSTALL_DIR=$PWD/$SERVICE_FOLDER
export APP_RELEASE=stable
export DOCKERHUB_USER=artifacts.plane.so/makeplane
export DOCKERHUB_USER=makeplane
export PULL_POLICY=${PULL_POLICY:-if_not_present}
export GH_REPO=makeplane/plane
export RELEASE_DOWNLOAD_URL="https://github.com/$GH_REPO/releases/download"
@@ -690,7 +690,7 @@ if [ -f "$DOCKER_ENV_PATH" ]; then
CUSTOM_BUILD=$(getEnvValue "CUSTOM_BUILD" "$DOCKER_ENV_PATH")
if [ -z "$DOCKERHUB_USER" ]; then
DOCKERHUB_USER=artifacts.plane.so/makeplane
DOCKERHUB_USER=makeplane
updateEnvFile "DOCKERHUB_USER" "$DOCKERHUB_USER" "$DOCKER_ENV_PATH"
fi
+9
View File
@@ -80,3 +80,12 @@ API_KEY_RATE_LIMIT=60/minute
# Live server environment variables
# WARNING: You must set a secure value for LIVE_SERVER_SECRET_KEY in production environments.
LIVE_SERVER_SECRET_KEY=
# Webhook IP allowlist — comma-separated IPs or CIDR ranges allowed as webhook targets
# even if they resolve to private networks (e.g. "10.0.0.0/8,192.168.1.0/24,172.16.0.5")
WEBHOOK_ALLOWED_IPS=
# Webhook hostname allowlist — comma-separated hostnames that bypass the private-IP
# SSRF check. Useful for trusted internal services whose container/service IPs are
# dynamic (e.g. "silo,silo.namespace.svc.cluster.local")
WEBHOOK_ALLOWED_HOSTS=
+2 -2
View File
@@ -5,7 +5,7 @@ SERVICE_FOLDER=plane-app
SCRIPT_DIR=$PWD
PLANE_INSTALL_DIR=$PWD/$SERVICE_FOLDER
export APP_RELEASE="stable"
export DOCKERHUB_USER=artifacts.plane.so/makeplane
export DOCKERHUB_USER=makeplane
export GH_REPO=makeplane/plane
export RELEASE_DOWNLOAD_URL="https://github.com/$GH_REPO/releases/download"
@@ -595,7 +595,7 @@ if [ -f "$DOCKER_ENV_PATH" ]; then
APP_RELEASE=$(getEnvValue "APP_RELEASE" "$DOCKER_ENV_PATH")
if [ -z "$DOCKERHUB_USER" ]; then
DOCKERHUB_USER=artifacts.plane.so/makeplane
DOCKERHUB_USER=makeplane
updateEnvFile "DOCKERHUB_USER" "$DOCKERHUB_USER" "$DOCKER_ENV_PATH"
fi
+19 -6
View File
@@ -1,6 +1,6 @@
{
"name": "plane",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"description": "Open-source project management that unlocks customer value",
"license": "AGPL-3.0",
@@ -24,7 +24,7 @@
"lint-staged": "16.2.7",
"oxfmt": "0.35.0",
"oxlint": "1.51.0",
"turbo": "2.8.12"
"turbo": "2.9.4"
},
"lint-staged": {
"*.{js,jsx,ts,tsx,cjs,mjs,cts,mts,json,css,md}": [
@@ -45,7 +45,7 @@
"valibot": "1.2.0",
"glob": "11.1.0",
"js-yaml": "4.1.1",
"brace-expansion": "2.0.2",
"brace-expansion": "5.0.5",
"nanoid": "3.3.8",
"esbuild": "0.25.0",
"@babel/helpers": "7.26.10",
@@ -62,18 +62,31 @@
"webpack": "5.104.1",
"lodash-es": "catalog:",
"@isaacs/brace-expansion": "5.0.1",
"lodash": "4.17.23",
"lodash": "4.18.1",
"markdown-it": "14.1.1",
"rollup": "4.59.0",
"minimatch@3": "3.1.4",
"minimatch@10": "10.2.3",
"serialize-javascript": "7.0.3",
"serialize-javascript": "7.0.5",
"ajv@6": "6.14.0",
"ajv@8": "8.18.0",
"undici@7": "7.24.0",
"flatted": "3.4.2"
"flatted": "3.4.2",
"picomatch": "2.3.2",
"yaml@1": "1.10.3",
"yaml@2": "2.8.3",
"path-to-regexp": "0.1.13",
"defu": "6.1.5",
"postcss": "8.5.10",
"axios": "catalog:",
"follow-redirects": "1.16.0",
"uuid": "catalog:"
},
"onlyBuiltDependencies": [
"@parcel/watcher",
"@swc/core",
"esbuild",
"msgpackr-extract",
"turbo"
],
"ignoredBuiltDependencies": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@plane/codemods",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"scripts": {
"test": "vitest run",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@plane/constants",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"license": "AGPL-3.0",
"type": "module",
@@ -12,7 +12,7 @@
"./package.json": "./package.json"
},
"scripts": {
"dev": "tsdown --watch",
"dev": "tsdown --watch --no-clean",
"build": "tsdown",
"check:lint": "oxlint --max-warnings=2 .",
"check:types": "tsc --noEmit",
+6 -1
View File
@@ -14,7 +14,7 @@
},
"scripts": {
"build": "tsdown",
"dev": "tsdown --watch",
"dev": "tsdown --watch --no-clean",
"check:lint": "oxlint --max-warnings=3 .",
"check:types": "tsc --noEmit",
"check:format": "oxfmt --check .",
@@ -30,5 +30,10 @@
"reflect-metadata": "^0.2.2",
"tsdown": "catalog:",
"typescript": "catalog:"
},
"inlinedDependencies": {
"@types/express": "4.17.23",
"@types/express-serve-static-core": "4.19.6",
"reflect-metadata": "0.2.2"
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@plane/editor",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"description": "Core Editor that powers Plane",
"keywords": [
@@ -24,7 +24,7 @@
},
"scripts": {
"build": "tsc && tsdown",
"dev": "tsdown --watch",
"dev": "tsdown --watch --no-clean",
"check:lint": "oxlint --max-warnings=416 .",
"check:types": "tsc --noEmit",
"check:format": "oxfmt --check .",
+3 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@plane/hooks",
"version": "1.2.3",
"version": "1.3.1",
"private": true,
"description": "React hooks that are shared across multiple apps internally",
"license": "AGPL-3.0",
@@ -9,15 +9,12 @@
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
".": "./dist/index.js",
"./package.json": "./package.json"
},
"scripts": {
"build": "tsdown",
"dev": "tsdown --watch",
"dev": "tsdown --watch --no-clean",
"check:lint": "oxlint --max-warnings=4 .",
"check:types": "tsc --noEmit",
"check:format": "oxfmt --check .",

Some files were not shown because too many files have changed in this diff Show More