Compare commits

..
14 Commits
Author SHA1 Message Date
Andrey Antukh 37f7ba4833 📚 Note general subagent delegation in flows intro
Delegating plan and review to a subagent (engineer-* or the
builtin general) starts a clean context instead of growing the
main session. Delegating to general keeps the same model.

AI-assisted-by: muse-spark-1.3-contributor
2026-09-11 15:44:15 +00:00
Andrey Antukh ed4367a782 📎 Add missing optional system prompt file for enginer agent 2026-09-11 17:39:57 +02:00
Andrey Antukh 74fd3ac8c3 📚 Restructure .agents README as agentic devenv guide
Turn the skills-only file into a full intro to opencode inside
plain devenv: setup, providers, models, opencode.json example,
gh auth, flows, and a skills summary at the end.

Provider, model, and flow sections follow Andrey's own setup
notes; the FAQ stays as a stub for later.

AI-assisted-by: muse-spark-1.3-contributor
2026-09-11 15:34:29 +00:00
Eva Marco c0221a9bf8 🐛 Hide "Create typography style" button for shapes with missing fonts (#11527)
The button let users convert a text shape's inline styles into a
typography asset even when the shape's font-id couldn't be resolved
(e.g. a custom/team font that was removed or isn't loaded), silently
baking a missing font into the new typography asset.

Guard the button on the font actually resolving via
app.main.fonts/fontsdb, in addition to the existing checks (no
typography or token already applied, single selection).

Added e2e coverage for all four conditions that must independently
hide the button: missing font, applied typography asset, multiple
selection with differing values, and applied typography token.

AI-assisted-by: claude-sonnet-5
2026-09-11 13:41:11 +02:00
Alonso Torres b598d7d72e 🐛 Fix problem in plugins api when removing interactions (#11621) 2026-09-11 13:19:55 +02:00
Andrey Antukh 06239844b1 🐛 Fix chunked upload storage amplification and cap chunk size (#11635)
* 🐛 Reject duplicate chunk index in chunked uploads

Repeat uploads of the same chunk index each stored a new
object because upload-chunk only checked index bounds. Run the
handler in a transaction, lock the session row and reject an
already-stored index with :duplicate-chunk-index.

Also harden assemble-chunks to require exactly indices 0..n-1
 so gaps or duplicates fail instead of assembling a corrupt
file. Covers media, fonts and binfile through the shared
helper.

Closes #11634

AI-assisted-by: muse-spark-1.3-contributor

*  Cap upload chunk size at 30 MiB by default

Chunks were only bounded by the 350 MiB HTTP body limit while the
30 MiB caps applied to the assembled file. Add :upload-max-chunk-size
(default 30 MiB, tunable via env) and reject oversize chunks in
upload-chunk with :validation/:chunk-too-large before anything is
stored. App clients slice at 25/10 MiB, so no frontend change needed.

AI-assisted-by: muse-spark-1.3-contributor

* 🐛 Fix tx-run! call and storage resolve in upload-chunk

Pass cfg as first arg to db/tx-run!, which expects [system f & params; without it every chunk upload raised invalid system/cfg provided and no chunk was stored, breaking assemble with missing-chunks. Also resolve storage without reuse-conn: put-object! writes to the backend outside any transaction, so reusing the tx connection gives no atomicity. Media, font and storage suites green, lint and format clean. AI-assisted-by: muse-spark-1.3-contributor
2026-09-11 12:10:57 +02:00
Andrey Antukh 09736aa4c9 Enforce commit body line wrapping
Add a body line-length validator to scripts/check-commit. It
fails when a body line exceeds 76 characters, exempting
trailers, URLs, and unbreakable tokens. The 76 limit leaves
room for git log's four-space indent in an 80-column
terminal.

Align the subject limit with the documented 70 characters;
the checker allowed 90 before.

Document the rule as a hard, verifiable requirement in
AGENTS.md, CONTRIBUTING.md, the create-commit skill, and
the workflow memory, and point at scripts/check-commit.

Add tests for the validator and the subject length rule.

AI-assisted-by: deepseek-flash
2026-09-11 08:10:49 +00:00
Andrey Antukh f9c02926b9 Merge remote-tracking branch 'origin/main' into staging 2026-09-10 20:21:41 +02:00
bameda bae3900537 ♻️ Rebalance CI runners and drop pinned ubuntu-24.04
Move build-docker and build-docker-devenv jobs from penpot-extended-runner
to penpot-standar-runner, point tests-exporter at the canonical
penpot-extended-runner label instead of the stale penpot-runner-02 alias,
and switch build-tag/release notify jobs from ubuntu-24.04 to ubuntu-latest.

Signed-off-by: David Barragán Merino <david.barragan@kaleidos.net>
2026-09-10 19:23:13 +02:00
bameda 757a5bd479 ♻️ Rebalance CI runners and drop pinned ubuntu-24.04
Move build-docker and build-docker-devenv jobs from penpot-extended-runner
to penpot-standar-runner, point tests-exporter at the canonical
penpot-extended-runner label instead of the stale penpot-runner-02 alias,
and switch build-tag/release notify jobs from ubuntu-24.04 to ubuntu-latest.

Signed-off-by: David Barragán Merino <david.barragan@kaleidos.net>
2026-09-10 19:22:46 +02:00
Andrey Antukh 8952d70fd2 Optimize get-profiles-for-file-comments query (#11622)
Rewrite sql:file-comment-users to join comment with
comment_thread and union the requesting profile id, then
join the resulting small id set against profile.

The previous "id IN (subquery) OR id = ?" forced a
sequential scan over the whole profile table with a hashed
subplan filter, taking ~1.9s on large instances. The
semi-join lets the planner use profile_pkey, dropping the
query to sub-millisecond time. UNION (not UNION ALL) keeps
the previous dedup semantics when the requesting profile is
also a commenter.

AI-assisted-by: deepseek-flash
2026-09-10 16:45:22 +02:00
Andrey Antukh 4ce459d720 🐛 Escape LDAP filter values and use directory email in retrieve-user (#11085)
Fix LDAP injection vulnerability (T5-N1-03) where the client-supplied email was used directly in the LDAP search filter without escaping RFC 4515 special characters (*, (, ), \, NUL), and the profile email was taken from client input instead of the LDAP directory attribute.

Changes:
- Add escape-ldap-filter-value per RFC 4515 section 3
- Apply escaping in search-user before building LDAP filter
- Add get-attr helper for multi-valued LDAP attributes
- Fix retrieve-user to use directory email (attrs-email) instead of client email
- Use cuerdas.core instead of clojure.string

Closes #11084

AI-assisted-by: mimo-v2.5-pro
2026-09-10 16:39:35 +02:00
Luis de Dios c589563912 ♻️ Replace digit with number in password validations (#11609) 2026-09-10 12:15:58 +02:00
andrés gonzález 0eb3179016 💄 Adjust release notes 2.18 titles (#11608) 2026-09-10 11:50:57 +02:00
36 changed files with 2028 additions and 158 deletions

No files matched your search

+389 -17
View File
@@ -1,19 +1,391 @@
# Agent skills
# Agentic development with opencode inside devenv
This folder is the single home for the skills our coding agents use.
Each skill is a folder with a `SKILL.md` inside — a short instruction
manual that an agent loads only when it needs it.
This doc shows how to run AI-assisted development for Penpot inside the
devenv with [opencode](https://opencode.ai). It covers the setup once,
then points to the skills that drive daily work.
One copy serves every tool:
Full reference lives in the technical guide:
- **opencode** reads this folder directly.
- **Claude Code** reads it through the `.claude/skills` symlink.
- **Codex** reads it directly.
- [Dev environment](../docs/technical-guide/developer/devenv.md)
To change how the agents behave, edit the `SKILL.md` here. There is no
second copy to keep in sync.
This file does not repeat those guides. It gives the short path and
leaves room for notes we add step by step.
## How the skills are organized
## TL;DR
```bash
./manage.sh pull-devenv
./manage.sh run-devenv --ws 0 --attach
```
Then open a shell in the container tmux session, run `opencode` inside
~/penpot directory.
## 1. Introduction
The LLM client — opencode, Claude Code, or Codex — runs in a shell
inside the plain devenv container, with the repo mounted and the
skills in this folder driving the work. One client session per
workspace (`ws0` is the live repo, `ws1+` are sibling clones).
This doc is written around opencode, but Claude Code runs the same
way inside devenv and follows exactly the same flows. This is not
the "agentic devenv" (`--agentic`) from the technical guide, which
runs the client outside devenv and wires it in over MCP — here the
client lives inside the sandboxed devenv docker.
Unlike the agentic devenv, running the client inside the devenv
docker gives it full access to the live environment: every
dependency already resolved by the image, so the agent can write
and run tests directly, query the running PostgreSQL, and reach
the backend and frontend through nREPL — no proxies, no round
trips outside the container.
And if you later want vision, it is one MCP entry away — a
headless Playwright server in your `opencode.json`:
```json
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"playwright": {
"type": "local",
"command": ["npx", "-y", "@playwright/mcp", "--headless"],
"enabled": true,
"env": {}
}
}
}
```
## 2. Quickstart: bring up devenv and run opencode inside
Pull once, then bring up the workspace you want (add `--ws 1`,
`--ws 2`, … for more):
```bash
./manage.sh pull-devenv
./manage.sh run-devenv --ws 0 --attach # ws0 (the live repo)
```
This attaches to the container tmux session. Open a new shell there
(`Ctrl+b c`), `cd` to the repo, and run opencode directly:
```bash
cd penpot;
opencode
```
One session drives exactly one workspace — for N parallel workspaces,
open one container shell and one opencode session per workspace.
Stop with `./manage.sh stop-devenv [--ws N | --all]`. Shared infra
stops when the last workspace stops.
## 3. Connecting providers
### Starting point: Zen free models, no login needed
The easiest way to try the setup is Zen's free models — they need no
login and no key. Just run opencode, pick a free model, and work.
That said, creating a Zen account and connecting with your API key is
still worth it from day one: it unlocks the full model list, spend
limits, auto-reload, and the Go-overflow fallback below. Connect
through the TUI:
- Run `/connect`, pick a provider, paste the key.
- Run `/models` to see what that provider offers.
### OpenCode Go (subscription, best value for daily use)
$10/month subscription with generous included usage — up to $60/month
of model consumption at published per-token rates, depending on the
model. Best value if you work mostly with open coding models
(GLM, Kimi, Qwen, DeepSeek, MiniMax, LongCat…).
The strong part: when you hit a model's monthly limit, Go can fall
back to your Zen balance instead of blocking (enable *Use balance* in
the console). So the setup many of us use is Go + Zen credit on top —
subscription first, pay-as-you-go overflow after.
### OpenCode Zen (pay per use)
Zen is the opencode team's gateway: curated models tested for coding
agents, fair prices, no markups, stable latency. You top up credit
and pay per request, with monthly spend limits and auto-reload.
Free usage is generous: the free models carry limits good enough for
real work, not just a quick taste. Worth knowing: brand-new,
unannounced models often show up on Zen first with a very generous
free quota so people try them — e.g. `0x Alpha`, which later turned
out to be GLM-5.3-Flash. Keep an eye on the free list; the newest
entry is often the best deal.
Two reasons to have a Zen account even with Go:
- It absorbs Go overflow (see above).
- Its free models let you try the whole setup before paying.
### OpenRouter (widest catalog)
If you already have an account, connect it: the widest model range in
one place. Trade-off is latency and occasional instability versus Zen,
which is tuned for coding agents.
Beyond code: OpenRouter also serves image, video, and audio models.
opencode itself cannot call those directly — it is built for code —
but a cheap model can quickly build you a small tool or script that
talks to them through the OpenRouter API. So if you also generate
content other than code and text, having OpenRouter connected is
worth it: the agent wires the plumbing for you.
### OpenAI (subscription or API key)
If you have an OpenAI subscription or API access, connect it — it
works very well as a daily driver alongside (or instead of) Go/Zen.
### Suggested combos
| Profile | Connect |
|---|---|
| Try it out | Nothing (Zen free models, no login) |
| Try it out, properly | Zen account + API key (free models + limits) |
| Daily use, best value | Go + Zen credit (overflow) |
| Widest model choice | Add OpenRouter |
| Already pay OpenAI | Add OpenAI account |
## 4. Recommended models
Personal picks from Andrey, current as of September 2026. Models come
and go, so treat this as a snapshot — the shape (one cheap solver,
one reviewer/planner, one explorer) matters more than the names.
| Model | Role | How often |
|---|---|---|
| Muse Spark 1.3 (`high`) | Main solver: plan, review, develop. Sharp and cheap — covers ~70% of coding tasks. | Daily |
| GLM-5.3-Flash | Reasoning all-rounder, now mostly code/plan reviewer and planner. | Daily |
| DeepSeek V4.1 Flash (`high`) | Explorer: code and idea exploration, sometimes development. Especially good at small bash/node utilities for repo chores and changelog updates. | Daily |
| LongCat 2.0 | Backup solver, occasional stand-in for Muse Spark 1.3. | Weekly |
| GPT-5.6 Luna | Alternative to DeepSeek Flash; pricier, unclear the extra cost pays off. | Rarely |
| Qwen3.8 Flash | As strong as the top three; used in rotation to avoid hammering one model. Less Go subsidy than the top picks, so mostly in overflow mode. | Overflow |
| MiMo-V2.5-Pro | Former main model; slightly pricier now next to Muse Spark / GLM-Flash / LongCat, and less Go subsidy — used in overflow. | Overflow |
| Kimi K3 | Heavy reasoning for hard reviews and plans. Expensive, ~1% of tasks. | Rarely |
| GLM-5.3 | Same slot as Kimi K3: hard reviews and plans only. | Rarely |
**TL;DR:** the first three (Muse Spark 1.3, GLM-5.3-Flash, DeepSeek
V4.1 Flash) are a good starting point.
## 5. Customizing your `opencode.json`
opencode merges config in this order (later wins):
1. Global: `~/.config/opencode/opencode.json` (on host, or the dir
mounted with `--opencode-config-dir` inside devenv —
see §9 Advanced usage).
2. Project: `opencode.json` at the repo root (gitignored on purpose —
use it to override the global entries for one workspace).
Below is a full working example of my personal config at the date of
writing this. It is only an example: define whatever subagents you
need, with whatever models you like or work with.
Copy it to `opencode.json` on the root of the repo:
```json
{
"$schema": "https://opencode.ai/config.json",
"disabled_providers": ["amazon-bedrock"],
"subagent_depth": 2,
"agent": {
"compaction": {
"model": "opencode-go/deepseek-flash",
"variant": "high"
},
"title": {
"model": "opencode-go/deepseek-flash",
"variant": "low"
},
"explore": {
"model": "opencode-go/deepseek-flash",
"variant": "high"
},
"build": {
"prompt": "{file:.agents/prompts/engineer-agent-prompt.md}",
"permission": {
"external_directory": {
"/tmp/**": "allow"
}
}
},
"general": {
"prompt": "{file:.agents/prompts/engineer-agent-prompt.md}",
"permission": {
"external_directory": {
"/tmp/**": "allow"
}
}
},
"engineer-glm": {
"mode": "subagent",
"model": "opencode-go/glm-5.3-flash",
"variant": "high",
"prompt": "{file:.agents/prompts/engineer-agent-prompt.md}",
"permission": {
"*": "allow",
"task": {
"*": "allow"
}
}
},
"engineer-kimi": {
"mode": "subagent",
"model": "opencode/kimi-k3",
"variant": "high",
"prompt": "{file:.agents/prompts/engineer-agent-prompt.md}",
"permission": {
"*": "allow",
"task": {
"*": "allow"
}
}
},
"engineer-qwen": {
"mode": "subagent",
"model": "opencode-go/qwen3.7-plus",
"variant": "high",
"prompt": "{file:.agents/prompts/engineer-agent-prompt.md}",
"permission": {
"*": "allow",
"task": {
"*": "allow"
}
}
}
}
}
```
What the blocks mean:
- `compaction` / `title` / `explore`: cheap background agents. Keep
them on a fast model; `title` uses the `low` variant on purpose.
- `build` / `general`: the main agents. They load the shared prompt
`{file:.agents/prompts/engineer-agent-prompt.md}` and may only touch
`/tmp/**` outside the repo without asking for explicit permision.
- `engineer-*`: one subagent per model family, all with the same
prompt and full permissions (`"*": "allow"`). They purpose are
specially for delegate work to them because are defined to be used
only as subagents.
- `disabled_providers` / `subagent_depth`: global guards. Keep
`"$schema"` — opencode refuses to start if any field is wrong.
How the `engineer-*` subagents are actually used — delegating work to
them to keep the main context clean — is covered in §6 Common agentic
flows.
Note this is opencode-only: other clients have their own way of
defining subagents or helpers — or none at all.
## 6. Common agentic flows
Work happens two ways: directly in your session, or delegated to a
subagent. Besides the `engineer-*` subagents from §5 there is a
builtin `general` subagent. Delegating planning and review to a
subagent starts a fresh, clean context with a clean prompt instead
of growing the main session — the main lever for keeping context
small. To delegate without switching models, delegate to `general`.
### Issue / error report flow
1. **Frame the problem.** Enter Plan mode (TAB in opencode) and paste the
report with your intent: "investigate this and find the possible cause",
"investigate and tell me where this points", or "does this still apply?".
Explore until you and the agent roughly agree on the problem.
2. **Write the plan.** Run `/make-a-plan` — it executes in Build mode.
If you need to step in and answer something yourself, press TAB to
leave Build mode. Use Plan mode only when you want a hard guarantee
that the agent modifies no file under any circumstance. If you
explored with a weaker model but want a stronger one to write the
plan, switch models first or delegate:
`/make-a-plan delegate to @engineer-glm`.
3. **Iterate on the plan.** The plan is saved to `.agents/plans/`, so you
never depend on LLM memory: read the file directly, or run `/review-plan`
for a second opinion (delegation works here too). Complex plans deserve a
review; simple ones can skip it.
4. **Execute.** Run `/implement-plan`. It first prints the full picture —
whether it will create an issue and a branch, the execution style, and a
task checklist — and waits for your go-ahead. Say "step by step" to stop
after each task (one commit per task) so you can verify as it goes;
the default runs all tasks with one final commit.
5. **Land the work.** When it finishes, either push yourself and run
`/create-pr`, or loop `/review-code``/make-a-plan`
`/implement-plan` until the findings are addressed, then push and
`/create-pr`. Nothing pushes for you — you always push from your shell.
> Note: `/implement-plan` checks the current branch. On a base branch
> (`main`, `develop`, `staging`) it creates a GitHub issue and a branch
> `issue-NNNN`; on an existing feature branch it continues there and
> creates nothing. The pre-run summary tells you which applies. Read the
> skill at `.agents/skills/implement-plan/SKILL.md` — it is
> self-explanatory.
### Big feature with multiple plans
When the work is too large for a single plan, tell `/make-a-plan`
up front: produce a high-level roadmap where each task will get its
own execution plan, and the roadmap doubles as the progress tracker.
From there the flow mirrors the issue flow above, one level down:
take each roadmap task in turn, write its own plan (`/make-a-plan`,
delegating when it helps), review it when the task is complex
(`/review-plan`), implement it (`/implement-plan`), and mark progress
on the roadmap as you land each piece.
## 7. Connecting `gh` CLI with a token
The `create-issue` and `create-pr` flows need an authenticated `gh`
so they can run on their own. Create a fine-grained token with the
minimum scopes:
1. GitHub → Settings → Developer settings → Personal access tokens →
Fine-grained tokens → Generate new token.
2. Under Organization permissions, grant access to **Projects**.
3. Under Repository permissions, grant at least **Issues** and
**Pull requests**.
Then authenticate the CLI and follow the prompts:
```bash
gh auth login
```
Verify with `gh auth status` (token lives in
`~/.config/gh/hosts.yml`). You still push from your own shell — the
agents only read and open issues and PRs.
## 8. Troubleshooting / FAQ
> TBD — filled in step by step as issues come up.
## 9. Advanced usage
### Personal agents and prompts without committing them here
Bind-mount a host dir over the container's `~/.config/opencode`:
```bash
./manage.sh run-devenv --ws 0 --opencode-config-dir ../penpot-opencode
```
It applies at container creation, so changing it needs a stop + rerun
of that instance.
## Summary of available skills
### How the skills are organized
**Flows** are the six skills you invoke by name. Each one covers one step
in the life of a change: plan it, review the plan, implement it, review
@@ -28,7 +400,7 @@ issue, a commit. Flows call them, but they also work on their own.
**Utilities** are small helpers for everyday work: search, file lookup,
JSON, REPL access, and so on.
## Flows
### Flows
| Skill | What it does | When you would say |
|---|---|---|
@@ -39,14 +411,14 @@ JSON, REPL access, and so on.
| [`create-pr`](skills/create-pr/SKILL.md) | Opens a pull request for the current branch — with checks on base branch, commits, issue, and push state — or updates an existing PR's title and description. | "open a PR for this branch" |
| [`resolve-git-conflicts`](skills/resolve-git-conflicts/SKILL.md) | Untangles merge or rebase conflicts: explains both sides, proposes a resolution, applies it after you approve. Never runs `git rebase --continue`. | "resolve these conflicts" |
## References
### References
| Skill | What it holds |
|---|---|
| [`plan-review-criteria`](skills/plan-review-criteria/SKILL.md) | The plan review rubric: six axes, severity levels, approval standard, output format. The `review-plan` reviewer loads it. |
| [`code-review-criteria`](skills/code-review-criteria/SKILL.md) | The code review rubric: five axes, core principles (DRY, KISS, YAGNI), severity format, verdict. The `review-code` reviewer loads it. |
## Procedures
### Procedures
| Skill | What it does |
|---|---|
@@ -54,7 +426,7 @@ JSON, REPL access, and so on.
| [`create-issue`](skills/create-issue/SKILL.md) | Creates a GitHub issue that follows Penpot conventions. Used by `implement-plan`; also works on its own. |
| [`create-commit`](skills/create-commit/SKILL.md) | Makes a commit the Penpot way: emoji subject, clear body, `AI-assisted-by` trailer. Used by `implement-plan`; also works alone when you say "commit this". |
## Utilities
### Utilities
| Skill | What it does |
|---|---|
@@ -71,7 +443,7 @@ JSON, REPL access, and so on.
| [`refine-prompt`](skills/refine-prompt/SKILL.md) | Rewrites a rough prompt into a clearer one. Never runs the prompt. |
| [`update-changelog`](skills/update-changelog/SKILL.md) | Regenerates `CHANGES.md` from a GitHub milestone. |
## A typical round
### A typical round
1. `/make-a-plan` — you get a plan and a saved file in `.agents/plans/`.
2. `/review-plan` — a second opinion; approve or request changes.
@@ -82,7 +454,7 @@ JSON, REPL access, and so on.
Every step also works on its own, and you can always say what you want
in plain words — the agents pick the right skill from what you say.
## Adding or changing a skill
### Adding or changing a skill
Create a folder here with a `SKILL.md` inside. The file needs `name` and
`description` in its frontmatter, and a clear "When to use" section so
+15
View File
@@ -0,0 +1,15 @@
Act as a senior full-stack software engineer for this project.
## Instructions
1. Read `AGENTS.md` first and follow its memory-reading rules: read `mem:critical-info`, then the core memory of every module your work touches, plus any deeper memories they reference.
2. Work autonomously: explore the codebase first, follow existing patterns and conventions, apply DRY/KISS.
3. Verify before finishing: run tests, lint and fm, fix anything you broke. Never report done with failing checks.
4. Before finishing, review the affected memories and documentation against the implementation. If the change introduces behavior, contracts, decisions, or constraints that are not documented, or makes existing documentation inaccurate, update the relevant memories and docs in the same change.
## Strong Rules
1. All new functionality ships with tests. No exceptions.
2. Do not touch unrelated modules.
3. Never `git push`, force-push, or modify remotes. Only create commits when the
command or the user explicitly instructs it.
+20 -2
View File
@@ -20,6 +20,17 @@ Before drafting any commit, read `mem:workflow/creating-commits` end-to-end. It
is the authoritative source for the commit message format, the emoji menu,
subject/body limits, and the `AI-assisted-by` trailer. Follow it exactly.
## Iron Rules (non-negotiable)
1. **Wrap every body line at 76 characters or fewer.** Count characters, do
not eyeball. Exceptions: `Signed-off-by:` / `AI-assisted-by:` trailers and
lines carrying a URL. This is the rule agents skip most often.
2. **Subject ≤70 chars**, imperative, capitalized, no trailing period.
3. **Blank line between subject and body.**
4. **Run `./scripts/check-commit` and require exit code 0.** It mechanically
checks rules 13. A non-zero exit is a hard blocker: fix the message and
re-commit. Never report the commit as done with a failing checker.
## Workflow
1. **Stage the files** specified by the calling context. Do not ask for
@@ -29,12 +40,18 @@ subject/body limits, and the `AI-assisted-by` trailer. Follow it exactly.
that does not match the stated intent, **STOP** and tell the user before
committing.
3. Draft the message following the format in the memory doc, wrapping the body
at 72 characters per line, and run:
at 76 characters per line, and run:
```bash
git commit -m "<subject>" -m "<body>"
```
(or `git commit -F -` if the body has unusual characters).
4. The `AI-assisted-by` trailer value is provided by the calling context — use
4. **Verify the message with the checker**:
```bash
./scripts/check-commit
```
If it fails, amend the message (`git commit --amend`) until it passes. Do
not finish with a failing checker.
5. The `AI-assisted-by` trailer value is provided by the calling context — use
it verbatim.
## Constraints
@@ -45,3 +62,4 @@ subject/body limits, and the `AI-assisted-by` trailer. Follow it exactly.
- Do not amend a commit you did not create in this session, unless explicitly asked.
- Do not bypass pre-commit hooks (`--no-verify`) unless explicitly asked.
- Do not add untracked files that were not created in this session.
- Do not skip the `scripts/check-commit` verification step (Iron Rule 4).
+1 -1
View File
@@ -6,7 +6,7 @@ on:
jobs:
build-and-push:
name: Build and push DevEnv Docker image
runs-on: penpot-extended-runner
runs-on: penpot-standar-runner
steps:
- name: Set common environment variables
+4 -4
View File
@@ -46,7 +46,7 @@ jobs:
# ── 1. Resolve the build key and check the whole set at once ───────────
prepare:
name: Prepare
runs-on: penpot-extended-runner
runs-on: penpot-standar-runner
timeout-minutes: 15
outputs:
gh_ref: ${{ steps.vars.outputs.gh_ref }}
@@ -135,7 +135,7 @@ jobs:
# ── 2. One build per image, in parallel, only when needed ──────────────
build:
name: Build ${{ matrix.image }}
runs-on: penpot-extended-runner
runs-on: penpot-standar-runner
timeout-minutes: 60
needs: prepare
if: needs.prepare.outputs.exists == 'false'
@@ -248,7 +248,7 @@ jobs:
# the S3 marker guarantees the branch tags were already moved.
promote:
name: Promote image set
runs-on: penpot-extended-runner
runs-on: penpot-standar-runner
timeout-minutes: 10
needs: [prepare, build]
@@ -302,7 +302,7 @@ jobs:
# ── 4. Single failure notification for the whole workflow ─────────────
notify:
name: Notify failure
runs-on: penpot-extended-runner
runs-on: penpot-standar-runner
timeout-minutes: 5
needs: [prepare, build, promote]
if: failure()
+1 -1
View File
@@ -46,7 +46,7 @@ jobs:
notify:
name: Notifications
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
needs:
- build-docker
- build-docker-admin-console
+1 -1
View File
@@ -19,7 +19,7 @@ permissions:
jobs:
release:
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
outputs:
version: ${{ steps.vars.outputs.gh_ref }}
release_notes: ${{ steps.extract_release_notes.outputs.release_notes }}
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
test-exporter:
if: ${{ !github.event.pull_request.draft }}
name: "Exporter Tests"
runs-on: penpot-runner-02
runs-on: penpot-extended-runner
container:
image: penpotapp/devenv:latest
volumes:
+1 -1
View File
@@ -11,7 +11,7 @@ You are working on the GitHub project `penpot/penpot`, a monorepo.
# Development workflow
- Commit/PR/issue creation is **on explicit request only**. Before any of these actions, read the relevant memory — don't infer format from prior examples:
- Before `git commit``mem:workflow/creating-commits` (subject format, body, `AI-assisted-by: model-name` trailer)
- Before `git commit``mem:workflow/creating-commits` (subject/body format, 76-char body wrapping enforced by `scripts/check-commit`, `AI-assisted-by: model-name` trailer)
- Before `gh issue create``mem:workflow/creating-issues` (title derivation, body template, labels, Issue Type)
- Before `gh pr create` / `gh pr edit``mem:workflow/creating-prs` (title format, body structure, "Note:" line)
- Before a repo-wide pnpm version update → `mem:workflow/updating-pnpm` (workspace
+22 -2
View File
@@ -14,12 +14,32 @@ automatically pull the identity from the local git config `user.name` and `user.
:emoji: Subject line (imperative, capitalized, no period, <=70 chars)
Body explaining what changed and why.
Wrap lines at 72 characters — git log and tooling
render long lines poorly. Keep each line concise.
Wrap lines at 76 characters — git log adds a
four-space indent, so 76 + 4 fits an 80-column
terminal. Keep each line concise.
AI-assisted-by: model-name
```
## HARD RULES (inexcusable)
These rules are not advisory. Do not commit until every one holds. A commit
that breaks them is wrong, even if the code is right.
- **Body lines MUST wrap at 76 characters or fewer.** Measure every line; do
not eyeball it. This is the rule most often skipped. Rationale: `git log`
indents the body four spaces, so 76 + 4 fits an 80-column terminal.
- **Subject MUST be ≤70 chars**, imperative, capitalized, no trailing period.
- **MUST be a blank line** between subject and body.
- **MUST run `scripts/check-commit` and get exit code 0 before finishing.**
It mechanically validates the rules above; a failing run is a blocker.
- It checks `HEAD` by default: `./scripts/check-commit`
- For another commit: `./scripts/check-commit -c <ref>`
- **NEVER** hand-wave the body as "one long line". If a line exceeds 76,
break it at a space.
- Exceptions inside the body (do not wrap these): `Signed-off-by:`,
`Co-authored-by:`, `AI-assisted-by:` trailers, and lines carrying a URL.
**AI-assisted-by trailer rules:**
- Use only the model name, e.g. `mimo-v2.5`, `deepseek-v4-flash`
- Do NOT add prefixes like `opencode-go/` — use the bare model name
+3
View File
@@ -17,6 +17,9 @@
- **`.claude/skills` is a symlink to `.agents/skills`.**
Edit skills only in their canonical location (`.agents/skills`); never edit
through `.claude/skills`.
- **Commit message body lines MUST wrap at ≤76 chars** (subject ≤70 chars) and
the commit MUST pass `./scripts/check-commit` with exit code 0 before you
consider it done. This is mechanically checked — do not eyeball it.
- **Read the workflow memory BEFORE the corresponding action**:
- Before `git commit``mem:workflow/creating-commits` (commit format, AI-assisted-by trailer)
- Before `gh issue create``mem:workflow/creating-issues` (title derivation, body template, Issue Type)
+3
View File
@@ -188,8 +188,11 @@ Commit messages must follow this format:
- Add clear and concise description on the body
- Do not end the subject with a period
- Keep the subject to **70 characters** or fewer
- **Wrap body lines at 76 characters or fewer** (trailers and URLs excepted)
- Separate the subject from the body with a **blank line**
You can check a commit against these rules with `./scripts/check-commit`.
### Examples
```
+1 -1
View File
@@ -27,7 +27,7 @@ export PENPOT_MEDIA_PROCESSING_SERVICE_URI=http://localhost:6065
export PENPOT_FLAGS="\
$PENPOT_FLAGS \
enable-login-with-password \
disable-login-with-ldap \
enable-login-with-ldap \
disable-login-with-oidc \
disable-login-with-google \
disable-login-with-github \
+24 -6
View File
@@ -10,7 +10,7 @@
[app.common.logging :as l]
[app.common.schema :as sm]
[clj-ldap.client :as ldap]
[clojure.string]
[cuerdas.core :as str]
[integrant.core :as ig]))
(defn- prepare-params
@@ -36,11 +36,22 @@
:cause cause))))
(defn- replace-several [s & {:as replacements}]
(reduce-kv clojure.string/replace s replacements))
(reduce-kv str/replace s replacements))
(defn- escape-ldap-filter-value
"Escapes special characters in a string for use in LDAP filter values,
per RFC 4515 section 3."
[s]
(-> s
(str/replace "\\" "\\5c")
(str/replace "*" "\\2a")
(str/replace "(" "\\28")
(str/replace ")" "\\29")
(str/replace "\u0000" "\\00")))
(defn- search-user
[{:keys [::conn base-dn] :as cfg} email]
(let [query (replace-several (:query cfg) ":username" email)
(let [query (replace-several (:query cfg) ":username" (escape-ldap-filter-value email))
attrs [(:attrs-username cfg)
(:attrs-email cfg)
(:attrs-fullname cfg)]
@@ -49,12 +60,19 @@
:attributes attrs}]
(first (ldap/search conn base-dn params))))
(defn- get-attr
"Retrieves an attribute from an LDAP entry. Handles multi-valued
attributes by returning the first value."
[entry attr-key]
(let [v (get entry attr-key)]
(if (coll? v) (first v) v)))
(defn- retrieve-user
[{:keys [::conn] :as cfg} {:keys [email password]}]
(when-let [{:keys [dn] :as user} (search-user cfg email)]
(when (ldap/bind? conn dn password)
{:fullname (get user (-> cfg :attrs-fullname keyword))
:email email
{:fullname (get-attr user (-> cfg :attrs-fullname keyword))
:email (get-attr user (-> cfg :attrs-email keyword))
:backend "ldap"})))
(def ^:private schema:info-data
@@ -79,7 +97,7 @@
(l/warn :hint "invalid response from ldap, looks like ldap is not configured correctly" :data user)
(ex/raise :type :restriction
:code :wrong-ldap-response
:explain explain)))
::sm/explain explain)))
user)))
(defn- try-connectivity
+2
View File
@@ -91,6 +91,7 @@
:quotes-upload-sessions-per-profile 5
:quotes-upload-chunks-per-session 20
:upload-max-chunk-size (* 1024 1024 30) ; 30MiB
;; SSRF protection
:ssrf-allowed-hosts #{}
@@ -202,6 +203,7 @@
[:quotes-team-access-requests-per-requester {:optional true} ::sm/int]
[:quotes-upload-sessions-per-profile {:optional true} ::sm/int]
[:quotes-upload-chunks-per-session {:optional true} ::sm/int]
[:upload-max-chunk-size {:optional true} ::sm/int]
[:quotes-media-storage-bytes-per-team {:optional true} ::sm/int]
[:auth-token-cookie-name {:optional true} :string]
+7 -1
View File
@@ -60,7 +60,13 @@
(defmethod handle-error :restriction
[err request _]
(let [{:keys [code] :as data} (ex-data err)]
(let [data (ex-data err)
code (get data :code)
explain (ex/explain data)
data (-> data
(dissoc ::sm/explain)
(cond-> explain (assoc :explain explain)))]
(if (= code :method-not-allowed)
{::yres/status 405
::yres/body data}
+14 -6
View File
@@ -390,18 +390,26 @@
(def ^:private sql:file-comment-users
"WITH available_profiles AS (
SELECT DISTINCT owner_id AS id
FROM comment
WHERE thread_id IN (SELECT id FROM comment_thread WHERE file_id=?)
SELECT DISTINCT c.owner_id AS id
FROM comment c
JOIN comment_thread ct
ON ct.id = c.thread_id
WHERE ct.file_id = ?::uuid
),
profile_ids AS (
SELECT id FROM available_profiles
UNION
SELECT ?::uuid
)
SELECT p.id,
p.email,
p.fullname AS name,
p.fullname AS fullname,
p.fullname,
p.photo_id,
p.is_active
FROM profile AS p
WHERE p.id IN (SELECT id FROM available_profiles) OR p.id=?")
FROM profile p
JOIN profile_ids AS x
ON x.id = p.id;")
(defn get-file-comments-users
[conn file-id profile-id]
+63 -26
View File
@@ -339,6 +339,9 @@
;; --- Chunked Upload: Upload a single chunk
(declare ^:private get-upload-chunk)
(declare ^:private check-upload-chunk-slot)
(def ^:private schema:upload-chunk
[:map {:title "upload-chunk"}
[:session-id ::sm/uuid]
@@ -354,9 +357,31 @@
{::doc/added "2.17"
::sm/params schema:upload-chunk
::sm/result schema:upload-chunk-result}
[{:keys [::db/pool] :as cfg}
{:keys [::rpc/profile-id session-id index content] :as _params}]
(let [session (db/get pool :upload-session {:id session-id :profile-id profile-id})]
[cfg {:keys [::rpc/profile-id session-id index content]}]
(let [session (db/tx-run! cfg check-upload-chunk-slot session-id profile-id index content)]
(l/trc :hint "upload-chunk"
:session-id session-id
:chunk (str index "/" (:total-chunks session))
:size (:size content)
:path (:path content))
(let [storage (sto/resolve cfg)
data (sto/content (:path content))]
(sto/put-object! storage
{::sto/content data
::sto/deduplicate? false
::sto/touch true
:content-type (:mtype content)
:bucket sto/tempfile-bucket
:upload-id (str session-id)
:chunk-index index}))
{:session-id session-id
:index index}))
(defn- check-upload-chunk-slot
[{:keys [::db/conn]} session-id profile-id index content]
(let [session (db/get conn :upload-session {:id session-id :profile-id profile-id} {::db/for-update true})]
(when (or (neg? index) (>= index (:total-chunks session)))
(ex/raise :type :validation
:code :invalid-chunk-index
@@ -365,26 +390,23 @@
:total-chunks (:total-chunks session)
:index index))
(when (> (:size content) (cf/get :upload-max-chunk-size))
(ex/raise :type :validation
:code :chunk-too-large
:hint "chunk size exceeds the maximum allowed"
:session-id session-id
:index index
:size (:size content)
:max-size (cf/get :upload-max-chunk-size)))
(l/trc :hint "upload-chunk"
:session-id session-id
:chunk (str index "/" (:total-chunks session))
:size (:size content)
:path (:path content)))
(when (get-upload-chunk conn session-id index)
(ex/raise :type :validation
:code :duplicate-chunk-index
:hint "chunk index already uploaded for this session"
:session-id session-id
:index index))
(let [storage (sto/resolve cfg)
data (sto/content (:path content))]
(sto/put-object! storage
{::sto/content data
::sto/deduplicate? false
::sto/touch true
:content-type (:mtype content)
:bucket sto/tempfile-bucket
:upload-id (str session-id)
:chunk-index index}))
{:session-id session-id
:index index})
session))
;; --- Chunked Upload: shared helpers
@@ -399,6 +421,18 @@
[conn session-id]
(db/exec! conn [sql:get-upload-chunks (str session-id)]))
(def ^:private sql:get-upload-chunk
"SELECT id
FROM storage_object
WHERE (metadata->>'~:upload-id') = ?::text
AND (metadata->>'~:chunk-index')::integer = ?
AND deleted_at IS NULL
LIMIT 1")
(defn- get-upload-chunk
[conn session-id index]
(db/exec-one! conn [sql:get-upload-chunk (str session-id) index]))
(defn- concat-chunks
"Reads all chunk storage objects in order and writes them to a single
temporary file on the local filesystem. Returns a path to that file."
@@ -417,18 +451,21 @@
conforming to `media.v/schema:upload` with `:filename`, `:path` and
`:size`.
Raises a :validation/:missing-chunks error when the number of stored
chunks does not match `:total-chunks` recorded in the session row.
Raises a :validation/:missing-chunks error when the stored chunk
indices do not form exactly the `0..total-chunks` range recorded in
the session row (wrong count, gaps or duplicates).
Raises :not-found when the session does not belong to `profile-id`.
Deletes the session row from `upload_session` on success."
[{:keys [::db/conn] :as cfg} profile-id session-id]
(let [session (db/get conn :upload-session {:id session-id :profile-id profile-id})
chunks (get-upload-chunks conn session-id)]
chunks (get-upload-chunks conn session-id)
indices (sort (map :chunk-index chunks))]
(when (not= (count chunks) (:total-chunks session))
(when (or (not= (count chunks) (:total-chunks session))
(not= indices (range (:total-chunks session))))
(ex/raise :type :validation
:code :missing-chunks
:hint "number of stored chunks does not match expected total"
:hint "stored chunks do not match expected total"
:session-id session-id
:expected (:total-chunks session)
:found (count chunks)))
@@ -0,0 +1,76 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS INC Sucursal en España SL
(ns backend-tests.auth-ldap-test
(:require
[app.auth.ldap :as ldap-auth]
[clj-ldap.client :as ldap]
[clojure.test :as t]))
;; --- search-user: filter must be escaped (RED: currently not escaped)
(t/deftest search-user-escapes-email-in-filter
(t/testing "wildcard * is escaped before building LDAP filter"
(let [captured-query (atom nil)
fake-search (fn [_conn _base-dn params]
(reset! captured-query (:filter params))
[])]
(with-redefs [ldap/search fake-search]
(#'ldap-auth/search-user {:query "(mail=:username)" :sizelimit 1
:attrs-username "uid" :attrs-email "mail"
:attrs-fullname "cn"}
"fry*@planetexpress.com"))
;; After fix: * should be escaped as \2a
(t/is (= "(mail=fry\\2a@planetexpress.com)" @captured-query)
"filter must have * escaped per RFC 4515"))))
;; --- retrieve-user: email must come from directory, not client (RED)
(t/deftest retrieve-user-uses-directory-email
(t/testing "returned email is from LDAP directory, not client input"
(let [fake-search (fn [_conn _base-dn _params]
[{:dn "cn=fry,ou=people,dc=planetexpress,dc=com"
:mail "fry@planetexpress.com"
:cn "Philip J. Fry"
:uid "fry"}])
fake-bind? (fn [_conn _dn _password] true)]
(with-redefs [ldap/search fake-search
ldap/bind? fake-bind?]
(let [cfg {:query "(mail=:username)" :sizelimit 1
:attrs-username "uid" :attrs-email "mail"
:attrs-fullname "cn"}
result (#'ldap-auth/retrieve-user cfg {:email "fry*@planetexpress.com" :password "fry"})]
;; After fix: email should be from directory (fry@planetexpress.com)
;; BUG: email is client input (fry*@planetexpress.com)
(t/is (= "fry@planetexpress.com" (:email result))
"email must come from LDAP directory attribute, not client input"))))))
;; --- authenticate: full flow with directory email (RED)
(t/deftest authenticate-returns-directory-email
(t/testing "authenticate returns directory email for profile"
(let [fake-search (fn [_conn _base-dn _params]
[{:dn "cn=amy,ou=people,dc=planetexpress,dc=com"
:mail "amy@planetexpress.com"
:cn "Amy Wong"
:uid "amy"}])
fake-bind? (fn [_conn _dn _password] true)]
(with-redefs [ldap/search fake-search
ldap/bind? fake-bind?
ldap/connect (fn [_cfg] (reify java.lang.AutoCloseable (close [_] nil)))]
(let [cfg {:query "(mail=:username)" :sizelimit 1
:attrs-username "uid" :attrs-email "mail"
:attrs-fullname "cn"
:bind-dn "cn=admin,dc=planetexpress,dc=com"
:bind-password "GoodNewsEveryone"
:host "localhost" :port 10389
:ssl false :tls false
:base-dn "ou=people,dc=planetexpress,dc=com"}
result (ldap-auth/authenticate cfg {:email "*@planetexpress.com" :password "amy"})]
;; After fix: email should be amy@planetexpress.com (directory)
;; BUG: email is *@planetexpress.com (client)
(t/is (= "amy@planetexpress.com" (:email result))
"authenticate must return directory email, not client-supplied wildcard"))))))
@@ -681,6 +681,131 @@
(t/is (= :validation (-> out :error ex-data :type)))
(t/is (= :missing-chunks (-> out :error ex-data :code))))))
(t/deftest chunked-upload-assemble-rejects-duplicate-indices
;; assemble-chunks must validate the index SET, not just the count: a
;; session declaring 2 chunks but storing [0,0] must fail instead of
;; assembling a corrupt file. Chunks are written at the storage level
;; because upload-chunk itself now rejects the second index.
(let [prof (th/create-profile* 1)
_ (th/create-project* 1 {:profile-id (:id prof)
:team-id (:default-team-id prof)})
file (th/create-file* 1 {:profile-id (:id prof)
:project-id (:default-project-id prof)
:is-shared false})
session-id (create-session! prof 2)
storage (:app.storage/storage th/*system*)
source-path (th/tempfile "backend_tests/test_files/sample.jpg")
chunks (split-file-into-chunks source-path 312043)
put-chunk! (fn [idx]
(let [mfile (make-chunk-mfile (first chunks) "image/jpeg")]
(sto/put-object! storage
{::sto/content (sto/content (:path mfile))
::sto/deduplicate? false
::sto/touch true
:content-type "image/jpeg"
:bucket sto/tempfile-bucket
:upload-id (str session-id)
:chunk-index idx})))]
(put-chunk! 0)
(put-chunk! 0)
(let [out (th/command! {::th/type :assemble-file-media-object
::rpc/profile-id (:id prof)
:session-id session-id
:file-id (:id file)
:is-local true
:name "dupe-indices"
:mtype "image/jpeg"})]
(t/is (some? (:error out)))
(t/is (= :validation (-> out :error ex-data :type)))
(t/is (= :missing-chunks (-> out :error ex-data :code))))))
(t/deftest chunked-upload-duplicate-then-assemble
;; A rejected duplicate must leave the first chunk intact: upload 0,
;; re-upload 0 (rejected), then assemble succeeds with the original size.
(let [prof (th/create-profile* 1)
_ (th/create-project* 1 {:profile-id (:id prof)
:team-id (:default-team-id prof)})
file (th/create-file* 1 {:profile-id (:id prof)
:project-id (:default-project-id prof)
:is-shared false})
session-id (create-session! prof 1)
source-path (th/tempfile "backend_tests/test_files/sample.jpg")
chunks (split-file-into-chunks source-path 312043)
mtype "image/jpeg"
size (alength (first chunks))]
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 0
:content (make-chunk-mfile (first chunks) mtype)})]
(t/is (nil? (:error out))))
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 0
:content (make-chunk-mfile (first chunks) mtype)})]
(t/is (some? (:error out)))
(t/is (= :duplicate-chunk-index (-> out :error ex-data :code))))
(let [out (th/command! {::th/type :assemble-file-media-object
::rpc/profile-id (:id prof)
:session-id session-id
:file-id (:id file)
:is-local true
:name "after-dupe"
:mtype mtype})]
(t/is (nil? (:error out)))
(let [storage (:app.storage/storage th/*system*)
mobj (sto/get-object storage (:media-id (:result out)))]
(t/is (= size (:size mobj)))))))
(t/deftest chunked-upload-rejected-duplicate-keeps-session-usable
;; Rejecting a duplicate must not poison the session: the remaining
;; distinct indices still accumulate and assemble normally.
(let [prof (th/create-profile* 1)
_ (th/create-project* 1 {:profile-id (:id prof)
:team-id (:default-team-id prof)})
file (th/create-file* 1 {:profile-id (:id prof)
:project-id (:default-project-id prof)
:is-shared false})
session-id (create-session! prof 2)
source-path (th/tempfile "backend_tests/test_files/sample.jpg")
chunks (split-file-into-chunks source-path 110000)
mtype "image/jpeg"]
(t/is (= 3 (count chunks)))
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 0
:content (make-chunk-mfile (nth chunks 0) mtype)})]
(t/is (nil? (:error out))))
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 0
:content (make-chunk-mfile (nth chunks 0) mtype)})]
(t/is (some? (:error out)))
(t/is (= :duplicate-chunk-index (-> out :error ex-data :code))))
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 1
:content (make-chunk-mfile (nth chunks 1) mtype)})]
(t/is (nil? (:error out))))
;; The live store holds exactly the two distinct indices: the
;; rejected duplicate stored nothing.
(let [rows (th/db-exec! ["SELECT (metadata->>'~:chunk-index')::integer AS idx FROM storage_object WHERE (metadata->>'~:upload-id') = ?::text AND deleted_at IS NULL ORDER BY idx"
(str session-id)])]
(t/is (= [0 1] (mapv :idx rows))))))
(t/deftest chunked-upload-session-not-found
(let [prof (th/create-profile* 1)
_ (th/create-project* 1 {:profile-id (:id prof)
@@ -767,6 +892,77 @@
(t/is (= :validation (-> out :error ex-data :type)))
(t/is (= :invalid-chunk-index (-> out :error ex-data :code))))))
(t/deftest chunked-upload-duplicate-index-rejected
;; Uploading the same chunk index twice into one session must fail:
;; the second call raises :validation / :duplicate-chunk-index and
;; stores nothing, so one session+index keeps at most one object.
(let [prof (th/create-profile* 1)
session-id (create-session! prof 1)
source-path (th/tempfile "backend_tests/test_files/sample.jpg")
chunks (split-file-into-chunks source-path 312043)
mtype "image/jpeg"
mfile1 (make-chunk-mfile (first chunks) mtype)
mfile2 (make-chunk-mfile (first chunks) mtype)]
;; First upload succeeds
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 0
:content mfile1})]
(t/is (nil? (:error out))))
;; Second upload of the same index must be rejected
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 0
:content mfile2})]
(t/is (some? (:error out)))
(t/is (= :validation (-> out :error ex-data :type)))
(t/is (= :duplicate-chunk-index (-> out :error ex-data :code))))
;; Exactly one live object stored for that session/index
(let [rows (th/db-exec! ["SELECT id FROM storage_object WHERE (metadata->>'~:upload-id') = ?::text AND (metadata->>'~:chunk-index') = '0' AND deleted_at IS NULL"
(str session-id)])]
(t/is (= 1 (count rows))))))
(t/deftest chunked-upload-chunk-too-large
;; Chunks larger than the configured cap must be rejected with
;; :validation / :chunk-too-large before anything is stored, while a
;; chunk exactly at the cap still uploads fine.
(with-mocks [mock {:target 'app.config/get
:return (th/config-get-mock
{:upload-max-chunk-size 1024})}]
(let [prof (th/create-profile* 1)
session-id (create-session! prof 1)
source-path (th/tempfile "backend_tests/test_files/sample.jpg")
chunks (split-file-into-chunks source-path 312043)
mtype "image/jpeg"]
;; 312043 bytes exceeds the mocked 1024-byte cap: rejected
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 0
:content (make-chunk-mfile (first chunks) mtype)})]
(t/is (some? (:error out)))
(t/is (= :validation (-> out :error ex-data :type)))
(t/is (= :chunk-too-large (-> out :error ex-data :code))))
;; Nothing stored for the rejected chunk
(let [rows (th/db-exec! ["SELECT id FROM storage_object WHERE (metadata->>'~:upload-id') = ?::text AND deleted_at IS NULL"
(str session-id)])]
(t/is (= 0 (count rows))))
;; A chunk exactly at the cap still uploads fine
(let [out (th/command! {::th/type :upload-chunk
::rpc/profile-id (:id prof)
:session-id session-id
:index 0
:content (make-chunk-mfile (byte-array 1024 (byte 1)) mtype)})]
(t/is (nil? (:error out)))))))
(t/deftest chunked-upload-sessions-per-profile-quota
;; With the session limit set to 2, creating a third session for the
;; same profile must fail with :restriction / :max-quote-reached.
+106
View File
@@ -0,0 +1,106 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { rpcPost, extractCookie } from "./helpers/client.mjs";
async function loginWithLdap(email, password) {
const res = await rpcPost("login-with-ldap", { email, password });
if (res.status !== 200 || res.body.type) {
throw new Error(
`LDAP login failed: ${JSON.stringify(res.body)}`
);
}
const cookie = extractCookie(res.setCookie);
return { profile: res.body, cookie };
}
describe("LDAP injection — T5-N1-03", () => {
it("normal LDAP login works with valid credentials", async () => {
const { profile, cookie } = await loginWithLdap(
"fry@planetexpress.com",
"fry"
);
assert.equal(profile.email, "fry@planetexpress.com");
assert.ok(profile.id, "profile should have id");
assert.ok(cookie, "cookie should be set");
});
it("wildcard injection: *@planetexpress.com must not return client literal as email", async () => {
// ATTACK SCENARIO (from Criptored audit):
// 1. Attacker (amy) sends email="*@planetexpress.com" with her own password
// 2. LDAP filter becomes (mail=*@planetexpress.com) — * is a wildcard
// 3. With sizelimit=1, LDAP returns amy's entry (first match)
// 4. Bind succeeds: amy's DN + amy's password = valid
//
// EXPECTED BEHAVIOR AFTER FIX (two valid outcomes):
// A) If * is escaped: LDAP finds no match → wrong-credentials (injection blocked)
// B) If * matches: profile email must be "amy@planetexpress.com" (directory), not "*@planetexpress.com" (client)
//
// Either outcome is correct — the vulnerability is fixed.
try {
const { profile } = await loginWithLdap("*@planetexpress.com", "amy");
// Outcome B: login succeeded, verify email is from directory
assert.equal(
profile.email,
"amy@planetexpress.com",
"email must come from LDAP directory, not client input"
);
} catch (e) {
// Outcome A: injection blocked — * is escaped, no LDAP match
assert.ok(
e.message.includes("wrong-credentials"),
"wildcard should be rejected or return directory email"
);
}
});
it("identity swap: alternate email must return primary directory email", async () => {
// Professor has two emails in LDAP: professor@ and hubert@.
// Login with hubert@ — the profile email should be the one
// the LDAP directory returns as attrs-email, not what the client typed.
//
// EXPECTED BEHAVIOR AFTER FIX:
// Profile email should be "professor@planetexpress.com" (primary directory email),
// NOT "hubert@planetexpress.com" (client literal).
//
// CURRENT BUG: email is "hubert@planetexpress.com" (client literal) — test FAILS
const { profile, cookie } = await loginWithLdap(
"hubert@planetexpress.com",
"professor"
);
assert.ok(profile.id, "profile should have id");
assert.ok(cookie, "cookie should be set");
// This assertion FAILS with current code (RED) — proves the vulnerability
assert.equal(
profile.email,
"professor@planetexpress.com",
"email must come from LDAP directory, not client input"
);
});
it("wrong password fails", async () => {
try {
await loginWithLdap("fry@planetexpress.com", "wrong-password");
assert.fail("should have thrown");
} catch (e) {
assert.ok(
e.message.includes("LDAP login failed") ||
e.message.includes("wrong-credentials"),
"should fail with wrong credentials"
);
}
});
it("non-existent user fails", async () => {
try {
await loginWithLdap("nobody@planetexpress.com", "password");
assert.fail("should have thrown");
} catch (e) {
assert.ok(
e.message.includes("LDAP login failed") ||
e.message.includes("wrong-credentials"),
"should fail for non-existent user"
);
}
});
});
@@ -712,14 +712,21 @@
(conj (or interactions []) interaction))
(defn remove-interaction
"Interactions without the one at `index`; unchanged when `index` addresses none."
[interactions index]
(let [interactions (or interactions [])]
(into (subvec interactions 0 index)
(subvec interactions (inc index)))))
(if (and (int? index) (< -1 index (count interactions)))
(into (subvec interactions 0 index)
(subvec interactions (inc index)))
interactions)))
(defn update-interaction
"Interactions with `update-fn` applied at `index`; unchanged when `index`
addresses none."
[interactions index update-fn]
(update interactions index update-fn))
(if (and (int? index) (< -1 index (count interactions)))
(update interactions index update-fn)
interactions))
(defn remap-interactions
"Update all interactions whose destination points to a shape in the
@@ -858,7 +858,20 @@
(t/testing "Update interaction"
(let [new-interactions (ctsi/update-interaction interactions 1 #(ctsi/set-action-type % :open-url))]
(t/is (= (count new-interactions) 2))
(t/is (= (:action-type (last new-interactions)) :open-url))))))
(t/is (= (:action-type (last new-interactions)) :open-url))))
(t/testing "Remove interaction with an index out of range"
(t/is (= interactions (ctsi/remove-interaction interactions 2)))
(t/is (= interactions (ctsi/remove-interaction interactions -1)))
(t/is (= interactions (ctsi/remove-interaction interactions nil)))
(t/is (= [] (ctsi/remove-interaction nil 0))))
(t/testing "Update interaction with an index out of range"
(let [update-fn #(ctsi/set-action-type % :open-url)]
(t/is (= interactions (ctsi/update-interaction interactions 2 update-fn)))
(t/is (= interactions (ctsi/update-interaction interactions -1 update-fn)))
(t/is (= interactions (ctsi/update-interaction interactions nil update-fn)))
(t/is (nil? (ctsi/update-interaction nil 0 update-fn)))))))
(t/deftest remap-interactions
@@ -0,0 +1,484 @@
{
"~:features": {
"~#set": [
"fdata/path-data",
"plugins/runtime",
"design-tokens/v1",
"variants/v1",
"layout/grid",
"styles/v2",
"fdata/pointer-map",
"fdata/objects-map",
"render-wasm/v1",
"components/v2",
"fdata/shape-data-type"
]
},
"~:team-id": "~u04868522-3ebf-81e8-8006-306b0c9b5f59",
"~:permissions": {
"~:type": "~:membership",
"~:is-owner": true,
"~:is-admin": true,
"~:can-edit": true,
"~:can-read": true,
"~:is-logged": true
},
"~:has-media-trimmed": false,
"~:comment-thread-seqn": 0,
"~:name": "Text: Custom Fonts",
"~:revn": 13,
"~:modified-at": "~m1750151641034",
"~:vern": 0,
"~:id": "~u434b0541-fa2f-802f-8006-6a827d964a9b",
"~:is-shared": false,
"~:migrations": {
"~#ordered-set": [
"legacy-2",
"legacy-3",
"legacy-5",
"legacy-6",
"legacy-7",
"legacy-8",
"legacy-9",
"legacy-10",
"legacy-11",
"legacy-12",
"legacy-13",
"legacy-14",
"legacy-16",
"legacy-17",
"legacy-18",
"legacy-19",
"legacy-25",
"legacy-26",
"legacy-27",
"legacy-28",
"legacy-29",
"legacy-31",
"legacy-32",
"legacy-33",
"legacy-34",
"legacy-36",
"legacy-37",
"legacy-38",
"legacy-39",
"legacy-40",
"legacy-41",
"legacy-42",
"legacy-43",
"legacy-44",
"legacy-45",
"legacy-46",
"legacy-47",
"legacy-48",
"legacy-49",
"legacy-50",
"legacy-51",
"legacy-52",
"legacy-53",
"legacy-54",
"legacy-55",
"legacy-56",
"legacy-57",
"legacy-59",
"legacy-62",
"legacy-65",
"legacy-66",
"legacy-67",
"0001-remove-tokens-from-groups",
"0002-normalize-bool-content",
"0002-clean-shape-interactions",
"0003-fix-root-shape",
"0003-convert-path-content",
"0004-clean-shadow-and-colors",
"0005-deprecate-image-type",
"0006-fix-old-texts-fills",
"0007-clear-invalid-strokes-and-fills-v2",
"0008-fix-library-colors-opacity",
"0009-add-partial-text-touched-flags"
]
},
"~:version": 67,
"~:project-id": "~u53a7ff09-2228-81d3-8006-4b5ea964593b",
"~:created-at": "~m1750081311326",
"~:data": {
"~:pages": ["~u434b0541-fa2f-802f-8006-6a827d964a9c"],
"~:pages-index": {
"~u434b0541-fa2f-802f-8006-6a827d964a9c": {
"~:objects": {
"~u00000000-0000-0000-0000-000000000000": {
"~#shape": {
"~:y": 0,
"~:hide-fill-on-export": false,
"~:transform": {
"~#matrix": {
"~:a": 1.0,
"~:b": 0.0,
"~:c": 0.0,
"~:d": 1.0,
"~:e": 0.0,
"~:f": 0.0
}
},
"~:rotation": 0,
"~:name": "Root Frame",
"~:width": 0.01,
"~:type": "~:frame",
"~:points": [
{
"~#point": {
"~:x": 0.0,
"~:y": 0.0
}
},
{
"~#point": {
"~:x": 0.01,
"~:y": 0.0
}
},
{
"~#point": {
"~:x": 0.01,
"~:y": 0.01
}
},
{
"~#point": {
"~:x": 0.0,
"~:y": 0.01
}
}
],
"~:r2": 0,
"~:proportion-lock": false,
"~:transform-inverse": {
"~#matrix": {
"~:a": 1.0,
"~:b": 0.0,
"~:c": 0.0,
"~:d": 1.0,
"~:e": 0.0,
"~:f": 0.0
}
},
"~:r3": 0,
"~:r1": 0,
"~:id": "~u00000000-0000-0000-0000-000000000000",
"~:parent-id": "~u00000000-0000-0000-0000-000000000000",
"~:frame-id": "~u00000000-0000-0000-0000-000000000000",
"~:strokes": [],
"~:x": 0,
"~:proportion": 1.0,
"~:r4": 0,
"~:selrect": {
"~#rect": {
"~:x": 0,
"~:y": 0,
"~:width": 0.01,
"~:height": 0.01,
"~:x1": 0,
"~:y1": 0,
"~:x2": 0.01,
"~:y2": 0.01
}
},
"~:fills": [
{
"~:fill-color": "#FFFFFF",
"~:fill-opacity": 1
}
],
"~:flip-x": null,
"~:height": 0.01,
"~:flip-y": null,
"~:shapes": [
"~u7d85a63e-18e7-809f-8006-6a827fe8501e",
"~u7d85a63e-18e7-809f-8006-6a833ef5fcef"
]
}
},
"~u7d85a63e-18e7-809f-8006-6a827fe8501e": {
"~#shape": {
"~:y": 451.9999962296588,
"~:transform": {
"~#matrix": {
"~:a": 1.0,
"~:b": 0.0,
"~:c": 0.0,
"~:d": 1.0,
"~:e": 0.0,
"~:f": 0.0
}
},
"~:rotation": 0,
"~:grow-type": "~:auto-width",
"~:content": {
"~:type": "root",
"~:key": "xgmgu1frox",
"~:children": [
{
"~:type": "paragraph-set",
"~:children": [
{
"~:line-height": "1.2",
"~:font-style": "normal",
"~:children": [
{
"~:line-height": "",
"~:font-style": "normal",
"~:typography-ref-id": null,
"~:text-transform": "none",
"~:font-id": "gfont-rufina",
"~:key": "ee7vl7klqs",
"~:font-size": "72",
"~:font-weight": "400",
"~:typography-ref-file": null,
"~:font-variant-id": "normal-400",
"~:text-decoration": "none",
"~:letter-spacing": "0",
"~:fills": [
{
"~:fill-color": "#000000",
"~:fill-opacity": 1
}
],
"~:font-family": "\"Rufina\"",
"~:text": "Text multiple selection one"
}
],
"~:typography-ref-id": null,
"~:text-transform": "none",
"~:text-align": "center",
"~:font-id": "gfont-rufina",
"~:key": "17bt2f4evfs",
"~:font-size": "72",
"~:font-weight": "400",
"~:typography-ref-file": null,
"~:text-direction": "ltr",
"~:type": "paragraph",
"~:font-variant-id": "normal-400",
"~:text-decoration": "none",
"~:letter-spacing": "0",
"~:fills": [
{
"~:fill-color": "#000000",
"~:fill-opacity": 1
}
],
"~:font-family": "\"Rufina\""
}
]
}
],
"~:vertical-align": "top"
},
"~:hide-in-viewer": false,
"~:name": "Text multiple selection one",
"~:width": 403.99995992417394,
"~:type": "~:text",
"~:points": [
{
"~#point": {
"~:x": 744.0000211580308,
"~:y": 451.9999962296588
}
},
{
"~#point": {
"~:x": 1147.9999810822046,
"~:y": 451.9999962296588
}
},
{
"~#point": {
"~:x": 1147.9999810822046,
"~:y": 537.9999971833331
}
},
{
"~#point": {
"~:x": 744.0000211580308,
"~:y": 537.9999971833331
}
}
],
"~:transform-inverse": {
"~#matrix": {
"~:a": 1.0,
"~:b": 0.0,
"~:c": 0.0,
"~:d": 1.0,
"~:e": 0.0,
"~:f": 0.0
}
},
"~:id": "~u7d85a63e-18e7-809f-8006-6a827fe8501e",
"~:parent-id": "~u00000000-0000-0000-0000-000000000000",
"~:frame-id": "~u00000000-0000-0000-0000-000000000000",
"~:x": 744.0000211580307,
"~:selrect": {
"~#rect": {
"~:x": 744.0000211580307,
"~:y": 451.9999962296588,
"~:width": 403.99995992417394,
"~:height": 86.00000095367432,
"~:x1": 744.0000211580307,
"~:y1": 451.9999962296588,
"~:x2": 1147.9999810822046,
"~:y2": 537.9999971833331
}
},
"~:flip-x": null,
"~:height": 86.00000095367432,
"~:flip-y": null
}
},
"~u7d85a63e-18e7-809f-8006-6a833ef5fcef": {
"~#shape": {
"~:y": 537.9999971833331,
"~:transform": {
"~#matrix": {
"~:a": 1.0,
"~:b": 0.0,
"~:c": 0.0,
"~:d": 1.0,
"~:e": 0.0,
"~:f": 0.0
}
},
"~:rotation": 0,
"~:grow-type": "~:auto-width",
"~:content": {
"~:type": "root",
"~:key": "xgmgu1frox",
"~:children": [
{
"~:type": "paragraph-set",
"~:children": [
{
"~:line-height": "1.2",
"~:font-style": "normal",
"~:children": [
{
"~:line-height": "",
"~:font-style": "normal",
"~:typography-ref-id": null,
"~:text-transform": "none",
"~:font-id": "gfont-rufina",
"~:key": "ee7vl7klqs",
"~:font-size": "36",
"~:font-weight": "500",
"~:typography-ref-file": null,
"~:font-variant-id": "normal-500",
"~:text-decoration": "none",
"~:letter-spacing": "0",
"~:fills": [
{
"~:fill-color": "#000000",
"~:fill-opacity": 1
}
],
"~:font-family": "\"Rufina\"",
"~:text": "Second text, same font"
}
],
"~:typography-ref-id": null,
"~:text-transform": "none",
"~:text-align": "center",
"~:font-id": "gfont-rufina",
"~:key": "17bt2f4evfs",
"~:font-size": "0",
"~:font-weight": "500",
"~:typography-ref-file": null,
"~:text-direction": "ltr",
"~:type": "paragraph",
"~:font-variant-id": "normal-500",
"~:text-decoration": "none",
"~:letter-spacing": "0",
"~:fills": [
{
"~:fill-color": "#000000",
"~:fill-opacity": 1
}
],
"~:font-family": "\"Rufina\""
}
]
}
],
"~:vertical-align": "top"
},
"~:hide-in-viewer": false,
"~:name": "Text multiple selection two",
"~:width": 466.0000131576671,
"~:type": "~:text",
"~:points": [
{
"~#point": {
"~:x": 712.9999941849438,
"~:y": 537.9999971833331
}
},
{
"~#point": {
"~:x": 1179.0000073426108,
"~:y": 537.9999971833331
}
},
{
"~#point": {
"~:x": 1179.0000073426108,
"~:y": 580.9999976601703
}
},
{
"~#point": {
"~:x": 712.9999941849438,
"~:y": 580.9999976601703
}
}
],
"~:transform-inverse": {
"~#matrix": {
"~:a": 1.0,
"~:b": 0.0,
"~:c": 0.0,
"~:d": 1.0,
"~:e": 0.0,
"~:f": 0.0
}
},
"~:id": "~u7d85a63e-18e7-809f-8006-6a833ef5fcef",
"~:parent-id": "~u00000000-0000-0000-0000-000000000000",
"~:frame-id": "~u00000000-0000-0000-0000-000000000000",
"~:x": 712.9999941849437,
"~:selrect": {
"~#rect": {
"~:x": 712.9999941849437,
"~:y": 537.9999971833331,
"~:width": 466.0000131576671,
"~:height": 43.00000047683716,
"~:x1": 712.9999941849437,
"~:y1": 537.9999971833331,
"~:x2": 1179.0000073426108,
"~:y2": 580.9999976601703
}
},
"~:flip-x": null,
"~:height": 43.00000047683716,
"~:flip-y": null
}
}
},
"~:id": "~u434b0541-fa2f-802f-8006-6a827d964a9c",
"~:name": "Page 1"
}
},
"~:id": "~u434b0541-fa2f-802f-8006-6a827d964a9b",
"~:options": {
"~:components-v2": true,
"~:base-font-size": "16px"
}
}
}
@@ -0,0 +1,201 @@
import { test, expect } from "@playwright/test";
import { WorkspacePage } from "../pages/WorkspacePage";
import { WasmWorkspacePage } from "../pages/WasmWorkspacePage";
// ---------------------------------------------------------------------------
// The "Create typography style" button (workspace.options.convert-to-typography)
// in the text options sidebar is only shown when ALL of these hold for the
// selected text shape(s) (src/app/main/ui/workspace/sidebar/options/menus/text.cljs):
// (and (some? font) (not typography) (not multiple?) (not applied-token-name))
// Each test below isolates one condition that must independently hide it:
// - font missing (font-id not registered in app.main.fonts/fontsdb)
// - a typography asset is applied (typography-ref-id set)
// - multiple shapes are selected with differing attributes
// - a typography design token is applied (applied-tokens :typography)
// ---------------------------------------------------------------------------
function convertToTypographyButton(workspace) {
return workspace.rightSidebar.getByRole("button", {
name: "Create typography style",
});
}
test.describe("font missing", () => {
// Fixture render-wasm/get-file-text-custom-fonts.json has a text shape
// ("Penpot & Dragons") using a custom team font-id and no typography/token
// applied - otherwise exactly the state that reveals the button once its
// font resolves. Toggling the get-font-variants mock between "the team owns
// this font" and "empty" simulates the font being present vs. missing.
const FILE = {
id: "434b0541-fa2f-802f-8006-59827d964a9b",
pageId: "434b0541-fa2f-802f-8006-59827d964a9c",
};
test.beforeEach(async ({ page }) => {
await WorkspacePage.init(page);
});
test("Create typography style button is hidden when the shape font is missing", async ({
page,
}) => {
const workspace = new WorkspacePage(page);
await workspace.setupEmptyFile();
await workspace.mockRPC(
/get\-file\?/,
"render-wasm/get-file-text-custom-fonts.json",
);
// The team does not own the shape's custom font, so it can't be resolved.
await workspace.mockRPC(
"get-font-variants?team-id=*",
"workspace/get-font-variants-empty.json",
);
await workspace.goToWorkspace({ fileId: FILE.id, pageId: FILE.pageId });
await workspace.clickLeafLayer("Penpot & Dragons");
await expect(convertToTypographyButton(workspace)).not.toBeVisible();
});
test("Create typography style button is visible once the shape font resolves", async ({
page,
}) => {
const workspace = new WorkspacePage(page);
await workspace.setupEmptyFile();
await workspace.mockRPC(
/get\-file\?/,
"render-wasm/get-file-text-custom-fonts.json",
);
// The team owns the shape's custom font, so it resolves normally.
await workspace.mockRPC(
"get-font-variants?team-id=*",
"render-wasm/get-font-variants-custom-fonts.json",
);
await workspace.goToWorkspace({ fileId: FILE.id, pageId: FILE.pageId });
await workspace.clickLeafLayer("Penpot & Dragons");
await expect(convertToTypographyButton(workspace)).toBeVisible();
});
});
test.describe("typography asset applied", () => {
// multiselection-typography.json: "Text with typography asset one" has a
// typography-ref-id pointing at an in-file typography asset (font
// gfont-agdasima, a built-in Google font that resolves with no extra
// mocking), and is not multi-selected or token-applied.
const FILE = {
id: "1062e0a0-8fe0-80ae-8007-e70b4993f5ef",
pageId: "1062e0a0-8fe0-80ae-8007-e70b4993f5f0",
};
test.beforeEach(async ({ page }) => {
await WorkspacePage.init(page);
});
test("Create typography style button is hidden when a typography asset is applied", async ({
page,
}) => {
const workspace = new WorkspacePage(page);
await workspace.setupEmptyFile();
await workspace.mockRPC(
/get\-file\?/,
"workspace/multiselection-typography.json",
);
await workspace.goToWorkspace({ fileId: FILE.id, pageId: FILE.pageId });
await workspace.clickLeafLayer("Text with typography asset one");
// Sanity check: the text options panel did render for this shape - the
// button is specifically hidden by the applied typography, not because
// the whole panel failed to show up.
await expect(
workspace.rightSidebar.getByRole("region", { name: "Text section" }),
).toBeVisible();
await expect(convertToTypographyButton(workspace)).not.toBeVisible();
});
});
test.describe("multiple selection", () => {
// get-file-text-multiple-selection.json has two text shapes sharing the
// same (resolvable, built-in) font-id but differing font-size, with no
// typography or token applied - so selecting both together isolates
// `multiple?` becoming true without also making the font unresolved.
const FILE = {
id: "434b0541-fa2f-802f-8006-6a827d964a9b",
pageId: "434b0541-fa2f-802f-8006-6a827d964a9c",
};
test.beforeEach(async ({ page }) => {
await WorkspacePage.init(page);
});
test("Create typography style button is hidden when multiple shapes with different values are selected", async ({
page,
}) => {
const workspace = new WorkspacePage(page);
await workspace.setupEmptyFile();
await workspace.mockRPC(
/get\-file\?/,
"workspace/get-file-text-multiple-selection.json",
);
await workspace.goToWorkspace({ fileId: FILE.id, pageId: FILE.pageId });
await workspace.clickLeafLayer("Text multiple selection one");
await expect(convertToTypographyButton(workspace)).toBeVisible();
await workspace.clickLeafLayer("Text multiple selection two", {
modifiers: ["Shift"],
});
await expect(convertToTypographyButton(workspace)).not.toBeVisible();
});
});
test.describe("typography token applied", () => {
// get-file-token-tooltip.json: "Text with token" has a typography design
// token applied (applied-tokens :typography) using font gfont-arizonia (a
// built-in Google font that resolves with no extra mocking).
test.beforeEach(async ({ page }) => {
await WasmWorkspacePage.init(page);
await WasmWorkspacePage.mockRPC(page, "get-teams", "get-teams-tokens.json");
});
test("Create typography style button is hidden when a typography token is applied", async ({
page,
}) => {
const workspace = new WasmWorkspacePage(page);
await workspace.mockConfigFlags(["enable-feature-token-input"]);
await workspace.setupEmptyFile();
await workspace.mockRPC("get-team?id=*", "workspace/get-team-tokens.json");
await workspace.mockRPC(
/get\-file\?/,
"workspace/get-file-token-tooltip.json",
);
await workspace.mockRPC(
/get\-file\-fragment\?/,
"workspace/get-file-fragment-tokens.json",
);
await workspace.mockRPC(
"update-file?id=*",
"workspace/update-file-create-rect.json",
);
await workspace.goToWorkspace({
fileId: "c7ce0794-0992-8105-8004-38f280443849",
pageId: "4530574a-7a0a-807b-8008-0107b2c4628e",
});
await page.getByRole("tab", { name: "Layers" }).click();
await workspace.layers
.getByTestId("layer-row")
.filter({ hasText: "Text with token" })
.click();
// Sanity check: the text options panel did render for this shape - the
// button is specifically hidden by the applied token, not because the
// whole panel failed to show up.
await expect(
workspace.rightSidebar.getByRole("region", { name: "Text section" }),
).toBeVisible();
await expect(convertToTypographyButton(workspace)).not.toBeVisible();
});
});
+2 -2
View File
@@ -158,7 +158,7 @@
[:div {:class (stl/css :modal-content)}
[:div {:class (stl/css :modal-header)}
[:h1 {:class (stl/css :modal-title)}
"Advanced permissions: An Admin Panel to rule them all"]]
"An Admin Panel to rule them all"]]
[:div {:class (stl/css :feature)}
[:p {:class (stl/css :feature-content)}
@@ -190,7 +190,7 @@
[:div {:class (stl/css :modal-content)}
[:div {:class (stl/css :modal-header)}
[:h1 {:class (stl/css :modal-title)}
"Advanced permissions: Penpot Enterprise billing"]]
"Penpot Enterprise billing"]]
[:div {:class (stl/css :feature)}
[:p {:class (stl/css :feature-content)}
@@ -20,6 +20,7 @@
[app.main.data.workspace.undo :as dwu]
[app.main.data.workspace.wasm-text :as dwwt]
[app.main.features :as features]
[app.main.fonts :as fonts]
[app.main.refs :as refs]
[app.main.store :as st]
[app.main.ui.components.title-bar :refer [title-bar*]]
@@ -307,6 +308,11 @@
main-menu-open? (:main-menu menu-state)
more-options-open? (:more-options menu-state)
font-id (or (:font-id values) (:font-id txt/default-typography))
fonts (mf/deref fonts/fontsdb)
font (get fonts font-id)
token-dropdown-open* (mf/use-state false)
token-dropdown-open? (deref token-dropdown-open*)
@@ -512,7 +518,7 @@
:on-click toggle-token-dropdown
:tooltip-placement "top-left"
:icon i/tokens}])
(when (and (not typography) (not multiple?) (not applied-token-name))
(when (and (some? font) (not typography) (not multiple?) (not applied-token-name))
[:> icon-button* {:variant "ghost"
:aria-label (tr "workspace.options.convert-to-typography")
:on-click on-convert-to-typography
+91 -74
View File
@@ -80,89 +80,102 @@
(obj/type-of? p "InteractionProxy"))
(defn interaction-proxy
[plugin-id file-id page-id shape-id index]
(obj/reify {:name "InteractionProxy"}
:$plugin {:enumerable false :get (fn [] plugin-id)}
:$file {:enumerable false :get (fn [] file-id)}
:$page {:enumerable false :get (fn [] page-id)}
:$shape {:enumerable false :get (fn [] shape-id)}
:$index {:enumerable false :get (fn [] index)}
"Proxy over one interaction of a shape.
;; Not enumerable so we don't have an infinite loop
:shape
{:enumerable false
:get (fn [] (shape-proxy plugin-id file-id page-id shape-id))}
Interactions are addressed by position, which shifts as interactions are added
or removed, so the position is resolved on each access from `interaction`,
kept up to date with the writes made through the proxy."
[plugin-id file-id page-id shape-id interaction index]
(let [current (atom interaction)
locate-index (fn [] (u/locate-interaction-index file-id page-id shape-id @current index))]
(obj/reify {:name "InteractionProxy"}
:$plugin {:enumerable false :get (fn [] plugin-id)}
:$file {:enumerable false :get (fn [] file-id)}
:$page {:enumerable false :get (fn [] page-id)}
:$shape {:enumerable false :get (fn [] shape-id)}
:$index {:enumerable false :get locate-index}
:trigger
{:this true
:get #(-> % u/proxy->interaction :event-type format/format-key)
:set
(fn [_ value]
(let [value (parser/parse-keyword value)]
;; Not enumerable so we don't have an infinite loop
:shape
{:enumerable false
:get (fn [] (shape-proxy plugin-id file-id page-id shape-id))}
:trigger
{:this true
:get #(-> % u/proxy->interaction :event-type format/format-key)
:set
(fn [_ value]
(let [value (parser/parse-keyword value)]
(cond
(not (contains? ctsi/event-types value))
(u/not-valid plugin-id :trigger value)
(not (r/check-permission plugin-id "content:write"))
(u/not-valid plugin-id :trigger "Plugin doesn't have 'content:write' permission")
:else
(do
(st/emit! (dwi/update-interaction
(u/locate-shape file-id page-id shape-id)
(locate-index)
#(assoc % :event-type value)
{:page-id page-id}))
(swap! current assoc :event-type value)))))}
:delay
{:this true
:get #(-> % u/proxy->interaction :delay)
:set
(fn [_ value]
(cond
(not (contains? ctsi/event-types value))
(u/not-valid plugin-id :trigger value)
(or (not (sm/valid-safe-int? value)) (neg? value))
(u/not-valid plugin-id :delay value)
(not (r/check-permission plugin-id "content:write"))
(u/not-valid plugin-id :trigger "Plugin doesn't have 'content:write' permission")
(u/not-valid plugin-id :delay "Plugin doesn't have 'content:write' permission")
:else
(st/emit! (dwi/update-interaction
(u/locate-shape file-id page-id shape-id)
index
#(assoc % :event-type value)
{:page-id page-id})))))}
(do
(st/emit! (dwi/update-interaction
(u/locate-shape file-id page-id shape-id)
(locate-index)
#(assoc % :delay value)
{:page-id page-id}))
(swap! current assoc :delay value))))}
:delay
{:this true
:get #(-> % u/proxy->interaction :delay)
:set
(fn [_ value]
(cond
(or (not (sm/valid-safe-int? value)) (neg? value))
(u/not-valid plugin-id :delay value)
:action
{:this true
:get #(-> % u/proxy->interaction (format/format-action plugin-id file-id page-id))
:set
(fn [self value]
(let [params (parser/parse-action value)
interaction
(-> (u/proxy->interaction self)
(d/patch-object params))]
(cond
(not (sm/validate ctsi/schema:interaction interaction))
(u/not-valid plugin-id :action interaction)
(not (r/check-permission plugin-id "content:write"))
(u/not-valid plugin-id :delay "Plugin doesn't have 'content:write' permission")
(not (r/check-permission plugin-id "content:write"))
(u/not-valid plugin-id :action "Plugin doesn't have 'content:write' permission")
:else
(st/emit! (dwi/update-interaction
(u/locate-shape file-id page-id shape-id)
index
#(assoc % :delay value)
{:page-id page-id}))))}
:else
(do
(st/emit! (dwi/update-interaction
(u/locate-shape file-id page-id shape-id)
(locate-index)
#(d/patch-object % params)
{:page-id page-id}))
(reset! current interaction)))))}
:action
{:this true
:get #(-> % u/proxy->interaction (format/format-action plugin-id file-id page-id))
:set
(fn [self value]
(let [params (parser/parse-action value)
interaction
(-> (u/proxy->interaction self)
(d/patch-object params))]
(cond
(not (sm/validate ctsi/schema:interaction interaction))
(u/not-valid plugin-id :action interaction)
:remove
(fn []
(cond
(not (r/check-permission plugin-id "content:write"))
(u/not-valid plugin-id :remove "Plugin doesn't have 'content:write' permission")
(not (r/check-permission plugin-id "content:write"))
(u/not-valid plugin-id :action "Plugin doesn't have 'content:write' permission")
:else
(st/emit! (dwi/update-interaction
(u/locate-shape file-id page-id shape-id)
index
#(d/patch-object % params)
{:page-id page-id})))))}
:remove
(fn []
(cond
(not (r/check-permission plugin-id "content:write"))
(u/not-valid plugin-id :remove "Plugin doesn't have 'content:write' permission")
:else
(st/emit! (dwi/remove-interaction {:id shape-id} index))))))
:else
(st/emit! (dwi/remove-interaction {:id shape-id} (locate-index))))))))
(def lib-typography-proxy? nil)
(def lib-component-proxy nil)
@@ -980,8 +993,9 @@
(fn [self]
(let [interactions (-> self u/proxy->shape :interactions)]
(format/format-array
#(interaction-proxy plugin-id file-id page-id id %)
(range 0 (count interactions)))))}
(fn [[index interaction]]
(interaction-proxy plugin-id file-id page-id id interaction index))
(d/enumerate interactions))))}
;; Methods
:resize
@@ -1626,7 +1640,7 @@
(st/emit!
(dwi/add-interaction page-id id interaction)
(se/event plugin-id "add-interaction"))
(interaction-proxy plugin-id file-id page-id id index)))))
(interaction-proxy plugin-id file-id page-id id interaction index)))))
:removeInteraction
(fn [interaction]
@@ -1637,6 +1651,9 @@
(not (r/check-permission plugin-id "content:write"))
(u/not-valid plugin-id :removeInteraction "Plugin doesn't have 'content:write' permission")
(not= id (obj/get interaction "$shape"))
(u/not-valid plugin-id :removeInteraction "The interaction doesn't belong to this shape")
:else
(st/emit!
(dwi/remove-interaction {:id id} (obj/get interaction "$index"))
+9
View File
@@ -206,6 +206,15 @@
(when-let [shape (locate-shape file-id page-id shape-id)]
(get-in shape [:interactions index])))
(defn locate-interaction-index
"Position of `interaction` within the shape's current interactions, falling
back to `index` while it addresses an existing interaction."
[file-id page-id shape-id interaction index]
(let [interactions (-> (locate-shape file-id page-id shape-id) :interactions)]
(or (d/index-of interactions interaction)
(when (and (int? index) (< -1 index (count interactions)))
index))))
(defn proxy->interaction
[proxy]
(let [file-id (obj/get proxy "$file")
+1 -1
View File
@@ -1770,7 +1770,7 @@ msgstr "At least 1 uppercase letter"
#: src/app/main/ui/settings/password.cljs, src/app/main/ui/auth/register.cljs
msgid "errors.weak-password.insufficient-digits"
msgstr "At least 1 digit"
msgstr "At least 1 number"
#: src/app/main/ui/settings/password.cljs, src/app/main/ui/auth/register.cljs
msgid "errors.weak-password.insufficient-special"
+1 -1
View File
@@ -1735,7 +1735,7 @@ msgstr "Al menos 1 letra mayúscula"
#: src/app/main/ui/settings/password.cljs, src/app/main/ui/auth/register.cljs
msgid "errors.weak-password.insufficient-digits"
msgstr "Al menos 1 dígito"
msgstr "Al menos 1 número"
#: src/app/main/ui/settings/password.cljs, src/app/main/ui/auth/register.cljs
msgid "errors.weak-password.insufficient-special"
+1 -1
View File
@@ -94,7 +94,7 @@ export class PluginBridge {
private readonly taskTimeoutSecs: number,
private readonly redisBridge?: RedisBridge
) {
this.wsServer = new WebSocketServer({ port: port, host: mcpServer.host });
this.wsServer = new WebSocketServer({ port: port });
this.setupWebSocketHandlers();
}
+2
View File
@@ -8,6 +8,8 @@
### 🩹 Fixes
- **plugins-runtime**: An interaction obtained from `Shape.interactions` now keeps addressing that interaction instead of the position it held when the array was read. Removing every interaction of a shape from a single read removes all of them rather than leaving some behind, and writing through a held interaction after an earlier one is removed no longer lands on a different interaction.
- **plugins-runtime**: `Shape.removeInteraction()` now rejects an interaction belonging to a different shape with a validation error, instead of removing whichever interaction sat at the same position on the target shape.
- **plugins-runtime**: `Library.createComponent()` now rejects invalid input (an empty shape list, or a shape inside a component copy) with a validation error instead of returning a component proxy pointing at nothing.
- **plugins-runtime**: Setting an individual padding/margin side (`leftPadding`, `topMargin`, …) now re-derives the padding/margin type, switching to `multiple` when the four sides stop being symmetric (so the value is actually painted) and back to `simple` once top/bottom and left/right are mirrored again.
@@ -349,6 +349,70 @@ describe('Interactions', () => {
expect(r.interactions.length).toBe(before - 1);
});
// Removing an interaction shifts the ones after it, so draining a shape from
// a single read of the array must reach every interaction it returned. Both
// removal entry points are covered.
test('every interaction can be removed from one read of the array', async (ctx) => {
const r = rect(ctx);
r.addInteraction('click', { type: 'open-url', url: 'https://a.example' });
await ctx.penpot.waitForLayoutUpdate();
r.addInteraction('mouse-enter', {
type: 'open-url',
url: 'https://b.example',
});
await ctx.penpot.waitForLayoutUpdate();
expect(r.interactions).toHaveLength(2);
for (const interaction of r.interactions) {
interaction.remove();
await ctx.penpot.waitForLayoutUpdate();
}
expect(r.interactions).toHaveLength(0);
});
test('removeInteraction can drain a shape from one read of the array', async (ctx) => {
const r = rect(ctx);
r.addInteraction('click', { type: 'open-url', url: 'https://a.example' });
await ctx.penpot.waitForLayoutUpdate();
r.addInteraction('mouse-enter', {
type: 'open-url',
url: 'https://b.example',
});
await ctx.penpot.waitForLayoutUpdate();
expect(r.interactions).toHaveLength(2);
for (const interaction of r.interactions) {
r.removeInteraction(interaction);
await ctx.penpot.waitForLayoutUpdate();
}
expect(r.interactions).toHaveLength(0);
});
// A held interaction addresses itself rather than a position, so a write
// reaches it even once an earlier interaction has shifted it.
test('an interaction still writes to itself after an earlier one is removed', async (ctx) => {
const r = rect(ctx);
for (const trigger of ['click', 'mouse-enter', 'mouse-leave'] as const) {
r.addInteraction(trigger, {
type: 'open-url',
url: `https://${trigger}.example`,
});
await ctx.penpot.waitForLayoutUpdate();
}
const [first, , last] = r.interactions;
first.remove();
await ctx.penpot.waitForLayoutUpdate();
last.delay = 500;
await ctx.penpot.waitForLayoutUpdate();
expect(r.interactions.map((i) => i.trigger)).toEqual([
'mouse-enter',
'mouse-leave',
]);
expect(r.interactions.map((i) => i.delay)).toEqual([null, 500]);
});
test('interaction trigger can be changed', (ctx) => {
const dest = board(ctx);
const r = rect(ctx);
+55 -4
View File
@@ -5,6 +5,7 @@ Check commit messages against Penpot's commit guidelines.
Validates commit messages using the rules defined in:
- .github/workflows/commit-checker.yml (regex pattern)
- CONTRIBUTING.md (formatting rules, subject length, DCO)
- .serena/memories/workflow/creating-commits.md (body wrapped at 76 chars)
By default, checks HEAD. Use --commit to specify a different commit.
@@ -38,6 +39,20 @@ COMMIT_PATTERN = re.compile(
MERGE_PATTERN = re.compile(r"^(Merge|Revert|Reapply).+[^.]$")
# ── Body line wrapping ───────────────────────────────────────────────────────
# Commit bodies must wrap at 76 characters (see
# .serena/memories/workflow/creating-commits.md). That leaves room for the
# four-space indent git log adds, fitting an 80-column terminal. Trailers and
# URLs are exempt: they cannot be wrapped without losing meaning.
MAX_BODY_LINE = 76
TRAILER_PATTERN = re.compile(
r"^(Signed-off-by|Co-authored-by|Co-developed-by|Reviewed-by|"
r"Acked-by|Tested-by|Reported-by|Suggested-by|AI-assisted-by):"
)
URL_PATTERN = re.compile(r"https?://\S+")
# ═══════════════════════════════════════════════════════════════════════════════
# Helpers
# ═══════════════════════════════════════════════════════════════════════════════
@@ -93,11 +108,11 @@ def check_regex(message):
def check_subject_length(message):
"""Subject line must be ≤ 90 characters."""
"""Subject line must be ≤ 70 characters."""
first_line = message.split("\n")[0]
if len(first_line) > 90:
if len(first_line) > 70:
return False, (
f"Subject line exceeds 90 characters ({len(first_line)} chars):\n"
f"Subject line exceeds 70 characters ({len(first_line)} chars):\n"
f" {first_line}"
)
return True, None
@@ -148,6 +163,41 @@ def check_body_blank_line(message):
return True, None
def check_body_line_length(message):
"""Body lines must wrap at 76 characters or fewer.
The subject (first line) has its own length rule. Trailers (e.g.
Signed-off-by) and lines carrying a URL are exempt, since wrapping them
would break tooling or lose information.
"""
lines = message.split("\n")
offenders = []
for line_number, line in enumerate(lines[1:], start=2):
if len(line) <= MAX_BODY_LINE:
continue
if TRAILER_PATTERN.match(line):
continue
if URL_PATTERN.search(line):
continue
# A long token with no whitespace before the limit cannot be wrapped.
if " " not in line[:MAX_BODY_LINE]:
continue
offenders.append((line_number, line))
if not offenders:
return True, None
details = "\n".join(
f" line {line_number} ({len(line)} chars): {line!r}"
for line_number, line in offenders
)
return False, (
f"Body lines must wrap at {MAX_BODY_LINE} characters or fewer. "
"Unwrapped line(s):\n" + details
)
def check_signed_off_by(message):
"""Check for the DCO Signed-off-by line (required for code changes)."""
if "Signed-off-by:" not in message:
@@ -179,10 +229,11 @@ def main():
validators = [
("Regex pattern", check_regex),
("Subject ≤ 90 chars", check_subject_length),
("Subject ≤ 70 chars", check_subject_length),
("No trailing period in subject", check_subject_no_trailing_dot),
("Subject capitalized", check_subject_capitalized),
("Blank line after subject", check_body_blank_line),
("Body wrapped at 76 chars", check_body_line_length),
]
all_ok = True
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python3
"""Tests for scripts/check-commit.
Run with:
python3 scripts/test_check_commit.py
Covers the body line-wrapping validator added to enforce the commit body
wrap rule documented in .serena/memories/workflow/creating-commits.md.
"""
import importlib.machinery
import importlib.util
import pathlib
import sys
import unittest
# Loading scripts/check-commit would otherwise emit scripts/__pycache__/.
sys.dont_write_bytecode = True
SCRIPT_PATH = pathlib.Path(__file__).resolve().parent / "check-commit"
def load_check_commit():
"""Load the extensionless scripts/check-commit as a module."""
loader = importlib.machinery.SourceFileLoader("check_commit", str(SCRIPT_PATH))
spec = importlib.util.spec_from_loader("check_commit", loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
check_commit = load_check_commit()
class BodyLineLengthTests(unittest.TestCase):
def assert_ok(self, message):
ok, error = check_commit.check_body_line_length(message)
self.assertTrue(ok, error)
self.assertIsNone(error)
def assert_fail(self, message):
ok, error = check_commit.check_body_line_length(message)
self.assertFalse(ok)
self.assertIsNotNone(error)
return error
def test_wrapped_body_passes(self):
message = (
":bug: Fix crash when opening the file menu\n"
"\n"
"The menu reused a stale reference after the file was\n"
"closed, which raised an exception on reopen.\n"
)
self.assert_ok(message)
def test_line_at_limit_passes(self):
line = "x " * 38 # 76 chars, breakable
self.assertEqual(len(line), 76)
self.assert_ok(":bug: Fix crash\n\n" + line + "\n")
def test_line_one_over_limit_fails(self):
line = "x " * 38 + "x" # 77 chars, breakable
self.assertEqual(len(line), 77)
error = self.assert_fail(":bug: Fix crash\n\n" + line + "\n")
self.assertIn("76", error)
def test_long_body_line_fails(self):
long_line = "word " * 20 # 100 chars, breakable
error = self.assert_fail(":bug: Fix crash\n\n" + long_line + "\n")
self.assertIn("76", error)
self.assertIn("line 3", error)
def test_subject_is_not_checked(self):
# The subject has its own length rule; the body validator ignores it.
subject = ":bug: " + "S" * 100
self.assert_ok(subject + "\n")
def test_url_line_passes(self):
line = (
"See https://github.com/penpot/penpot/issues/1234"
"/comments/very/long/fragment"
)
self.assert_ok(":books: Update docs\n\n" + line + "\n")
def test_trailer_passes(self):
line = "Signed-off-by: Someone With A Long Name <someone@example.com>"
self.assert_ok(":bug: Fix crash\n\nBody.\n\n" + line + "\n")
def test_unbreakable_token_passes(self):
line = "a" * 100 # no whitespace to wrap at
self.assert_ok(":bug: Fix crash\n\n" + line + "\n")
def test_blank_lines_are_ignored(self):
self.assert_ok(":bug: Fix crash\n\n\n\n")
def test_multiple_offenders_reported(self):
error = self.assert_fail(
":bug: Fix crash\n\n"
+ ("word " * 20)
+ "\n"
+ ("other " * 20)
+ "\n"
)
self.assertIn("line 3", error)
self.assertIn("line 4", error)
class SubjectRulesRegressionTests(unittest.TestCase):
"""Guard the pre-existing validators against accidental breakage."""
def test_valid_subject_passes_regex(self):
ok, error = check_commit.check_regex(":bug: Fix crash on startup")
self.assertTrue(ok, error)
def test_missing_emoji_fails_regex(self):
ok, _ = check_commit.check_regex("Fix crash on startup")
self.assertFalse(ok)
def test_trailing_dot_fails(self):
ok, _ = check_commit.check_subject_no_trailing_dot(":bug: Fix crash.")
self.assertFalse(ok)
def test_subject_at_70_chars_passes(self):
# ":bug: " is 6 chars, so 64 chars of text reach exactly 70.
ok, error = check_commit.check_subject_length(":bug: " + "S" * 64)
self.assertTrue(ok, error)
def test_subject_over_70_chars_fails(self):
ok, error = check_commit.check_subject_length(":bug: " + "S" * 65)
self.assertFalse(ok)
self.assertIn("70", error)
if __name__ == "__main__":
unittest.main(verbosity=2)