diff --git a/.github/zizmor.yml b/.github/zizmor.yml new file mode 100644 index 0000000000..cac6b29ce9 --- /dev/null +++ b/.github/zizmor.yml @@ -0,0 +1,7 @@ +rules: + excessive-permissions: + ignore: + # The existing Cloudron publisher grants packages:write at workflow level. + # Keep this exception scoped to that exact finding until permissions can + # be moved to the image build and manifest jobs. + - publish-image.yml:17 diff --git a/.mise.toml b/.mise.toml index d1671b012e..aacd2f1869 100644 --- a/.mise.toml +++ b/.mise.toml @@ -1,5 +1,27 @@ +min_version = "2026.7.5" + [settings] idiomatic_version_file_enable_tools = ["ruby"] +[tools] +gum = "0.17.0" + [env] PROMETHEUS_EXPORTER_URL = "http://127.0.0.1:9306/metrics" + +[bootstrap.packages] +# Arch +"pacman:imagemagick" = "latest" +"pacman:mariadb-libs" = "latest" +"pacman:openslide" = "latest" +"pacman:libvips" = "latest" +"pacman:libheif" = "latest" +"pacman:libwebp" = "latest" +"pacman:libjxl" = "latest" +"pacman:libraw" = "latest" +"pacman:poppler-glib" = "latest" +"pacman:libcgif" = "latest" +"pacman:ffmpeg" = "latest" +"pacman:rav1e" = "latest" +"pacman:svt-av1" = "latest" +"pacman:gitleaks" = "latest" diff --git a/.rubocop.yml b/.rubocop.yml index c0d945b705..f06669aabc 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -13,3 +13,8 @@ AllCops: - 'db/schema*.rb' - 'saas/db/migrate/**/*' - 'saas/db/saas_schema.rb' + +Style/NegatedIf: + Enabled: true +Style/NegatedUnless: + Enabled: true diff --git a/.ruby-version b/.ruby-version index 2aa5131992..7921bd0c89 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -3.4.7 +3.4.8 diff --git a/AGENTS.md b/AGENTS.md index 64c69151aa..f72ef659c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ bin/setup # Initial setup (installs gems, creates DB, loads schema) bin/dev # Start development server (runs on port 3006) ``` -Development URL: http://fizzy.localhost:3006 +Development URL: http://app.fizzy.localhost:3006 Login with: david@example.com (development fixtures), password will appear in the browser console ### Testing @@ -156,7 +156,7 @@ Allow people to move between OSS and SAAS Fizzy instances: ### Chrome MCP (Local Dev) -URL: `http://fizzy.localhost:3006` +URL: `http://app.fizzy.localhost:3006` Login: david@example.com (passwordless magic link auth - check rails console for link) Use Chrome MCP tools to interact with the running dev app for UI testing and debugging. diff --git a/Brewfile b/Brewfile new file mode 100644 index 0000000000..b175ae24c3 --- /dev/null +++ b/Brewfile @@ -0,0 +1,4 @@ +brew "imagemagick" +brew "openslide" +brew "vips" +brew "gitleaks" diff --git a/CHANGELOG b/CHANGELOG index 49e05d558e..835ba0f158 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,12 @@ This repository tracks Cloudron packaging changes for Fizzy. +## v1.2.5 + +- Sync Basecamp Fizzy through upstream commit `1476c215d` (2026-07-22). +- Upgrade the Cloudron image to Ruby 3.4.8 and align the package runtime with current upstream conventions. +- Adapt URL, logging, signup gating, and single-database integration to the current upstream runtime. + ## v1.2.4 - Corrective Cloudron package release to republish the supported `stable` and `v1.2.4` image tags. diff --git a/CloudronManifest.json b/CloudronManifest.json index c1b04d0907..650c3f5ce5 100644 --- a/CloudronManifest.json +++ b/CloudronManifest.json @@ -4,7 +4,7 @@ "author": "37signals", "description": "Fizzy is a collaborative kanban-style project management app for planning, discussing, and shipping work.", "tagline": "Plan, discuss, and deliver work together.", - "version": "1.2.4", + "version": "1.2.5", "website": "https://fizzy.do", "contactEmail": "patattzel@users.noreply.github.com", "forumUrl": "https://github.com/patattzel/fizzy-cloudron/issues", @@ -29,6 +29,6 @@ "mediaLinks": [ "https://raw.githubusercontent.com/patattzel/fizzy-cloudron/main/public/app-icon.png" ], - "changelog": "Corrective Cloudron release 1.2.4 republishing the supported stable and versioned package images", + "changelog": "Sync with Basecamp Fizzy through 1476c215d, upgrade Ruby to 3.4.8, and preserve Cloudron runtime compatibility", "postInstallMessage": "Fizzy is ready. Open the app URL to create the first account, then review docs/cloudron.md in this repository for runtime configuration and release details." } diff --git a/CloudronVersions.json b/CloudronVersions.json index 584e1d3e24..304f1d13fb 100644 --- a/CloudronVersions.json +++ b/CloudronVersions.json @@ -294,6 +294,48 @@ "creationDate": "Thu, 02 Apr 2026 20:16:03 GMT", "ts": "Thu, 02 Apr 2026 20:16:03 GMT", "publishState": "published" + }, + "1.2.5": { + "manifest": { + "id": "do.fizzy.cloudron", + "title": "Fizzy", + "author": "37signals", + "description": "Fizzy is a collaborative kanban-style project management app for planning, discussing, and shipping work.", + "tagline": "Plan, discuss, and deliver work together.", + "version": "1.2.5", + "website": "https://fizzy.do", + "contactEmail": "patattzel@users.noreply.github.com", + "forumUrl": "https://github.com/patattzel/fizzy-cloudron/issues", + "healthCheckPath": "/up", + "httpPort": 3000, + "documentationUrl": "https://github.com/patattzel/fizzy-cloudron/blob/main/docs/cloudron.md", + "dockerImage": "ghcr.io/patattzel/fizzy-cloudron:1.2.5", + "addons": { + "localstorage": {}, + "mysql": {}, + "sendmail": {} + }, + "manifestVersion": 2, + "memoryLimit": 2147483648, + "minBoxVersion": "9.1.0", + "icon": "public/app-icon.png", + "tags": [ + "project", + "notes", + "collaboration" + ], + "mediaLinks": [ + "https://raw.githubusercontent.com/patattzel/fizzy-cloudron/main/public/app-icon.png" + ], + "changelog": "Sync with Basecamp Fizzy through 1476c215d, upgrade Ruby to 3.4.8, and preserve Cloudron runtime compatibility", + "postInstallMessage": "Fizzy is ready. Open the app URL to create the first account, then review docs/cloudron.md in this repository for runtime configuration and release details.", + "iconUrl": "https://raw.githubusercontent.com/patattzel/fizzy-cloudron/main/public/app-icon.png", + "packagerName": "patattzel", + "packagerUrl": "https://github.com/patattzel/fizzy-cloudron" + }, + "creationDate": "Wed, 22 Jul 2026 21:39:27 GMT", + "ts": "Wed, 22 Jul 2026 21:39:27 GMT", + "publishState": "published" } } } diff --git a/DESCRIPTION.md b/DESCRIPTION.md index 43cb53a2e8..5ef6e0d689 100644 --- a/DESCRIPTION.md +++ b/DESCRIPTION.md @@ -1,3 +1,3 @@ # Fizzy for Cloudron -This package wraps Basecamp\s Fizzy for Cloudron. +This package wraps Basecamp’s Fizzy for Cloudron. diff --git a/Dockerfile b/Dockerfile index babd3b6d15..06d93df682 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ # For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html # Make sure RUBY_VERSION matches the Ruby version in .ruby-version -ARG RUBY_VERSION=3.4.7 +ARG RUBY_VERSION=3.4.8 FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base # Rails app lives here diff --git a/Dockerfile.cloudron b/Dockerfile.cloudron index 58425f6212..1a880b2753 100644 --- a/Dockerfile.cloudron +++ b/Dockerfile.cloudron @@ -1,8 +1,8 @@ # syntax=docker/dockerfile:1 # check=error=true -# Cloudron image for Fizzy -ARG RUBY_VERSION=3.4.7 +# Cloudron image for Fizzy. Keep this in sync with .ruby-version and Dockerfile. +ARG RUBY_VERSION=3.4.8 FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base WORKDIR /app/code @@ -50,6 +50,13 @@ RUN SECRET_KEY_BASE_DUMMY=1 DATABASE_ADAPTER=sqlite ./bin/rails assets:precompil # Final stage FROM base +# Image metadata +ARG OCI_DESCRIPTION +LABEL org.opencontainers.image.description="${OCI_DESCRIPTION}" +ARG OCI_SOURCE +LABEL org.opencontainers.image.source="${OCI_SOURCE}" +LABEL org.opencontainers.image.licenses="O'Saasy" + # Create Cloudron user but keep root to chown mounted volume at runtime; start.sh drops to cloudron via gosu. RUN groupadd --system --gid 8000 cloudron && \ useradd cloudron --uid 8000 --gid 8000 --create-home --shell /bin/bash diff --git a/Gemfile b/Gemfile index 6b012e96d5..a3b2a77c6c 100644 --- a/Gemfile +++ b/Gemfile @@ -13,13 +13,13 @@ gem "turbo-rails", github: "hotwired/turbo-rails", branch: "offline-cache" # Deployment and drivers gem "bootsnap", require: false gem "kamal", require: false -gem "puma", ">= 5.0" -gem "solid_cable", ">= 3.0" +gem "puma", "~> 7.2", ">= 7.2.1" +gem "solid_cable", github: "rails/solid_cable" gem "solid_cache", "~> 1.0" -gem "solid_queue", "~> 1.3" +gem "solid_queue", github: "rails/solid_queue" gem "sqlite3", ">= 2.0" gem "thruster", require: false -gem "trilogy", "~> 2.10" +gem "trilogy", "~> 2.12" # Features gem "bcrypt", "~> 3.1.22" @@ -27,7 +27,7 @@ gem "geared_pagination", "~> 1.2" gem "rqrcode" gem "rouge" gem "jbuilder" -gem "lexxy", "0.9.0.beta" +gem "lexxy", "0.9.23" gem "image_processing", "~> 1.14" gem "platform_agent" gem "aws-sdk-s3", require: false @@ -59,8 +59,9 @@ end group :test do gem "capybara" + gem "minitest-reporters", require: false + gem "mocha" gem "selenium-webdriver" - gem "webmock" gem "vcr" - gem "mocha" + gem "webmock" end diff --git a/Gemfile.lock b/Gemfile.lock index 354984d3cd..3623f6e513 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -15,7 +15,7 @@ GIT GIT remote: https://github.com/rails/rails.git - revision: 12e24eaf2f0a9613e015653f013dd131317d9bf5 + revision: 813301c1ca6a4a11ad2379ed50a57922bc76ae6d branch: main specs: actioncable (8.2.0.alpha) @@ -46,7 +46,7 @@ GIT rack-session (>= 1.0.1) rack-test (>= 0.6.3) rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) + rails-html-sanitizer (~> 1.7) useragent (~> 0.16) actiontext (8.2.0.alpha) action_text-trix (~> 2.1.16) @@ -61,7 +61,7 @@ GIT builder (~> 3.1) erubi (~> 1.11) rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) + rails-html-sanitizer (~> 1.7) activejob (8.2.0.alpha) activesupport (= 8.2.0.alpha) globalid (>= 0.3.6) @@ -115,6 +115,28 @@ GIT tsort (>= 0.2) zeitwerk (~> 2.6) +GIT + remote: https://github.com/rails/solid_cable.git + revision: c968ba777f990194596d035e6ba50e1ee677a09c + specs: + solid_cable (4.0.0) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + +GIT + remote: https://github.com/rails/solid_queue.git + revision: a8c89374b2b600f7306cb44059dce1cc3fc45cec + specs: + solid_queue (1.4.0) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + GIT remote: https://github.com/rails/web-console.git revision: 90e3474306f2367cfeaf2875e91e2bc2d71b5f0f @@ -129,13 +151,14 @@ GEM specs: action_text-trix (2.1.18) railties - addressable (2.8.9) + addressable (2.9.0) public_suffix (>= 2.0.2, < 8.0) + ansi (1.6.0) ast (2.4.3) autotuner (1.1.0) aws-eventstream (1.4.0) - aws-partitions (1.1229.0) - aws-sdk-core (3.244.0) + aws-partitions (1.1240.0) + aws-sdk-core (3.245.0) aws-eventstream (~> 1, >= 1.3.0) aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) @@ -146,8 +169,8 @@ GEM aws-sdk-kms (1.123.0) aws-sdk-core (~> 3, >= 3.244.0) aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.216.0) - aws-sdk-core (~> 3, >= 3.243.0) + aws-sdk-s3 (1.219.0) + aws-sdk-core (~> 3, >= 3.244.0) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) aws-sigv4 (1.12.1) @@ -156,9 +179,9 @@ GEM bcrypt (3.1.22) bcrypt_pbkdf (1.1.2) benchmark (0.5.0) - bigdecimal (4.1.0) + bigdecimal (4.1.2) bindex (0.8.1) - bootsnap (1.23.0) + bootsnap (1.24.5) msgpack (~> 1.2) brakeman (8.0.4) racc @@ -178,12 +201,12 @@ GEM childprocess (5.1.0) logger (~> 1.5) chunky_png (1.4.0) - concurrent-ruby (1.3.6) + concurrent-ruby (1.3.7) connection_pool (3.0.2) crack (1.0.1) bigdecimal rexml - crass (1.0.6) + crass (1.0.7) date (3.5.1) debug (1.11.1) irb (~> 1.10) @@ -191,11 +214,11 @@ GEM dotenv (3.2.0) drb (2.2.3) ed25519 (1.4.0) - erb (6.0.2) + erb (6.0.4) erubi (1.13.1) et-orbi (1.4.0) tzinfo - faker (3.6.1) + faker (3.8.0) i18n (>= 1.8.11, < 2) ffi (1.17.2-aarch64-linux-gnu) ffi (1.17.2-aarch64-linux-musl) @@ -211,10 +234,10 @@ GEM geared_pagination (1.2.0) activesupport (>= 5.0) addressable (>= 2.5.0) - globalid (1.3.0) + globalid (1.4.0) activesupport (>= 6.1) hashdiff (1.2.1) - i18n (1.14.8) + i18n (1.15.2) concurrent-ruby (~> 1.0) image_processing (1.14.0) mini_magick (>= 4.9.5, < 6) @@ -224,7 +247,7 @@ GEM activesupport (>= 6.0.0) railties (>= 6.0.0) io-console (0.8.2) - irb (1.17.0) + irb (1.18.0) pp (>= 0.6.0) prism (>= 1.3.0) rdoc (>= 4.0.0) @@ -233,10 +256,10 @@ GEM actionview (>= 7.0.0) activesupport (>= 7.0.0) jmespath (1.6.2) - json (2.19.3) - jwt (3.1.2) + json (2.20.0) + jwt (3.2.0) base64 - kamal (2.10.1) + kamal (2.11.0) activesupport (>= 7.0) base64 (~> 0.2) bcrypt_pbkdf (~> 1.0) @@ -254,11 +277,11 @@ GEM logger (~> 1.6) letter_opener (1.10.0) launchy (>= 2.2, < 4) - lexxy (0.9.0.beta) + lexxy (0.9.23) rails (>= 8.0.2) lint_roller (1.1.0) logger (1.7.0) - loofah (2.25.1) + loofah (2.25.2) crass (~> 1.0.2) nokogiri (>= 1.12.0) mail (2.9.0) @@ -267,14 +290,19 @@ GEM net-imap net-pop net-smtp - marcel (1.1.0) + marcel (1.2.1) matrix (0.4.3) mini_magick (5.3.1) logger mini_mime (1.1.5) - minitest (6.0.2) + minitest (6.0.6) drb (~> 2.0) prism (~> 1.5) + minitest-reporters (1.8.0) + ansi + builder + minitest (>= 5.0, < 7) + ruby-progressbar mission_control-jobs (1.1.0) actioncable (>= 7.1) actionpack (>= 7.1) @@ -288,10 +316,10 @@ GEM mittens (0.3.1) mocha (3.1.0) ruby2_keywords (>= 0.0.5) - msgpack (1.8.0) + msgpack (1.8.3) net-http-persistent (4.0.8) connection_pool (>= 2.2.4, < 4) - net-imap (0.6.3) + net-imap (0.6.4.1) date net-protocol net-pop (0.1.2) @@ -304,23 +332,23 @@ GEM net-ssh (>= 5.0.0, < 8.0.0) net-smtp (0.5.1) net-protocol - net-ssh (7.3.0) + net-ssh (7.3.2) nio4r (2.7.5) - nokogiri (1.19.2-aarch64-linux-gnu) + nokogiri (1.19.4-aarch64-linux-gnu) racc (~> 1.4) - nokogiri (1.19.2-aarch64-linux-musl) + nokogiri (1.19.4-aarch64-linux-musl) racc (~> 1.4) - nokogiri (1.19.2-arm-linux-gnu) + nokogiri (1.19.4-arm-linux-gnu) racc (~> 1.4) - nokogiri (1.19.2-arm-linux-musl) + nokogiri (1.19.4-arm-linux-musl) racc (~> 1.4) - nokogiri (1.19.2-arm64-darwin) + nokogiri (1.19.4-arm64-darwin) racc (~> 1.4) - nokogiri (1.19.2-x86_64-darwin) + nokogiri (1.19.4-x86_64-darwin) racc (~> 1.4) - nokogiri (1.19.2-x86_64-linux-gnu) + nokogiri (1.19.4-x86_64-linux-gnu) racc (~> 1.4) - nokogiri (1.19.2-x86_64-linux-musl) + nokogiri (1.19.4-x86_64-linux-musl) racc (~> 1.4) openssl (4.0.0) ostruct (0.6.3) @@ -331,26 +359,26 @@ GEM platform_agent (1.0.1) activesupport (>= 5.2.0) useragent (~> 0.16.3) - pp (0.6.3) + pp (0.6.4) prettyprint prettyprint (0.2.0) prism (1.9.0) - propshaft (1.3.1) + propshaft (1.3.2) actionpack (>= 7.0.0) activesupport (>= 7.0.0) rack - psych (5.3.1) + psych (5.4.0) date stringio public_suffix (7.0.5) - puma (7.2.0) + puma (7.2.1) nio4r (~> 2.0) raabro (1.4.0) racc (1.8.1) - rack (3.2.5) + rack (3.2.6) rack-mini-profiler (4.0.1) rack (>= 1.2.0) - rack-session (2.1.1) + rack-session (2.1.2) base64 (>= 0.1.0) rack (>= 3.0.0) rack-test (2.2.0) @@ -361,14 +389,19 @@ GEM activesupport (>= 5.0.0) minitest nokogiri (>= 1.6) - rails-html-sanitizer (1.7.0) - loofah (~> 2.25) + rails-html-sanitizer (1.7.1) + loofah (~> 2.25, >= 2.25.2) nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) rainbow (3.1.1) - rake (13.3.1) - rdoc (7.2.0) + rake (13.4.2) + rbs (4.0.3) + logger + prism (>= 1.6.0) + tsort + rdoc (8.0.0) erb - psych (>= 4.0.0) + prism (>= 1.6.0) + rbs (>= 4.0.0) tsort regexp_parser (2.11.3) reline (0.6.3) @@ -412,38 +445,26 @@ GEM ffi (~> 1.12) logger ruby2_keywords (0.0.5) - rubyzip (3.2.2) + rubyzip (3.3.0) securerandom (0.4.1) - selenium-webdriver (4.41.0) + selenium-webdriver (4.44.0) base64 (~> 0.2) logger (~> 1.4) rexml (~> 3.2, >= 3.2.5) rubyzip (>= 1.2.2, < 4.0) websocket (~> 1.0) - solid_cable (3.0.12) - actioncable (>= 7.2) - activejob (>= 7.2) - activerecord (>= 7.2) - railties (>= 7.2) solid_cache (1.0.10) activejob (>= 7.2) activerecord (>= 7.2) railties (>= 7.2) - solid_queue (1.3.2) - activejob (>= 7.1) - activerecord (>= 7.1) - concurrent-ruby (>= 1.3.1) - fugit (~> 1.11) - railties (>= 7.1) - thor (>= 1.3.1) - sqlite3 (2.9.2-aarch64-linux-gnu) - sqlite3 (2.9.2-aarch64-linux-musl) - sqlite3 (2.9.2-arm-linux-gnu) - sqlite3 (2.9.2-arm-linux-musl) - sqlite3 (2.9.2-arm64-darwin) - sqlite3 (2.9.2-x86_64-darwin) - sqlite3 (2.9.2-x86_64-linux-gnu) - sqlite3 (2.9.2-x86_64-linux-musl) + sqlite3 (2.9.5-aarch64-linux-gnu) + sqlite3 (2.9.5-aarch64-linux-musl) + sqlite3 (2.9.5-arm-linux-gnu) + sqlite3 (2.9.5-arm-linux-musl) + sqlite3 (2.9.5-arm64-darwin) + sqlite3 (2.9.5-x86_64-darwin) + sqlite3 (2.9.5-x86_64-linux-gnu) + sqlite3 (2.9.5-x86_64-linux-musl) sshkit (1.25.0) base64 logger @@ -456,13 +477,13 @@ GEM railties (>= 6.0.0) stringio (3.2.0) thor (1.5.0) - thruster (0.1.19) - thruster (0.1.19-aarch64-linux) - thruster (0.1.19-arm64-darwin) - thruster (0.1.19-x86_64-darwin) - thruster (0.1.19-x86_64-linux) - timeout (0.6.0) - trilogy (2.10.0) + thruster (0.1.21) + thruster (0.1.21-aarch64-linux) + thruster (0.1.21-arm64-darwin) + thruster (0.1.21-x86_64-darwin) + thruster (0.1.21-x86_64-linux) + timeout (0.6.1) + trilogy (2.12.6) bigdecimal tsort (0.2.0) tzinfo (2.0.6) @@ -480,13 +501,13 @@ GEM crack (>= 0.3.2) hashdiff (>= 0.4.0, < 2.0.0) websocket (1.2.11) - websocket-driver (0.8.0) + websocket-driver (0.8.2) base64 websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) xpath (3.2.0) nokogiri (~> 1.8) - zeitwerk (2.7.5) + zeitwerk (2.8.2) zip_kit (6.3.4) PLATFORMS @@ -518,28 +539,29 @@ DEPENDENCIES jbuilder kamal letter_opener - lexxy (= 0.9.0.beta) + lexxy (= 0.9.23) + minitest-reporters mission_control-jobs mittens mocha net-http-persistent platform_agent propshaft - puma (>= 5.0) + puma (~> 7.2, >= 7.2.1) rack-mini-profiler rails! rouge rqrcode rubocop-rails-omakase selenium-webdriver - solid_cable (>= 3.0) + solid_cable! solid_cache (~> 1.0) - solid_queue (~> 1.3) + solid_queue! sqlite3 (>= 2.0) stackprof stimulus-rails thruster - trilogy (~> 2.10) + trilogy (~> 2.12) turbo-rails! useragent! vcr diff --git a/Gemfile.saas b/Gemfile.saas index 384f5b4b72..8856523e00 100644 --- a/Gemfile.saas +++ b/Gemfile.saas @@ -8,7 +8,7 @@ gem "actionpack-xml_parser" # needed by queenbee for XML request body parsing gem "queenbee", bc: "queenbee-plugin" gem "fizzy-saas", path: "saas" gem "console1984", bc: "console1984" -gem "audits1984", bc: "audits1984", branch: "flavorjones/coworker-api" +gem "audits1984", bc: "audits1984" # Native push notifications (iOS/Android) gem "action_push_native" diff --git a/Gemfile.saas.lock b/Gemfile.saas.lock index f5bc0bb20b..54194ed31a 100644 --- a/Gemfile.saas.lock +++ b/Gemfile.saas.lock @@ -1,7 +1,6 @@ GIT remote: https://github.com/basecamp/audits1984 - revision: 422b8ff25820c828b7cf09aff4923fd8cc2c6795 - branch: flavorjones/coworker-api + revision: 4271a8e1f02f0f35d749c938bf4dcccf902b4190 specs: audits1984 (0.1.7) console1984 @@ -23,7 +22,7 @@ GIT GIT remote: https://github.com/basecamp/queenbee-plugin - revision: 14312a940471e20617b38cdec7c092a01567d18b + revision: c0119be5940edb3739d4bb591c1a5c7064881638 specs: queenbee (3.2.0) activeresource @@ -64,7 +63,7 @@ GIT GIT remote: https://github.com/rails/rails.git - revision: 12e24eaf2f0a9613e015653f013dd131317d9bf5 + revision: 813301c1ca6a4a11ad2379ed50a57922bc76ae6d branch: main specs: actioncable (8.2.0.alpha) @@ -95,7 +94,7 @@ GIT rack-session (>= 1.0.1) rack-test (>= 0.6.3) rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) + rails-html-sanitizer (~> 1.7) useragent (~> 0.16) actiontext (8.2.0.alpha) action_text-trix (~> 2.1.16) @@ -110,7 +109,7 @@ GIT builder (~> 3.1) erubi (~> 1.11) rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) + rails-html-sanitizer (~> 1.7) activejob (8.2.0.alpha) activesupport (= 8.2.0.alpha) globalid (>= 0.3.6) @@ -164,6 +163,28 @@ GIT tsort (>= 0.2) zeitwerk (~> 2.6) +GIT + remote: https://github.com/rails/solid_cable.git + revision: c968ba777f990194596d035e6ba50e1ee677a09c + specs: + solid_cable (4.0.0) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + +GIT + remote: https://github.com/rails/solid_queue.git + revision: a8c89374b2b600f7306cb44059dce1cc3fc45cec + specs: + solid_queue (1.4.0) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + GIT remote: https://github.com/rails/web-console.git revision: 90e3474306f2367cfeaf2875e91e2bc2d71b5f0f @@ -217,15 +238,16 @@ GEM activemodel (>= 7.0) activemodel-serializers-xml (~> 1.0) activesupport (>= 7.0) - addressable (2.8.9) + addressable (2.9.0) public_suffix (>= 2.0.2, < 8.0) + ansi (1.6.0) anyway_config (2.7.2) ruby-next-core (~> 1.0) ast (2.4.3) autotuner (1.1.0) aws-eventstream (1.4.0) - aws-partitions (1.1229.0) - aws-sdk-core (3.244.0) + aws-partitions (1.1240.0) + aws-sdk-core (3.245.0) aws-eventstream (~> 1, >= 1.3.0) aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) @@ -236,8 +258,8 @@ GEM aws-sdk-kms (1.123.0) aws-sdk-core (~> 3, >= 3.244.0) aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.216.0) - aws-sdk-core (~> 3, >= 3.243.0) + aws-sdk-s3 (1.219.0) + aws-sdk-core (~> 3, >= 3.244.0) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) aws-sigv4 (1.12.1) @@ -246,9 +268,9 @@ GEM bcrypt (3.1.22) bcrypt_pbkdf (1.1.2) benchmark (0.5.0) - bigdecimal (4.1.0) + bigdecimal (4.1.2) bindex (0.8.1) - bootsnap (1.23.0) + bootsnap (1.24.5) msgpack (~> 1.2) brakeman (8.0.4) racc @@ -268,12 +290,12 @@ GEM childprocess (5.1.0) logger (~> 1.5) chunky_png (1.4.0) - concurrent-ruby (1.3.6) + concurrent-ruby (1.3.7) connection_pool (3.0.2) crack (1.0.1) bigdecimal rexml - crass (1.0.6) + crass (1.0.7) date (3.5.1) debug (1.11.1) irb (~> 1.10) @@ -282,11 +304,11 @@ GEM drb (2.2.3) dry-initializer (3.2.0) ed25519 (1.4.0) - erb (6.0.2) + erb (6.0.4) erubi (1.13.1) et-orbi (1.4.0) tzinfo - faker (3.6.1) + faker (3.8.0) i18n (>= 1.8.11, < 2) faraday (2.14.0) faraday-net_http (>= 2.0, < 3.5) @@ -308,7 +330,7 @@ GEM geared_pagination (1.2.0) activesupport (>= 5.0) addressable (>= 2.5.0) - globalid (1.3.0) + globalid (1.4.0) activesupport (>= 6.1) google-cloud-env (2.3.1) base64 (~> 0.2) @@ -327,7 +349,7 @@ GEM http-2 (1.1.1) httpx (1.7.1) http-2 (>= 1.0.0) - i18n (1.14.8) + i18n (1.15.2) concurrent-ruby (~> 1.0) image_processing (1.14.0) mini_magick (>= 4.9.5, < 6) @@ -337,7 +359,7 @@ GEM activesupport (>= 6.0.0) railties (>= 6.0.0) io-console (0.8.2) - irb (1.17.0) + irb (1.18.0) pp (>= 0.6.0) prism (>= 1.3.0) rdoc (>= 4.0.0) @@ -346,10 +368,10 @@ GEM actionview (>= 7.0.0) activesupport (>= 7.0.0) jmespath (1.6.2) - json (2.19.3) - jwt (3.1.2) + json (2.20.0) + jwt (3.2.0) base64 - kamal (2.10.1) + kamal (2.11.0) activesupport (>= 7.0) base64 (~> 0.2) bcrypt_pbkdf (~> 1.0) @@ -367,11 +389,11 @@ GEM logger (~> 1.6) letter_opener (1.10.0) launchy (>= 2.2, < 4) - lexxy (0.9.0.beta) + lexxy (0.9.23) rails (>= 8.0.2) lint_roller (1.1.0) logger (1.7.0) - loofah (2.25.1) + loofah (2.25.2) crass (~> 1.0.2) nokogiri (>= 1.12.0) mail (2.9.0) @@ -380,14 +402,19 @@ GEM net-imap net-pop net-smtp - marcel (1.1.0) + marcel (1.2.1) matrix (0.4.3) mini_magick (5.3.1) logger mini_mime (1.1.5) - minitest (6.0.2) + minitest (6.0.6) drb (~> 2.0) prism (~> 1.5) + minitest-reporters (1.8.0) + ansi + builder + minitest (>= 5.0, < 7) + ruby-progressbar mission_control-jobs (1.1.0) actioncable (>= 7.1) actionpack (>= 7.1) @@ -401,13 +428,13 @@ GEM mittens (0.3.1) mocha (3.1.0) ruby2_keywords (>= 0.0.5) - msgpack (1.8.0) + msgpack (1.8.3) multi_json (1.19.1) net-http (0.9.1) uri (>= 0.11.1) net-http-persistent (4.0.8) connection_pool (>= 2.2.4, < 4) - net-imap (0.6.3) + net-imap (0.6.4.1) date net-protocol net-pop (0.1.2) @@ -420,23 +447,23 @@ GEM net-ssh (>= 5.0.0, < 8.0.0) net-smtp (0.5.1) net-protocol - net-ssh (7.3.0) + net-ssh (7.3.2) nio4r (2.7.5) - nokogiri (1.19.2-aarch64-linux-gnu) + nokogiri (1.19.4-aarch64-linux-gnu) racc (~> 1.4) - nokogiri (1.19.2-aarch64-linux-musl) + nokogiri (1.19.4-aarch64-linux-musl) racc (~> 1.4) - nokogiri (1.19.2-arm-linux-gnu) + nokogiri (1.19.4-arm-linux-gnu) racc (~> 1.4) - nokogiri (1.19.2-arm-linux-musl) + nokogiri (1.19.4-arm-linux-musl) racc (~> 1.4) - nokogiri (1.19.2-arm64-darwin) + nokogiri (1.19.4-arm64-darwin) racc (~> 1.4) - nokogiri (1.19.2-x86_64-darwin) + nokogiri (1.19.4-x86_64-darwin) racc (~> 1.4) - nokogiri (1.19.2-x86_64-linux-gnu) + nokogiri (1.19.4-x86_64-linux-gnu) racc (~> 1.4) - nokogiri (1.19.2-x86_64-linux-musl) + nokogiri (1.19.4-x86_64-linux-musl) racc (~> 1.4) openssl (4.0.0) os (1.1.4) @@ -448,7 +475,7 @@ GEM platform_agent (1.0.1) activesupport (>= 5.2.0) useragent (~> 0.16.3) - pp (0.6.3) + pp (0.6.4) prettyprint prettyprint (0.2.0) prism (1.9.0) @@ -487,22 +514,22 @@ GEM bigdecimal logger rb_sys (~> 0.9.117) - propshaft (1.3.1) + propshaft (1.3.2) actionpack (>= 7.0.0) activesupport (>= 7.0.0) rack - psych (5.3.1) + psych (5.4.0) date stringio public_suffix (7.0.5) - puma (7.2.0) + puma (7.2.1) nio4r (~> 2.0) raabro (1.4.0) racc (1.8.1) - rack (3.2.5) + rack (3.2.6) rack-mini-profiler (4.0.1) rack (>= 1.2.0) - rack-session (2.1.1) + rack-session (2.1.2) base64 (>= 0.1.0) rack (>= 3.0.0) rack-test (2.2.0) @@ -513,17 +540,22 @@ GEM activesupport (>= 5.0.0) minitest nokogiri (>= 1.6) - rails-html-sanitizer (1.7.0) - loofah (~> 2.25) + rails-html-sanitizer (1.7.1) + loofah (~> 2.25, >= 2.25.2) nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) rainbow (3.1.1) - rake (13.3.1) + rake (13.4.2) rake-compiler-dock (1.9.1) rb_sys (0.9.117) rake-compiler-dock (= 1.9.1) - rdoc (7.2.0) + rbs (4.0.3) + logger + prism (>= 1.6.0) + tsort + rdoc (8.0.0) erb - psych (>= 4.0.0) + prism (>= 1.6.0) + rbs (>= 4.0.0) tsort regexp_parser (2.11.3) reline (0.6.3) @@ -569,9 +601,9 @@ GEM ffi (~> 1.12) logger ruby2_keywords (0.0.5) - rubyzip (3.2.2) + rubyzip (3.3.0) securerandom (0.4.1) - selenium-webdriver (4.41.0) + selenium-webdriver (4.44.0) base64 (~> 0.2) logger (~> 1.4) rexml (~> 3.2, >= 3.2.5) @@ -591,30 +623,18 @@ GEM sniffer (0.5.0) anyway_config (>= 1.0) dry-initializer (~> 3) - solid_cable (3.0.12) - actioncable (>= 7.2) - activejob (>= 7.2) - activerecord (>= 7.2) - railties (>= 7.2) solid_cache (1.0.10) activejob (>= 7.2) activerecord (>= 7.2) railties (>= 7.2) - solid_queue (1.3.2) - activejob (>= 7.1) - activerecord (>= 7.1) - concurrent-ruby (>= 1.3.1) - fugit (~> 1.11) - railties (>= 7.1) - thor (>= 1.3.1) - sqlite3 (2.9.2-aarch64-linux-gnu) - sqlite3 (2.9.2-aarch64-linux-musl) - sqlite3 (2.9.2-arm-linux-gnu) - sqlite3 (2.9.2-arm-linux-musl) - sqlite3 (2.9.2-arm64-darwin) - sqlite3 (2.9.2-x86_64-darwin) - sqlite3 (2.9.2-x86_64-linux-gnu) - sqlite3 (2.9.2-x86_64-linux-musl) + sqlite3 (2.9.5-aarch64-linux-gnu) + sqlite3 (2.9.5-aarch64-linux-musl) + sqlite3 (2.9.5-arm-linux-gnu) + sqlite3 (2.9.5-arm-linux-musl) + sqlite3 (2.9.5-arm64-darwin) + sqlite3 (2.9.5-x86_64-darwin) + sqlite3 (2.9.5-x86_64-linux-gnu) + sqlite3 (2.9.5-x86_64-linux-musl) sshkit (1.25.0) base64 logger @@ -627,13 +647,13 @@ GEM railties (>= 6.0.0) stringio (3.2.0) thor (1.5.0) - thruster (0.1.19) - thruster (0.1.19-aarch64-linux) - thruster (0.1.19-arm64-darwin) - thruster (0.1.19-x86_64-darwin) - thruster (0.1.19-x86_64-linux) - timeout (0.6.0) - trilogy (2.10.0) + thruster (0.1.21) + thruster (0.1.21-aarch64-linux) + thruster (0.1.21-arm64-darwin) + thruster (0.1.21-x86_64-darwin) + thruster (0.1.21-x86_64-linux) + timeout (0.6.1) + trilogy (2.12.6) bigdecimal tsort (0.2.0) tzinfo (2.0.6) @@ -652,7 +672,7 @@ GEM hashdiff (>= 0.4.0, < 2.0.0) webrick (1.9.1) websocket (1.2.11) - websocket-driver (0.8.0) + websocket-driver (0.8.2) base64 websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) @@ -685,7 +705,7 @@ GEM anyway_config (>= 1.3, < 3) railties yabeda (~> 0.8) - zeitwerk (2.7.5) + zeitwerk (2.8.2) zip_kit (6.3.4) PLATFORMS @@ -724,7 +744,8 @@ DEPENDENCIES jbuilder kamal letter_opener - lexxy (= 0.9.0.beta) + lexxy (= 0.9.23) + minitest-reporters mission_control-jobs mittens mocha @@ -732,7 +753,7 @@ DEPENDENCIES platform_agent prometheus-client-mmap (~> 1.3) propshaft - puma (>= 5.0) + puma (~> 7.2, >= 7.2.1) queenbee! rack-mini-profiler rails! @@ -743,14 +764,14 @@ DEPENDENCIES selenium-webdriver sentry-rails sentry-ruby - solid_cable (>= 3.0) + solid_cable! solid_cache (~> 1.0) - solid_queue (~> 1.3) + solid_queue! sqlite3 (>= 2.0) stackprof stimulus-rails thruster - trilogy (~> 2.10) + trilogy (~> 2.12) turbo-rails! useragent! vcr diff --git a/README.md b/README.md index f5ebebbe1a..9a2c413439 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ For manual fallback installs, you can still install the stable package image dir cloudron install --image ghcr.io/patattzel/fizzy-cloudron:stable --location fizzy ``` -Use `stable` or an explicit package version such as `ghcr.io/patattzel/fizzy-cloudron:1.2.4`. Do not use `latest`. +Use `stable` or an explicit package version such as `ghcr.io/patattzel/fizzy-cloudron:1.2.5`. Do not use `latest`. ## Maintainer release flow @@ -38,7 +38,7 @@ Use `stable` or an explicit package version such as `ghcr.io/patattzel/fizzy-clo 3. Push the commit to `main`. 4. Push a matching Git tag in the form `v` to publish the immutable Cloudron image tag and refresh `stable`. -The existing GitHub CI workflows remain useful for the Rails app. Only `.github/workflows/publish-image.yml` is Cloudron-specific, and it now publishes the Cloudron package image from `Dockerfile.cloudron`. +The fork’s OSS CI validates the Rails app, while `.github/workflows/publish-image.yml` validates and publishes the Cloudron package image from `Dockerfile.cloudron`. ## Runtime notes diff --git a/app/assets/stylesheets/lexxy.css b/app/assets/stylesheets/lexxy.css index 053f626a9f..1a7b56481f 100644 --- a/app/assets/stylesheets/lexxy.css +++ b/app/assets/stylesheets/lexxy.css @@ -59,13 +59,18 @@ lexxy-toolbar { border-color: var(--lexxy-border-color); gap: 0; + + svg { + fill: currentColor; + } } - .lexxy-editor__toolbar-button { + /* Exclude the link dropdown's action buttons — they keep the gem's accent/gray background. */ + .lexxy-editor__toolbar-button:not(.lexxy-editor__toolbar-dropdown-actions *) { background: transparent; &[aria-pressed="true"], - [open] > & { + &[aria-expanded="true"] { background-color: oklch(var(--lch-blue-medium) / 20%); } @@ -76,10 +81,19 @@ } } + .lexxy-editor__toolbar-button--chevron { + &:after { + block-size: 0.3rem; + inline-size: 0.3rem; + } + } + lexxy-link-dropdown { - --lexxy-toolbar-spacing: 1.5ch; + [data-dropdown-panel] { + --lexxy-toolbar-spacing: 1.5ch; + } - .lexxy-editor__toolbar-button { + .lexxy-editor__toolbar-dropdown-actions .lexxy-editor__toolbar-button { border-radius: 99rem; @media(any-hover: hover) { @@ -89,12 +103,16 @@ } } - &[type="submit"], - &[type="submit"]:hover { + &[value="link"] { background-color: var(--color-link); + color: var(--color-ink-inverted); + + &:hover { + background-color: var(--color-link); + } } - &[type="button"] { + &[value="unlink"] { border: 1px solid var(--color-ink-light); } } diff --git a/app/assets/stylesheets/settings.css b/app/assets/stylesheets/settings.css index 699992c10d..bbb6f95445 100644 --- a/app/assets/stylesheets/settings.css +++ b/app/assets/stylesheets/settings.css @@ -20,6 +20,9 @@ } } + /* Sections & Panels + /* -------------------------------------------------------------------------- */ + .settings__panel { --panel-size: 100%; --panel-padding: calc(var(--settings-spacer) / 1); @@ -65,6 +68,20 @@ min-width: 0; } + .settings__section { + h2 { + font-size: var(--text-large); + } + + > * + * { + margin-block-start: calc(var(--panel-padding) / 2); + } + + &:is(:first-child):has(h2) { + margin-top: -0.33lh; /* Align h2 letters caps with panel padding */ + } + } + .settings__section--negative { h2 { color: var(--color-negative); diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb new file mode 100644 index 0000000000..51ae3de8f0 --- /dev/null +++ b/app/controllers/activities_controller.rb @@ -0,0 +1,30 @@ +class ActivitiesController < ApplicationController + ACTIONS = %w[ + card_assigned + card_auto_postponed + card_board_changed + card_closed + card_postponed + card_published + card_reopened + card_sent_back_to_triage + card_title_changed + card_triaged + card_unassigned + comment_created + ].freeze + + def index + set_page_and_extract_portion_from(activities) + end + + private + def activities + Current.user.accessible_events + .preloaded + .where(action: ACTIONS) + .for_creators(params[:creator_ids]) + .for_boards(params[:board_ids]) + .reverse_chronologically + end +end diff --git a/app/controllers/boards/accesses_controller.rb b/app/controllers/boards/accesses_controller.rb new file mode 100644 index 0000000000..fbb1fe97d7 --- /dev/null +++ b/app/controllers/boards/accesses_controller.rb @@ -0,0 +1,14 @@ +class Boards::AccessesController < ApplicationController + include BoardScoped + + def index + set_page_and_extract_portion_from @board.account.users.active.alphabetically.includes(:identity) + end + + private + def involvement_by_user + @involvement_by_user ||= @board.accesses.where(user_id: @page.records.map(&:id)).pluck(:user_id, :involvement).to_h + end + + helper_method :involvement_by_user +end diff --git a/app/controllers/boards/columns/cards_controller.rb b/app/controllers/boards/columns/cards_controller.rb new file mode 100644 index 0000000000..ae6602f14a --- /dev/null +++ b/app/controllers/boards/columns/cards_controller.rb @@ -0,0 +1,19 @@ +class Boards::Columns::CardsController < ApplicationController + include BoardScoped + + before_action :set_column + + def index + set_page_and_extract_portion_from @column.cards.active.latest.with_golden_first.preloaded + fresh_when etag: @page.records + + respond_to do |format| + format.json + end + end + + private + def set_column + @column = @board.columns.find(params[:column_id]) + end +end diff --git a/app/controllers/boards/columns_controller.rb b/app/controllers/boards/columns_controller.rb index d0bd13c551..cd07562755 100644 --- a/app/controllers/boards/columns_controller.rb +++ b/app/controllers/boards/columns_controller.rb @@ -29,7 +29,7 @@ def update respond_to do |format| format.turbo_stream - format.json { head :no_content } + format.json { render :show } end end diff --git a/app/controllers/boards_controller.rb b/app/controllers/boards_controller.rb index 3d5485f1ff..3f242bcb8d 100644 --- a/app/controllers/boards_controller.rb +++ b/app/controllers/boards_controller.rb @@ -50,7 +50,13 @@ def update redirect_to root_path, notice: "Saved (you were removed from the board)" end end - format.json { head :no_content } + format.json do + if @board.accessible_to?(Current.user) + render :show + else + head :no_content + end + end end end diff --git a/app/controllers/cards/boards_controller.rb b/app/controllers/cards/boards_controller.rb index 3444cd3452..3c26607a56 100644 --- a/app/controllers/cards/boards_controller.rb +++ b/app/controllers/cards/boards_controller.rb @@ -14,7 +14,7 @@ def update respond_to do |format| format.html { redirect_to @card } - format.json { head :no_content } + format.json { render "cards/show" } end end diff --git a/app/controllers/cards/comments_controller.rb b/app/controllers/cards/comments_controller.rb index 7aed33c8c8..2243c1bdb4 100644 --- a/app/controllers/cards/comments_controller.rb +++ b/app/controllers/cards/comments_controller.rb @@ -30,7 +30,7 @@ def update respond_to do |format| format.turbo_stream - format.json { head :no_content } + format.json { render :show } end end diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb index a269fc2d66..95240f11e7 100644 --- a/app/controllers/concerns/authentication.rb +++ b/app/controllers/concerns/authentication.rb @@ -57,7 +57,7 @@ def find_session_by_cookie def authenticate_by_bearer_token if request.authorization.to_s.include?("Bearer") - if request.format.json? + if bearer_token_authenticatable_request? authenticate_or_request_with_http_token do |token| if identity = Identity.find_by_permissable_access_token(token, method: request.method) Current.identity = identity @@ -69,6 +69,10 @@ def authenticate_by_bearer_token end end + def bearer_token_authenticatable_request? + request.format.json? + end + def request_authentication if Current.account.present? session[:return_to_after_authenticating] = request.url diff --git a/app/controllers/my/timezones_controller.rb b/app/controllers/my/timezones_controller.rb index c70d7e80a4..8ad770db3c 100644 --- a/app/controllers/my/timezones_controller.rb +++ b/app/controllers/my/timezones_controller.rb @@ -1,6 +1,7 @@ class My::TimezonesController < ApplicationController def update Current.user.settings.update!(timezone_name: timezone_param) + head :no_content end private diff --git a/app/controllers/prompts/tags_controller.rb b/app/controllers/prompts/tags_controller.rb deleted file mode 100644 index 3d32a071e3..0000000000 --- a/app/controllers/prompts/tags_controller.rb +++ /dev/null @@ -1,9 +0,0 @@ -class Prompts::TagsController < ApplicationController - def index - @tags = Current.account.tags.all.alphabetically - - if stale? etag: @tags - render layout: false - end - end -end diff --git a/app/controllers/users/data_exports_controller.rb b/app/controllers/users/data_exports_controller.rb index 60df1e3265..8a3239b8f9 100644 --- a/app/controllers/users/data_exports_controller.rb +++ b/app/controllers/users/data_exports_controller.rb @@ -7,11 +7,20 @@ class Users::DataExportsController < ApplicationController CURRENT_EXPORT_LIMIT = 10 def show + respond_to do |format| + format.html + format.json { @export ? render(:show) : head(:not_found) } + end end def create - @user.data_exports.create!(account: Current.account).build_later - redirect_to @user, notice: "Export started. You'll receive an email when it's ready." + @export = @user.data_exports.create!(account: Current.account) + @export.build_later + + respond_to do |format| + format.html { redirect_to @user, notice: "Export started. You'll receive an email when it's ready." } + format.json { render :show, status: :created } + end end private @@ -28,6 +37,7 @@ def ensure_export_limit_not_exceeded end def set_export - @export = @user.data_exports.completed.find_by(id: params[:id]) + scope = request.format.json? ? @user.data_exports : @user.data_exports.completed + @export = scope.find_by(id: params[:id]) end end diff --git a/app/controllers/users/email_addresses/confirmations_controller.rb b/app/controllers/users/email_addresses/confirmations_controller.rb index b5fd334ea4..f844285daa 100644 --- a/app/controllers/users/email_addresses/confirmations_controller.rb +++ b/app/controllers/users/email_addresses/confirmations_controller.rb @@ -12,9 +12,15 @@ def create terminate_session if Current.session start_new_session_for @user.identity - redirect_to edit_user_url(script_name: @user.account.slug, id: @user) + respond_to do |format| + format.html { redirect_to edit_user_url(script_name: @user.account.slug, id: @user) } + format.json { head :no_content } + end else - render :invalid_token, status: :unprocessable_entity + respond_to do |format| + format.html { render :invalid_token, status: :unprocessable_entity } + format.json { render json: { error: "Token is invalid or has expired" }, status: :unprocessable_entity } + end end end diff --git a/app/controllers/users/email_addresses_controller.rb b/app/controllers/users/email_addresses_controller.rb index 69957b1f61..58d8a2723e 100644 --- a/app/controllers/users/email_addresses_controller.rb +++ b/app/controllers/users/email_addresses_controller.rb @@ -1,18 +1,17 @@ class Users::EmailAddressesController < ApplicationController before_action :set_user + before_action :ensure_valid_email_address, only: :create rate_limit to: 5, within: 1.hour, only: :create def new end def create - identity = Identity.find_by_email_address(new_email_address) + @user.send_email_address_change_confirmation(new_email_address) - if identity&.users&.exists?(account: @user.account) - flash[:alert] = "You already have a user in this account with that email address" - redirect_to new_user_email_address_path(@user) - else - @user.send_email_address_change_confirmation(new_email_address) + respond_to do |format| + format.html + format.json { head :created } end end @@ -21,6 +20,25 @@ def set_user @user = Current.identity.users.find(params[:user_id]) end + def ensure_valid_email_address + if !new_email_address.match?(URI::MailTo::EMAIL_REGEXP) + error = "Please enter a valid email address" + elsif (identity = Identity.find_by_email_address(new_email_address)) + if identity == @user.identity + error = "That is already your email address" + elsif identity.users.exists?(account: @user.account) + error = "You already have a user in this account with that email address" + end + end + + if error + respond_to do |format| + format.html { redirect_to new_user_email_address_path(@user), alert: error } + format.json { render json: { error: error }, status: :unprocessable_entity } + end + end + end + def new_email_address params.expect :email_address end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index fdc528d3e9..e77f3d4b12 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -18,7 +18,7 @@ def update if @user.update(user_params) respond_to do |format| format.html { redirect_to @user } - format.json { head :no_content } + format.json { render :show } end else respond_to do |format| diff --git a/app/controllers/webhooks/deliveries_controller.rb b/app/controllers/webhooks/deliveries_controller.rb new file mode 100644 index 0000000000..551e5ae76a --- /dev/null +++ b/app/controllers/webhooks/deliveries_controller.rb @@ -0,0 +1,19 @@ +class Webhooks::DeliveriesController < ApplicationController + include BoardScoped + + before_action :ensure_admin + before_action :set_webhook + + def index + respond_to do |format| + format.json do + set_page_and_extract_portion_from @webhook.deliveries.ordered.includes(event: [ :creator, { eventable: :card } ]) + end + end + end + + private + def set_webhook + @webhook = @board.webhooks.find(params[:webhook_id]) + end +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index f0c21c7080..4994ded54f 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,16 +1,4 @@ module ApplicationHelper - def support_email - ENV["SUPPORT_EMAIL"] || - ENV["MAIL_FROM"] || - ENV["MAILER_FROM_ADDRESS"] || - ENV["MAIL_SMTP_USERNAME"] || - "support@example.com" - end - - def marketing_url - ENV["MARKETING_URL"] || root_url - end - def signups_allowed? defined?(SignupToggle) ? SignupToggle.allowed? : true end diff --git a/app/helpers/rich_text_helper.rb b/app/helpers/rich_text_helper.rb index c580b4507a..e40fb8138b 100644 --- a/app/helpers/rich_text_helper.rb +++ b/app/helpers/rich_text_helper.rb @@ -7,10 +7,6 @@ def global_mentions_prompt content_tag "lexxy-prompt", "", trigger: "@", src: prompts_users_path, name: "mention" end - def tags_prompt - content_tag "lexxy-prompt", "", trigger: "#", src: prompts_tags_path, name: "tag" - end - def cards_prompt content_tag "lexxy-prompt", "", trigger: "#", src: prompts_cards_path, name: "card", "insert-editable-text": true, "remote-filtering": true, "supports-space-in-searches": true end diff --git a/app/javascript/controllers/dialog_manager_controller.js b/app/javascript/controllers/dialog_manager_controller.js index 71552e2c8a..1af4146e61 100644 --- a/app/javascript/controllers/dialog_manager_controller.js +++ b/app/javascript/controllers/dialog_manager_controller.js @@ -2,11 +2,12 @@ import { Controller } from "@hotwired/stimulus" export default class extends Controller { connect() { - this.element.addEventListener("dialog:show", this.handleDialogShow.bind(this)) + this.boundHandleDialogShow = this.handleDialogShow.bind(this) + this.element.addEventListener("dialog:show", this.boundHandleDialogShow) } disconnect() { - this.element.removeEventListener("dialog:show", this.handleDialogShow.bind(this)) + this.element.removeEventListener("dialog:show", this.boundHandleDialogShow) } handleDialogShow(event) { diff --git a/app/javascript/controllers/drag_and_strum_controller.js b/app/javascript/controllers/drag_and_strum_controller.js index 8946f360a5..741e79168a 100644 --- a/app/javascript/controllers/drag_and_strum_controller.js +++ b/app/javascript/controllers/drag_and_strum_controller.js @@ -49,11 +49,12 @@ export default class extends Controller { connect() { this.instrumentIndex = 0 this.preloadedAudioFiles = [] - document.addEventListener("keydown", this.handleKeyDown.bind(this)); + this.boundHandleKeyDown = this.handleKeyDown.bind(this) + document.addEventListener("keydown", this.boundHandleKeyDown); } disconnect() { - document.removeEventListener("keydown", this.handleKeyDown.bind(this)); + document.removeEventListener("keydown", this.boundHandleKeyDown); } handleKeyDown(event) { diff --git a/app/javascript/controllers/morph_guard_controller.js b/app/javascript/controllers/morph_guard_controller.js new file mode 100644 index 0000000000..1458c27af4 --- /dev/null +++ b/app/javascript/controllers/morph_guard_controller.js @@ -0,0 +1,16 @@ +import { Controller } from "@hotwired/stimulus" + +// Marks the enclosing turbo-frame permanent while connected, so that a +// broadcasted page refresh can't morph away an edit in progress. The attribute +// is never in the server-rendered markup, so display mode stays morphable and +// page replacements never transplant the frame (https://github.com/basecamp/lexxy/issues/263). +export default class extends Controller { + connect() { + this.frame = this.element.closest("turbo-frame") + this.frame?.setAttribute("data-turbo-permanent", "") + } + + disconnect() { + this.frame?.removeAttribute("data-turbo-permanent") + } +} diff --git a/app/javascript/controllers/syntax_highlight_controller.js b/app/javascript/controllers/syntax_highlight_controller.js index cfaf93ba10..9dd82f959e 100644 --- a/app/javascript/controllers/syntax_highlight_controller.js +++ b/app/javascript/controllers/syntax_highlight_controller.js @@ -1,8 +1,8 @@ import { Controller } from "@hotwired/stimulus" -import { highlightAll } from "lexxy" +import { highlightCode } from "lexxy" export default class extends Controller { connect() { - highlightAll() + highlightCode() } } diff --git a/app/javascript/controllers/tooltip_controller.js b/app/javascript/controllers/tooltip_controller.js index 57958cd15e..d9158113ca 100644 --- a/app/javascript/controllers/tooltip_controller.js +++ b/app/javascript/controllers/tooltip_controller.js @@ -5,13 +5,15 @@ export default class extends Controller { static targets = [ "tooltip" ] connect() { - this.element.addEventListener("mouseenter", this.mouseEnter.bind(this)) - this.element.addEventListener("mouseout", this.mouseOut.bind(this)) + this.boundMouseEnter = this.mouseEnter.bind(this) + this.boundMouseOut = this.mouseOut.bind(this) + this.element.addEventListener("mouseenter", this.boundMouseEnter) + this.element.addEventListener("mouseout", this.boundMouseOut) } disconnect() { - this.element.removeEventListener("mouseenter", this.mouseEnter.bind(this)) - this.element.removeEventListener("mouseout", this.mouseOut.bind(this)) + this.element.removeEventListener("mouseenter", this.boundMouseEnter) + this.element.removeEventListener("mouseout", this.boundMouseOut) } mouseEnter(event) { diff --git a/app/javascript/helpers/date_helpers.js b/app/javascript/helpers/date_helpers.js index b8d9855f47..923a7b6ca2 100644 --- a/app/javascript/helpers/date_helpers.js +++ b/app/javascript/helpers/date_helpers.js @@ -1,3 +1,5 @@ +import { getMetaContent } from "helpers/meta_helpers" + export function differenceInDays(fromDate, toDate) { return Math.round(Math.abs((beginningOfDay(toDate) - beginningOfDay(fromDate)) / (1000 * 60 * 60 * 24))) } @@ -7,9 +9,44 @@ export function signedDifferenceInDays(fromDate, toDate) { } export function beginningOfDay(date) { - return new Date(date.getFullYear(), date.getMonth(), date.getDate()) + const { year, month, day } = datePartsInTimezone(date) + return new Date(Date.UTC(year, month - 1, day)) } export function secondsToDate(seconds) { return new Date(seconds * 1000) } + +// Snap a timestamp to midnight using the timezone the server rendered with (the +// `timezone` meta tag), so client day boundaries match the server's instead of +// following the browser's resolved timezone, which can differ in a PWA. +function datePartsInTimezone(date) { + return dateFormatter().formatToParts(date).reduce((parts, { type, value }) => { + if (type !== "literal") parts[type] = parseInt(value, 10) + return parts + }, {}) +} + +let dateFormatterCache +let dateFormatterTimezone + +function dateFormatter() { + const timezone = getMetaContent("timezone") + + if (!dateFormatterCache || dateFormatterTimezone !== timezone) { + dateFormatterTimezone = timezone + dateFormatterCache = buildDateFormatter(timezone) + } + + return dateFormatterCache +} + +function buildDateFormatter(timezone) { + const options = { year: "numeric", month: "2-digit", day: "2-digit" } + + try { + return new Intl.DateTimeFormat("en-US", { ...options, timeZone: timezone }) + } catch { + return new Intl.DateTimeFormat("en-US", options) + } +} diff --git a/app/javascript/helpers/form_helpers.js b/app/javascript/helpers/form_helpers.js index f9a8727022..e1590eb5ca 100644 --- a/app/javascript/helpers/form_helpers.js +++ b/app/javascript/helpers/form_helpers.js @@ -1,8 +1,16 @@ import { FetchRequest } from "@rails/request.js" +// Persist a form in the background. Auto-save uses this to save drafts as you type; it asks +// for JSON so the server acknowledges through CardsController#update's `format.json` branch +// (auto-save ignores the response body). That avoids the drafted-card Turbo Stream response, +// whose first action morphs the whole card container — which *is* the form you're editing — +// and would clobber keystrokes typed while the save is in flight. JSON also clears the +// original 406: the request no longer defaults to `Accept: text/html`, a format #update +// doesn't serve. export async function submitForm(form) { const request = new FetchRequest(form.method, form.action, { - body: new FormData(form) + body: new FormData(form), + responseKind: "json" }) return await request.perform() diff --git a/app/javascript/helpers/meta_helpers.js b/app/javascript/helpers/meta_helpers.js new file mode 100644 index 0000000000..a53f7312a9 --- /dev/null +++ b/app/javascript/helpers/meta_helpers.js @@ -0,0 +1,3 @@ +export function getMetaContent(name) { + return document.querySelector(`meta[name="${name}"]`)?.getAttribute("content") +} diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb index d394c3d106..7cbf01d557 100644 --- a/app/jobs/application_job.rb +++ b/app/jobs/application_job.rb @@ -1,4 +1,6 @@ class ApplicationJob < ActiveJob::Base + prepend AccountTenanted + # Automatically retry jobs that encountered a deadlock # retry_on ActiveRecord::Deadlocked diff --git a/app/jobs/concerns/account_tenanted.rb b/app/jobs/concerns/account_tenanted.rb new file mode 100644 index 0000000000..d8df4331c2 --- /dev/null +++ b/app/jobs/concerns/account_tenanted.rb @@ -0,0 +1,47 @@ +# Serializes the current account into job data so that jobs run +# within the correct account context via Current.with_account. +# +# Account resolution is deferred to an around_perform callback so +# that missing accounts raise DeserializationError inside the +# execution path where discard_on can handle it. +module AccountTenanted + extend ActiveSupport::Concern + + prepended do + attr_reader :account + around_perform :with_account_context + end + + def initialize(...) + super + @account = Current.account + end + + def serialize + super.merge({ "account" => @account&.to_gid }) + end + + def deserialize(job_data) + super + @account_gid = job_data["account"] + end + + private + def with_account_context(&block) + resolve_account! + + if account.present? + Current.with_account(account, &block) + else + yield + end + end + + def resolve_account! + if @account_gid + @account = GlobalID::Locator.locate(@account_gid) + end + rescue ActiveRecord::RecordNotFound + raise ActiveJob::DeserializationError + end +end diff --git a/app/jobs/search_reindex_job.rb b/app/jobs/search_reindex_job.rb new file mode 100644 index 0000000000..84fadaa8ce --- /dev/null +++ b/app/jobs/search_reindex_job.rb @@ -0,0 +1,60 @@ +# Repair task — reindexes every searchable Card and Comment in the database. +# Intended to be invoked manually after a search-index loss event. Not a recurring job. +# +# Idempotent: Searchable#reindex upserts by (searchable_type, searchable_id). +# Continuable: if the worker is interrupted, the job resumes from the last-processed id. +# +# `rich_text_limit` is a safety valve against unbounded bodies: records whose rich text +# exceeds the limit (in bytes) are filtered out at the SQL level, so they never materialize +# in Ruby. Without it, a single pathological body can stall the batch query or OOM the +# worker during preload, which has happened in practice. +# +# Usage: +# SearchReindexJob.perform_later +# SearchReindexJob.perform_later(batch_size: 500, log_every: 100, rich_text_limit: 50_000) +class SearchReindexJob < ApplicationJob + include ActiveJob::Continuable + + queue_as :backend + + def perform(batch_size: 100, log_every: 1000, rich_text_limit: 100_000) + step :cards do |step| + processed = 0 + Card.published + .left_joins(:rich_text_description) + .where("action_text_rich_texts.body IS NULL OR OCTET_LENGTH(action_text_rich_texts.body) <= ?", rich_text_limit) + .includes(:rich_text_description) + .find_each(start: step.cursor, batch_size: batch_size) do |card| + safely_reindex(card) + processed += 1 + log_progress(:cards, processed, card.id) if (processed % log_every).zero? + step.advance! from: card.id + end + end + + step :comments do |step| + processed = 0 + Comment.joins(:card).merge(Card.published) + .left_joins(:rich_text_body) + .where("action_text_rich_texts.body IS NULL OR OCTET_LENGTH(action_text_rich_texts.body) <= ?", rich_text_limit) + .includes(:rich_text_body, :card) + .find_each(start: step.cursor, batch_size: batch_size) do |comment| + safely_reindex(comment) + processed += 1 + log_progress(:comments, processed, comment.id) if (processed % log_every).zero? + step.advance! from: comment.id + end + end + end + + private + def safely_reindex(record) + record.reindex + rescue StandardError => e + Rails.error.report(e, context: { record_type: record.class.name, record_id: record.id }) + end + + def log_progress(step_name, count, cursor) + Rails.logger.info { "SearchReindexJob: step=#{step_name} processed=#{count} cursor=#{cursor}" } + end +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb index ebcf3ff430..9f0d723596 100644 --- a/app/mailers/application_mailer.rb +++ b/app/mailers/application_mailer.rb @@ -1,8 +1,5 @@ class ApplicationMailer < ActionMailer::Base - default from: ENV["MAILER_FROM_ADDRESS"] || - ENV["MAIL_FROM"] || - ENV["MAIL_SMTP_USERNAME"] || - "Fizzy " + default from: ENV.fetch("MAILER_FROM_ADDRESS", "Fizzy ") layout "mailer" append_view_path Rails.root.join("app/views/mailers") diff --git a/app/models/access.rb b/app/models/access.rb index afdd6312fa..3492317e71 100644 --- a/app/models/access.rb +++ b/app/models/access.rb @@ -19,6 +19,6 @@ def recently_accessed? end def clean_inaccessible_data_later - Board::CleanInaccessibleDataJob.perform_later(user, board) + Board::CleanInaccessibleDataJob.perform_later(user, board) unless user.destroyed? end end diff --git a/app/models/account.rb b/app/models/account.rb index 92590d9f90..687a46a39f 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -1,5 +1,5 @@ class Account < ApplicationRecord - include Account::Storage, Cancellable, Entropic, Incineratable, MultiTenantable, Seedeable + include Account::Storage, Cancellable, Entropic, Incineratable, MultiTenantable, Searchable, Seedeable has_one :join_code, dependent: :destroy has_many :users, dependent: :destroy diff --git a/app/models/account/data_transfer/record_set.rb b/app/models/account/data_transfer/record_set.rb index ff7b79b5c5..c46c348961 100644 --- a/app/models/account/data_transfer/record_set.rb +++ b/app/models/account/data_transfer/record_set.rb @@ -65,7 +65,7 @@ def records end def export_record(record) - zip.add_file "data/#{model_dir}/#{record.id}.json", record.to_json + zip.add_file "data/#{model_dir}/#{record.id}.json", record.attributes.slice(*attributes).to_json end def files diff --git a/app/models/account/import.rb b/app/models/account/import.rb index 50ec3769d4..2bf1b88e7b 100644 --- a/app/models/account/import.rb +++ b/app/models/account/import.rb @@ -4,7 +4,7 @@ class Account::Import < ApplicationRecord belongs_to :account belongs_to :identity - has_one_attached :file + has_one_attached :file, dependent: :purge_later enum :status, %w[ pending processing completed failed ].index_by(&:itself), default: :pending enum :failure_reason, %w[ conflict invalid_export ].index_by(&:itself), prefix: :failed_due_to, scopes: false diff --git a/app/models/account/incineratable.rb b/app/models/account/incineratable.rb index c734c0768a..25b26a9f92 100644 --- a/app/models/account/incineratable.rb +++ b/app/models/account/incineratable.rb @@ -11,7 +11,7 @@ module Account::Incineratable def incinerate run_callbacks :incinerate do - account.destroy + Storage::Entry.suppressing_recording { account.destroy } end end end diff --git a/app/models/account/searchable.rb b/app/models/account/searchable.rb new file mode 100644 index 0000000000..5e5cc3c594 --- /dev/null +++ b/app/models/account/searchable.rb @@ -0,0 +1,14 @@ +module Account::Searchable + extend ActiveSupport::Concern + + included do + has_many :search_queries, class_name: "Search::Query", dependent: :delete_all + + before_destroy :clear_search_records + end + + private + def clear_search_records + Search::Record.for(id).where(account_id: id).destroy_all + end +end diff --git a/app/models/account/storage.rb b/app/models/account/storage.rb index 8b432e8ce6..f59ff88bba 100644 --- a/app/models/account/storage.rb +++ b/app/models/account/storage.rb @@ -2,7 +2,15 @@ module Account::Storage extend ActiveSupport::Concern include Storage::Totaled + included do + before_destroy :clear_storage_entries + end + private + def clear_storage_entries + Storage::Entry.where(account_id: id).delete_all + end + def calculate_real_storage_bytes boards.sum { |board| board.send(:calculate_real_storage_bytes) } end diff --git a/app/models/card.rb b/app/models/card.rb index c3c0b9173b..14b89c00f1 100644 --- a/app/models/card.rb +++ b/app/models/card.rb @@ -30,6 +30,7 @@ class Card < ApplicationRecord when "stalled" then stalled when "postponing_soon" then postponing_soon when "closed" then closed + when "maybe" then awaiting_triage when "not_now" then postponed.latest when "golden" then golden when "draft" then drafted @@ -89,6 +90,6 @@ def track_board_change_event(old_board_name) end def assign_number - self.number ||= account.increment!(:cards_count).cards_count + self.number ||= account.with_lock { account.increment!(:cards_count).cards_count } end end diff --git a/app/models/card/entropic.rb b/app/models/card/entropic.rb index ebaad78c70..328c4bb00e 100644 --- a/app/models/card/entropic.rb +++ b/app/models/card/entropic.rb @@ -2,14 +2,6 @@ module Card::Entropic extend ActiveSupport::Concern included do - scope :due_to_be_postponed, -> do - active - .joins(board: :account) - .left_outer_joins(board: :entropy) - .joins("LEFT OUTER JOIN entropies AS account_entropies ON account_entropies.account_id = accounts.id AND account_entropies.container_type = 'Account' AND account_entropies.container_id = accounts.id") - .where("last_active_at <= #{connection.date_subtract('?', 'COALESCE(entropies.auto_postpone_period, account_entropies.auto_postpone_period)')}", Time.now) - end - scope :postponing_soon, -> do now = Time.now active @@ -24,9 +16,21 @@ module Card::Entropic end class_methods do - def auto_postpone_all_due - due_to_be_postponed.find_each do |card| - card.auto_postpone(user: card.account.system_user) + # Iterates per account, grouping the account's boards by their effective + # auto-postpone period (board override, else account default). Each group + # queries with a single constant cutoff, so `account_id = ? AND + # last_active_at <= ?` rides the existing index instead of computing the + # threshold per row across every card in the system. + def auto_postpone_all_due(as_of: Time.now) + Account.find_each do |account| + account.boards.includes(:entropy).group_by(&:auto_postpone_period).each do |period, boards| + account.cards.active + .where(board_id: boards.map(&:id)) + .where(last_active_at: ..(as_of - period)) + .find_each do |card| + card.auto_postpone(user: account.system_user) + end + end end end end diff --git a/app/models/color.rb b/app/models/color.rb index 1817d4f709..b6cc1110cc 100644 --- a/app/models/color.rb +++ b/app/models/color.rb @@ -2,9 +2,23 @@ class Color class << self + # Finds a Color by its CSS value (e.g. "var(--color-card-4)"). + # Falls back to extracting the value from legacy export formats where + # the Color struct was serialized instead of the raw CSS string. def for_value(value) - COLORS.find { |it| it.value == value } + COLORS.find { |it| it.value == value } || + extract_from_legacy_export(value) end + + private + # Broken exports serialized Color structs instead of raw CSS values, + # producing JSON like {"name":"Lime","value":"var(--color-card-4)"}. + # Parse it and extract the value. + def extract_from_legacy_export(value) + parsed = value.is_a?(String) && JSON.parse(value) + COLORS.find { |it| it.value == parsed["value"] } if parsed.is_a?(Hash) + rescue JSON::ParserError + end end def to_s diff --git a/app/models/event.rb b/app/models/event.rb index bbbf2a60c6..23495326d2 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -9,10 +9,13 @@ class Event < ApplicationRecord has_many :webhook_deliveries, class_name: "Webhook::Delivery", dependent: :delete_all scope :chronologically, -> { order created_at: :asc, id: :desc } + scope :reverse_chronologically, -> { order created_at: :desc, id: :desc } + scope :for_creators, ->(ids) { where(creator_id: ids) if ids.present? } + scope :for_boards, ->(ids) { where(board_id: ids) if ids.present? } scope :preloaded, -> { includes(:creator, :board, { eventable: [ - :goldness, :closure, :image_attachment, + :creator, :goldness, :closure, :image_attachment, { rich_text_body: :embeds_attachments }, { rich_text_description: :embeds_attachments }, { card: [ :goldness, :closure, :image_attachment ] } diff --git a/app/models/event/particulars.rb b/app/models/event/particulars.rb index 31ecd66bfa..d7a133ae2c 100644 --- a/app/models/event/particulars.rb +++ b/app/models/event/particulars.rb @@ -8,4 +8,21 @@ module Event::Particulars def assignees @assignees ||= User.where id: assignee_ids end + + def api_particulars + nested = particulars.dig("particulars") || {} + + case action.to_s + when "card_assigned", "card_unassigned" + { "assignee_ids" => Array(assignee_ids) } + when "card_board_changed" + { "old_board" => nested["old_board"].to_s, "new_board" => nested["new_board"].to_s } + when "card_title_changed" + { "old_title" => nested["old_title"].to_s, "new_title" => nested["new_title"].to_s } + when "card_triaged" + { "column" => nested["column"].to_s } + else + {} + end + end end diff --git a/app/models/export.rb b/app/models/export.rb index 101c9a3790..1ebdebda96 100644 --- a/app/models/export.rb +++ b/app/models/export.rb @@ -2,7 +2,7 @@ class Export < ApplicationRecord belongs_to :account belongs_to :user - has_one_attached :file + has_one_attached :file, dependent: :purge_later enum :status, %w[ pending processing completed failed ].index_by(&:itself), default: :pending diff --git a/app/models/filter.rb b/app/models/filter.rb index 9bfefe176a..63884ea022 100644 --- a/app/models/filter.rb +++ b/app/models/filter.rb @@ -27,7 +27,7 @@ def cards result = result.unassigned if assignment_status.unassigned? result = result.assigned_to(assignees.ids) if assignees.present? result = result.where(creator_id: creators.ids) if creators.present? - result = result.where(board: boards.ids) if boards.present? + result = filter_boards(result) if boards.present? result = result.tagged_with(tags.ids) if tags.present? result = result.where(cards: { created_at: creation_window }) if creation_window result = result.closed_at_window(closure_window) if closure_window @@ -35,6 +35,7 @@ def cards result = terms.reduce(result) do |result, term| result.mentioning(term, user: creator) end + result = result.where(column_id: column_ids) if column_ids.present? result.distinct end @@ -65,6 +66,23 @@ def only_closed? end private + def filter_boards(relation) + relation = relation.where(cards: { account_id: creator.account_id }).where(board: boards.ids) + if joins_has_many? + relation + else + # Pin the (account_id, last_active_at, status) index so the ordered page is served by a reverse scan, not a filesort. + relation.use_index(:index_cards_on_account_id_and_last_active_at_and_status) + end + end + + # Assignee, tag, and term filters add a has-many join that fans a card into + # several rows; the ordered reverse scan loses to a different plan then, so + # the pin only applies without them. + def joins_has_many? + assignees.present? || tags.present? || terms.present? + end + def include_closed_cards? only_closed? || card_ids.present? end diff --git a/app/models/filter/fields.rb b/app/models/filter/fields.rb index 0e1c62e0a4..a41d5ce4a5 100644 --- a/app/models/filter/fields.rb +++ b/app/models/filter/fields.rb @@ -31,7 +31,7 @@ def indexed_by_human_name(index) included do store_accessor :fields, :assignment_status, :indexed_by, :sorted_by, :terms, - :card_ids, :creation, :closure + :card_ids, :creation, :closure, :column_ids def assignment_status super.to_s.inquiry @@ -60,6 +60,14 @@ def terms def terms=(value) super(Array(value).filter(&:present?)) end + + def column_ids + Array(super).filter(&:present?).uniq + end + + def column_ids=(value) + super(Array(value).filter(&:present?).uniq) + end end def with(**fields) diff --git a/app/models/filter/params.rb b/app/models/filter/params.rb index 586a758855..c934970351 100644 --- a/app/models/filter/params.rb +++ b/app/models/filter/params.rb @@ -8,6 +8,7 @@ module Filter::Params :creation, :closure, card_ids: [], + column_ids: [], assignee_ids: [], creator_ids: [], closer_ids: [], diff --git a/app/models/identity.rb b/app/models/identity.rb index ac0accded8..e784e198a5 100644 --- a/app/models/identity.rb +++ b/app/models/identity.rb @@ -9,7 +9,7 @@ class Identity < ApplicationRecord has_many :users, dependent: :nullify has_many :accounts, through: :users - has_one_attached :avatar + has_one_attached :avatar, dependent: :purge_later before_destroy :deactivate_users, prepend: true @@ -41,7 +41,7 @@ def deactivate_users users.find_each(&:deactivate) end - # First created identity becomes staff so admins exist even ohne SMTP/Setup. + # Give self-hosted installations an initial staff administrator. def ensure_first_staff return if staff? return if self.class.where(staff: true).exists? diff --git a/app/models/ssrf_protection.rb b/app/models/ssrf_protection.rb index 40be7d1573..b4390a9ba8 100644 --- a/app/models/ssrf_protection.rb +++ b/app/models/ssrf_protection.rb @@ -8,10 +8,49 @@ module SsrfProtection 8.8.8.8 ] + # IPv4 ranges that must never be a fetch target (RFC 5735/6890 special-use, + # plus CGNAT and benchmarking). RFC1918/loopback/link-local are also covered + # by the IPAddr predicates in #blocked_address?. DISALLOWED_IP_RANGES = [ - IPAddr.new("0.0.0.0/8"), # "This" network (RFC1700) - IPAddr.new("100.64.0.0/10"), # Carrier-grade NAT (RFC6598) - IPAddr.new("198.18.0.0/15") # Benchmark testing (RFC2544) + IPAddr.new("0.0.0.0/8"), # "This" network (RFC1700) + IPAddr.new("10.0.0.0/8"), # Private (RFC1918) + IPAddr.new("100.64.0.0/10"), # Carrier-grade NAT (RFC6598) + IPAddr.new("127.0.0.0/8"), # Loopback + IPAddr.new("169.254.0.0/16"), # Link-local (incl. AWS metadata) + IPAddr.new("172.16.0.0/12"), # Private (RFC1918) + IPAddr.new("192.0.0.0/24"), # IETF protocol assignments (RFC6890) + IPAddr.new("192.0.2.0/24"), # TEST-NET-1 (RFC5737) + IPAddr.new("192.88.99.0/24"), # 6to4 relay anycast (RFC7526) + IPAddr.new("192.168.0.0/16"), # Private (RFC1918) + IPAddr.new("198.18.0.0/15"), # Benchmark testing (RFC2544) + IPAddr.new("198.51.100.0/24"), # TEST-NET-2 (RFC5737) + IPAddr.new("203.0.113.0/24"), # TEST-NET-3 (RFC5737) + IPAddr.new("224.0.0.0/4"), # Multicast (RFC5771) + IPAddr.new("240.0.0.0/4") # Reserved / future use (RFC1112) + ].freeze + + # IPv6 special-use ranges not caught by the predicates. 6to4 (2002::/16) and + # Teredo (2001::/32) are deprecated transition mechanisms with no legitimate + # fetch target, so they are blocked outright. ULA (fc00::/7, incl. AWS + # IMDSv6 fd00:ec2::254), link-local, and loopback are covered by the predicates. + DISALLOWED_IPV6_RANGES = [ + IPAddr.new("::/128"), # Unspecified + IPAddr.new("100::/64"), # Discard-only (RFC6666) + IPAddr.new("2001::/32"), # Teredo (RFC4380) + IPAddr.new("2001:2::/48"), # Benchmark testing (RFC5180) + IPAddr.new("2001:db8::/32"), # Documentation (RFC3849) + IPAddr.new("2002::/16"), # 6to4 (RFC3056) + IPAddr.new("fec0::/10"), # Deprecated site-local (RFC3879) + IPAddr.new("ff00::/8") # Multicast (RFC4291) + ].freeze + + # NAT64 prefixes: the well-known prefix (RFC 6052/6146) and the local-use + # prefix (RFC 8215). An address here embeds an IPv4 target in its low 32 + # bits; extract it and re-check against the IPv4 rules so NAT64 to a public + # address still resolves while NAT64 to an internal address is blocked. + NAT64_PREFIXES = [ + IPAddr.new("64:ff9b::/96"), + IPAddr.new("64:ff9b:1::/48") ].freeze def resolve_public_ip(hostname) @@ -21,14 +60,21 @@ def resolve_public_ip(hostname) end def blocked_address?(ip) - ip = IPAddr.new(ip.to_s) unless ip.is_a?(IPAddr) - - ip.private? || - ip.loopback? || - ip.link_local? || - ip.ipv4_mapped? || - ip.ipv4_compat? || - in_disallowed_range?(ip) + ipaddr = ip.is_a?(IPAddr) ? ip : IPAddr.new(ip.to_s) + + # DNS never legitimately returns these embedded forms, so block them all + # regardless of the address they wrap. + if ipaddr.ipv4_mapped? || ipaddr.ipv4_compat? + true + elsif ipaddr.ipv4? + disallowed_ipv4?(ipaddr) + elsif NAT64_PREFIXES.any? { |prefix| prefix.include?(ipaddr) } + disallowed_ipv4?(embedded_ipv4(ipaddr)) + else + disallowed_ipv6?(ipaddr) + end + rescue IPAddr::InvalidAddressError + true end private @@ -44,7 +90,17 @@ def resolve_dns(hostname) ip_addresses end - def in_disallowed_range?(ip) - DISALLOWED_IP_RANGES.any? { |range| range.include?(ip) } + def disallowed_ipv4?(ipaddr) + ipaddr.private? || ipaddr.loopback? || ipaddr.link_local? || + DISALLOWED_IP_RANGES.any? { |range| range.include?(ipaddr) } + end + + def disallowed_ipv6?(ipaddr) + ipaddr.private? || ipaddr.loopback? || ipaddr.link_local? || + DISALLOWED_IPV6_RANGES.any? { |range| range.include?(ipaddr) } + end + + def embedded_ipv4(ipaddr) + IPAddr.new([ ipaddr.to_i & 0xffffffff ].pack("N").unpack("C4").join(".")) end end diff --git a/app/models/storage/entry.rb b/app/models/storage/entry.rb index 768a4c6f81..cb1e25c6ec 100644 --- a/app/models/storage/entry.rb +++ b/app/models/storage/entry.rb @@ -5,12 +5,22 @@ class Storage::Entry < ApplicationRecord scope :pending, ->(last_entry_id) { where.not(id: ..last_entry_id) if last_entry_id } + thread_mattr_accessor :recording, default: true + + def self.suppressing_recording(&block) + original, self.recording = self.recording, false + yield + ensure + self.recording = original + end + # Records may be destroyed (during cascading deletes) but .id still works. # Skip entirely if account is destroyed - no need to track storage for deleted accounts. # Skip materialize jobs for destroyed boards since there's nothing to update. def self.record(delta:, operation:, account:, board: nil, recordable: nil, blob: nil) return if delta.zero? return if account.destroyed? + return unless recording entry = create! \ account_id: account.id, diff --git a/app/models/tag.rb b/app/models/tag.rb index 192f0b86e6..14d73b4c4d 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -1,5 +1,5 @@ class Tag < ApplicationRecord - include Attachable, Filterable + include Filterable belongs_to :account, default: -> { Current.account } has_many :taggings, dependent: :destroy diff --git a/app/models/tag/attachable.rb b/app/models/tag/attachable.rb deleted file mode 100644 index 37d95b2ddd..0000000000 --- a/app/models/tag/attachable.rb +++ /dev/null @@ -1,11 +0,0 @@ -module Tag::Attachable - extend ActiveSupport::Concern - - included do - include ActionText::Attachable - - def attachable_plain_text_representation(...) - "##{title}" - end - end -end diff --git a/app/models/user/avatar.rb b/app/models/user/avatar.rb index 970104d6f4..bdc14ba771 100644 --- a/app/models/user/avatar.rb +++ b/app/models/user/avatar.rb @@ -11,7 +11,7 @@ module User::Avatar ].freeze included do - has_one_attached :avatar do |attachable| + has_one_attached :avatar, dependent: :purge_later do |attachable| attachable.variant :thumb, resize_to_fill: [ 256, 256 ], process: :immediately end @@ -39,7 +39,7 @@ def publicly_accessible? private def avatar_content_type_allowed - if !ALLOWED_AVATAR_CONTENT_TYPES.include?(avatar.content_type) + unless ALLOWED_AVATAR_CONTENT_TYPES.include?(avatar.content_type) errors.add(:avatar, "must be a JPEG, PNG, GIF, or WebP image") end end diff --git a/app/models/user/day_timeline.rb b/app/models/user/day_timeline.rb index 4b30d24ca6..137122f5a7 100644 --- a/app/models/user/day_timeline.rb +++ b/app/models/user/day_timeline.rb @@ -42,7 +42,7 @@ def closed_column end def cache_key - ActiveSupport::Cache.expand_cache_key [ user, filter, day.to_date, events ], "day-timeline" + ActiveSupport::Cache.expand_cache_key [ user, filter, day.to_date, Time.zone.name, events ], "day-timeline" end private diff --git a/app/models/user/mentionable.rb b/app/models/user/mentionable.rb index be82f3d95e..87b2c0f21d 100644 --- a/app/models/user/mentionable.rb +++ b/app/models/user/mentionable.rb @@ -8,6 +8,10 @@ module User::Mentionable def to_attachable_partial_path "users/attachable" end + + def to_editor_content_attachment_partial_path + to_attachable_partial_path + end end def mentioned_by(mentioner, at:) diff --git a/app/models/webhook/delivery.rb b/app/models/webhook/delivery.rb index 40dab42f00..952aab1288 100644 --- a/app/models/webhook/delivery.rb +++ b/app/models/webhook/delivery.rb @@ -44,6 +44,18 @@ def deliver raise end + def sanitized_request + if headers = request&.dig("headers")&.except("X-Webhook-Signature") + { headers: headers } + end + end + + def response_summary + if response.present? + { code: response[:code], error: response[:error] } + end + end + def failed? (errored? || completed?) && !succeeded? end diff --git a/app/views/activities/_activity.json.jbuilder b/app/views/activities/_activity.json.jbuilder new file mode 100644 index 0000000000..5585ac1fe3 --- /dev/null +++ b/app/views/activities/_activity.json.jbuilder @@ -0,0 +1,21 @@ +json.(event, :id, :action) +json.created_at event.created_at.utc +json.description event.description_for(Current.user).to_plain_text +json.particulars event.api_particulars +json.url( + case event.eventable + when Comment then card_url(event.eventable.card, anchor: dom_id(event.eventable)) + else polymorphic_url(event.eventable) + end +) +json.eventable_type event.eventable_type + +json.eventable do + case event.eventable + when Card then json.partial! "cards/card", card: event.eventable + when Comment then json.partial! "cards/comments/comment", comment: event.eventable + end +end + +json.board event.board, partial: "boards/board", as: :board +json.creator event.creator, partial: "users/user", as: :user diff --git a/app/views/activities/index.json.jbuilder b/app/views/activities/index.json.jbuilder new file mode 100644 index 0000000000..1e40481842 --- /dev/null +++ b/app/views/activities/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @page.records, partial: "activities/activity", as: :event diff --git a/app/views/boards/_board.json.jbuilder b/app/views/boards/_board.json.jbuilder index 0eeff18968..586835c38b 100644 --- a/app/views/boards/_board.json.jbuilder +++ b/app/views/boards/_board.json.jbuilder @@ -6,5 +6,9 @@ json.cache! board do json.creator board.creator, partial: "users/user", as: :user - json.public_url published_board_url(board) if board.published? + if board.published? + json.public_description board.public_description.to_plain_text + json.public_description_html board.public_description.to_s + json.public_url published_board_url(board) + end end diff --git a/app/views/boards/accesses/index.json.jbuilder b/app/views/boards/accesses/index.json.jbuilder new file mode 100644 index 0000000000..37498fc1fb --- /dev/null +++ b/app/views/boards/accesses/index.json.jbuilder @@ -0,0 +1,8 @@ +json.board_id @board.id +json.all_access @board.all_access? + +json.users @page.records do |user| + json.partial! "users/user", user: user + json.has_access involvement_by_user.key?(user.id) + json.involvement involvement_by_user[user.id] +end diff --git a/app/views/boards/columns/cards/index.json.jbuilder b/app/views/boards/columns/cards/index.json.jbuilder new file mode 100644 index 0000000000..c1dc1dff15 --- /dev/null +++ b/app/views/boards/columns/cards/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @page.records, partial: "cards/card", as: :card diff --git a/app/views/boards/show.json.jbuilder b/app/views/boards/show.json.jbuilder index a6916c4673..08c3456605 100644 --- a/app/views/boards/show.json.jbuilder +++ b/app/views/boards/show.json.jbuilder @@ -1 +1,2 @@ json.partial! "boards/board", board: @board +json.user_ids @board.users.ids unless @board.all_access? diff --git a/app/views/cards/container/_content.html.erb b/app/views/cards/container/_content.html.erb index 5da73f266d..b43af4d572 100644 --- a/app/views/cards/container/_content.html.erb +++ b/app/views/cards/container/_content.html.erb @@ -1,5 +1,4 @@ <% if card.published? %> -
<%= turbo_frame_tag card, :edit do %> <%# When canceling an edit (with the ESC key), restore the button area to show "Edit" instead of "Save changes". %> <%= turbo_stream.replace dom_id(card, :card_closure_toggle) do %> @@ -8,7 +7,6 @@ <%= render "cards/container/content_display", card: card %> <% end %> -
<% else %> <%= form_with model: card, id: "card_form", data: { controller: "autoresize auto-save" } do |form| %>

diff --git a/app/views/cards/edit.html.erb b/app/views/cards/edit.html.erb index 1e81896a17..f748d360cf 100644 --- a/app/views/cards/edit.html.erb +++ b/app/views/cards/edit.html.erb @@ -7,7 +7,7 @@ <% end %> <%= form_with model: @card, id: dom_id(@card, :edit_form), - data: { controller: "autoresize form local-save", local_save_key_value: "card-#{@card.id}", action: "turbo:submit-end->local-save#submit" } do |form| %> + data: { controller: "autoresize form local-save morph-guard", local_save_key_value: "card-#{@card.id}", action: "turbo:submit-end->local-save#submit" } do |form| %>

<%= form.label :title, class: "flex flex-column align-center autoresize__wrapper", data: { autoresize_target: "wrapper", autoresize_clone_value: "" } do %> <%= form.text_area :title, class: "card-field__title autoresize__textarea input input--textarea full-width borderless txt-align-start hide-focus-ring hide-scrollbar", diff --git a/app/views/columns/_column.json.jbuilder b/app/views/columns/_column.json.jbuilder index 5bb56bdd6f..16f5604d06 100644 --- a/app/views/columns/_column.json.jbuilder +++ b/app/views/columns/_column.json.jbuilder @@ -1,4 +1,5 @@ json.cache! column do json.(column, :id, :name, :color) json.created_at column.created_at.utc + json.cards_url board_column_cards_url(column.board, column) end diff --git a/app/views/events/day_timeline/_columns.html.erb b/app/views/events/day_timeline/_columns.html.erb index 80752d9add..16d09ed07d 100644 --- a/app/views/events/day_timeline/_columns.html.erb +++ b/app/views/events/day_timeline/_columns.html.erb @@ -1,4 +1,4 @@ -<% cache [ day_timeline.events ] do %> +<% cache [ day_timeline.events, Time.zone.name ] do %> <%# Template Dependency Updated: _layout.html.erb 2026-01-26 %> <% if day_timeline.has_activity? %>
diff --git a/app/views/layouts/shared/_head.html.erb b/app/views/layouts/shared/_head.html.erb index 9ef153df2b..bddd34b4a4 100644 --- a/app/views/layouts/shared/_head.html.erb +++ b/app/views/layouts/shared/_head.html.erb @@ -11,6 +11,7 @@ <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= tag.meta name: "current-user-id", content: Current.user.id if Current.user %> + <%= tag.meta name: "timezone", content: Time.zone.name %> <%= tag.meta name: "vapid-public-key", content: Rails.configuration.x.vapid.public_key %> <% turbo_refreshes_with method: :morph, scroll: :preserve %> diff --git a/app/views/notifications/_notification.json.jbuilder b/app/views/notifications/_notification.json.jbuilder index ae166f44ab..2b11165172 100644 --- a/app/views/notifications/_notification.json.jbuilder +++ b/app/views/notifications/_notification.json.jbuilder @@ -15,7 +15,11 @@ json.cache! notification do json.closed notification.card.closed? json.postponed notification.card.postponed? json.url card_url(notification.card) - json.column notification.card.column, partial: "columns/column", as: :column if notification.card.column + if notification.card.column + json.column notification.card.column, partial: "columns/column", as: :column + else + json.column nil + end end json.url notification_url(notification) diff --git a/app/views/prompts/tags/_tag.html.erb b/app/views/prompts/tags/_tag.html.erb deleted file mode 100644 index 3be999a8ef..0000000000 --- a/app/views/prompts/tags/_tag.html.erb +++ /dev/null @@ -1,8 +0,0 @@ - - - - diff --git a/app/views/prompts/tags/index.html.erb b/app/views/prompts/tags/index.html.erb deleted file mode 100644 index 7ff9bbb1fc..0000000000 --- a/app/views/prompts/tags/index.html.erb +++ /dev/null @@ -1 +0,0 @@ -<%= render partial: "prompts/tags/tag", collection: @tags %> diff --git a/app/views/pwa/service_worker.js.erb b/app/views/pwa/service_worker.js.erb index 41fac14463..efbbee06c5 100644 --- a/app/views/pwa/service_worker.js.erb +++ b/app/views/pwa/service_worker.js.erb @@ -42,8 +42,10 @@ TurboOffline.addRule({ maxAge: 60 * 60 * 24 * 7, networkTimeout: 2, maxEntrySize: 2 * 1024 * 1024, // 2MB covers about 95% of all Fizzy blobs - maxEntries: 500, - fetchOptions: { mode: "cors" } +<% if ENV["SERVICE_WORKER_CORS_ENABLED"] != "false" -%> + fetchOptions: { mode: "cors" }, +<% end -%> + maxEntries: 500 }) }) diff --git a/app/views/reactions/_reactions.html.erb b/app/views/reactions/_reactions.html.erb index 14237799a1..f990db4eb9 100644 --- a/app/views/reactions/_reactions.html.erb +++ b/app/views/reactions/_reactions.html.erb @@ -6,8 +6,8 @@ <%= turbo_frame_tag reactable, :new_reaction do %> <%= link_to new_polymorphic_path([ *reaction_path_prefix_for(reactable), :reaction ]), role: "button", - class: "reactions__trigger btn btn--circle", action: "soft-keyboard#open", - data: { turbo_frame: dom_id(reactable, :new_reaction), action: "dialog#close" } do %> + class: "reactions__trigger btn btn--circle", + data: { controller: "tooltip soft-keyboard", turbo_frame: dom_id(reactable, :new_reaction), action: "dialog#close soft-keyboard#open" } do %> <%= image_tag "boost-color.svg", aria: { hidden: true } %> Add your own reaction <% end %> diff --git a/app/views/sessions/menus/show.html.erb b/app/views/sessions/menus/show.html.erb index cc0597a37f..489b131d7f 100644 --- a/app/views/sessions/menus/show.html.erb +++ b/app/views/sessions/menus/show.html.erb @@ -1,6 +1,6 @@ <% @page_title = "Choose an account" %> -<% cache [ Current.identity, @accounts ] do %> +<% cache [ Current.identity, @accounts, signups_allowed? ] do %>
<% if signups_allowed? && Account.accepting_signups? %> -

New here? <%= link_to "Sign up", new_signup_path %> to create an account. Already have an account? Enter your email and we'll get you signed in.

+

New here? <%= link_to "Sign up", new_signup_path %> to create an account. Already have an account? Enter your email and we’ll get you signed in.

<% else %> -

Enter your email and we'll get you signed in.

+

Enter your email and we’ll get you signed in.

<% end %> <% end %> diff --git a/app/views/users/data_exports/show.json.jbuilder b/app/views/users/data_exports/show.json.jbuilder new file mode 100644 index 0000000000..2bd9e3d60a --- /dev/null +++ b/app/views/users/data_exports/show.json.jbuilder @@ -0,0 +1,6 @@ +json.(@export, :id, :status) +json.created_at @export.created_at.utc + +if @export.completed? && @export.file.attached? + json.download_url rails_blob_url(@export.file, disposition: "attachment") +end diff --git a/app/views/webhooks/deliveries/_delivery.json.jbuilder b/app/views/webhooks/deliveries/_delivery.json.jbuilder new file mode 100644 index 0000000000..0fa8d92b3a --- /dev/null +++ b/app/views/webhooks/deliveries/_delivery.json.jbuilder @@ -0,0 +1,10 @@ +json.cache! delivery do + json.(delivery, :id, :state) + json.created_at delivery.created_at.utc + json.updated_at delivery.updated_at.utc + + json.request delivery.sanitized_request + json.response delivery.response_summary + + json.event delivery.event, partial: "webhooks/deliveries/event", as: :event +end diff --git a/app/views/webhooks/deliveries/_event.json.jbuilder b/app/views/webhooks/deliveries/_event.json.jbuilder new file mode 100644 index 0000000000..311a736910 --- /dev/null +++ b/app/views/webhooks/deliveries/_event.json.jbuilder @@ -0,0 +1,15 @@ +json.cache! [ event, event.creator, event.eventable ] do + json.(event, :id, :action) + json.created_at event.created_at.utc + + json.creator do + json.id event.creator_id + json.name event.creator.name + end + + json.eventable do + json.type event.eventable_type + json.id event.eventable_id + json.url polymorphic_url(event.eventable) + end +end diff --git a/app/views/webhooks/deliveries/index.json.jbuilder b/app/views/webhooks/deliveries/index.json.jbuilder new file mode 100644 index 0000000000..8df50813b4 --- /dev/null +++ b/app/views/webhooks/deliveries/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @page.records, partial: "webhooks/deliveries/delivery", as: :delivery diff --git a/bin/bundle-drift b/bin/bundle-drift index 08ea3713de..ee1e7c4bcb 100755 --- a/bin/bundle-drift +++ b/bin/bundle-drift @@ -3,9 +3,10 @@ # Since Gemfile.saas evals Gemfile, shared gems should have identical versions. # # Usage: -# bin/bundle-drift [check] # check for drift (default subcommand) -# bin/bundle-drift correct # restore alignment (Gemfile.saas.lock is authoritative) -# bin/bundle-drift forward # push Gemfile.lock changes into Gemfile.saas.lock +# bin/bundle-drift [check] # check for drift (default subcommand) +# bin/bundle-drift correct # restore alignment (Gemfile.saas.lock is authoritative) +# bin/bundle-drift forward # push Gemfile.lock changes into Gemfile.saas.lock +# bin/bundle-drift self-test # run built-in tests require "bundler" require "fileutils" @@ -31,38 +32,98 @@ class GemfileDriftChecker def find_drift oss_specs, saas_specs = specs_hash(@oss_lockfile), specs_hash(@saas_lockfile) + oss_deps, saas_deps = deps_hash(@oss_lockfile), deps_hash(@saas_lockfile) + oss_sdeps, saas_sdeps = spec_deps_hash(@oss_lockfile), spec_deps_hash(@saas_lockfile) shared_gems = oss_specs.keys & saas_specs.keys + shared_deps = oss_deps.keys & saas_deps.keys + missing_gems = oss_specs.keys - saas_specs.keys - shared_gems.filter_map do |name| + shared_drift = shared_gems.filter_map do |name| oss_version, saas_version = oss_specs[name], saas_specs[name] - if oss_version != saas_version - { name: name, oss: oss_version, saas: saas_version } + version_drift = oss_version != saas_version + + oss_dep, saas_dep = oss_deps[name], saas_deps[name] + dep_drift = shared_deps.include?(name) && oss_dep != saas_dep + + oss_sd, saas_sd = oss_sdeps[name] || {}, saas_sdeps[name] || {} + subdep_changes = (oss_sd.keys | saas_sd.keys).filter_map do |dep_name| + if oss_sd[dep_name] != saas_sd[dep_name] + { name: dep_name, oss: oss_sd[dep_name], saas: saas_sd[dep_name] } + end + end + + if version_drift || dep_drift || subdep_changes.any? + { name: name, oss: oss_version, saas: saas_version, oss_dep: oss_dep, saas_dep: saas_dep, subdep_changes: subdep_changes } end - end.sort_by { |d| d[:name] } + end + + missing_drift = missing_gems.map do |name| + { name: name, oss: oss_specs[name], saas: nil, missing: true } + end + + (shared_drift + missing_drift).sort_by { |d| d[:name] } end def specs_hash(lockfile) lockfile.specs.to_h { |spec| [ spec.name, spec.version.to_s ] } end + def deps_hash(lockfile) + lockfile.dependencies.transform_values { |dep| dep.requirement.to_s } + end + + def spec_deps_hash(lockfile) + lockfile.specs.to_h do |spec| + [spec.name, spec.dependencies.map { |d| [d.name, d.requirement.to_s] }.sort.to_h] + end + end + def report(drift) if drift.empty? puts "✓ Gemfile.lock and Gemfile.saas.lock are in sync" else puts "✗ Gemfile lock files have drifted!\n\n" - name_width = [ drift.map { |d| d[:name].length }.max, "Gem".length ].max - oss_width = [ drift.map { |d| d[:oss].length }.max, "Gemfile.lock".length ].max - saas_width = [ drift.map { |d| d[:saas].length }.max, "Gemfile.saas.lock".length ].max + missing = drift.select { |d| d[:missing] } + spec_drift = drift.select { |d| !d[:missing] && d[:oss] != d[:saas] } + dep_drift = drift.select { |d| !d[:missing] && d[:oss_dep] != d[:saas_dep] } - puts " #{"Gem".ljust(name_width)} #{"Gemfile.lock".ljust(oss_width)} Gemfile.saas.lock" - puts " #{"-" * name_width} #{"-" * oss_width} #{"-" * saas_width}" + if missing.any? + puts " Gems missing from Gemfile.saas.lock:" + missing.each do |d| + puts " #{d[:name]} (#{d[:oss]})" + end + end + + if spec_drift.any? + puts " Spec versions:" + spec_drift.each do |d| + puts " #{d[:name]}: #{d[:oss]} (Gemfile.lock) vs #{d[:saas]} (Gemfile.saas.lock)" + end + end - drift.each do |d| - puts " #{d[:name].ljust(name_width)} #{d[:oss].ljust(oss_width)} #{d[:saas]}" + if dep_drift.any? + puts " Dependency requirements:" + dep_drift.each do |d| + puts " #{d[:name]}: #{d[:oss_dep]} (Gemfile.lock) vs #{d[:saas_dep]} (Gemfile.saas.lock)" + end end - puts "\nRun 'bin/bundle-drift correct' to restore alignment." + subdep_drift = drift.select { |d| d[:subdep_changes]&.any? } + if subdep_drift.any? + puts " Spec sub-dependency requirements:" + subdep_drift.each do |d| + d[:subdep_changes].each do |sd| + puts " #{d[:name]} → #{sd[:name]}: #{sd[:oss] || "(absent)"} (Gemfile.lock) vs #{sd[:saas] || "(absent)"} (Gemfile.saas.lock)" + end + end + end + + if missing.any? + puts "\nRun 'bin/bundle-drift forward' to add the missing gems to Gemfile.saas.lock." + else + puts "\nRun 'bin/bundle-drift correct' to restore alignment." + end end end end @@ -74,13 +135,10 @@ class GemfileDriftCorrector puts "\nRestoring alignment (Gemfile.saas.lock is authoritative)...\n\n" - # Save original for diff original_content = File.read(GEMFILE_LOCK) - # Seed Gemfile.lock with Gemfile.saas.lock - Bundler will use these as version hints FileUtils.cp(GEMFILE_SAAS_LOCK, GEMFILE_LOCK) - # Re-lock: Bundler prunes SaaS-only gems while preserving shared versions puts "▸ Re-locking Gemfile (seeded from Gemfile.saas.lock)" unless system("BUNDLE_GEMFILE=Gemfile bundle lock") File.write(GEMFILE_LOCK, original_content) @@ -124,35 +182,107 @@ class GemfileDriftForwarder drift = GemfileDriftChecker.new.check return puts "\nNothing to forward." if drift.empty? - puts "\nForwarding Gemfile.lock versions into Gemfile.saas.lock...\n\n" + if drift.any? { |d| d[:missing] } + relock_saas + drift = GemfileDriftChecker.new.check + return if drift.empty? + end + + patch_saas(drift) + end - original_content = File.read(GEMFILE_SAAS_LOCK) - patched_content = original_content.dup + private + def relock_saas + original_content = File.read(GEMFILE_SAAS_LOCK) - drift.each do |d| - puts " #{d[:name]} (#{d[:saas]}) → #{d[:name]} (#{d[:oss]})" - patched_content.gsub!(/#{Regexp.escape(d[:name])} \(#{Regexp.escape(d[:saas])}([^)]*)\)/) do - "#{d[:name]} (#{d[:oss]}#{$1})" + puts "\n▸ Re-locking Gemfile.saas (to add gems missing from Gemfile.saas.lock)" + unless system("BUNDLE_GEMFILE=Gemfile.saas bundle lock") + File.write(GEMFILE_SAAS_LOCK, original_content) + abort("Failed to lock Gemfile.saas. Restored original.") end end - File.write(GEMFILE_SAAS_LOCK, patched_content) + def patch_saas(drift) + puts "\nForwarding Gemfile.lock changes into Gemfile.saas.lock...\n\n" - puts "\n▸ Verifying alignment" - new_drift = GemfileDriftChecker.new.check + original_content = File.read(GEMFILE_SAAS_LOCK) + patched_content = original_content.dup - if new_drift.empty? - puts "\n✓ Lock files are now in sync" - show_diff(original_content, patched_content) - else - puts "\n✗ Lock files still have drift after forwarding." - puts " Restoring original Gemfile.saas.lock." - File.write(GEMFILE_SAAS_LOCK, original_content) - exit 1 + drift.each do |d| + next if d[:missing] + + if d[:oss] != d[:saas] + puts " #{d[:name]}: spec #{d[:saas]} → #{d[:oss]}" + patched_content.gsub!(/#{Regexp.escape(d[:name])} \(#{Regexp.escape(d[:saas])}([^)]*)\)/) do + "#{d[:name]} (#{d[:oss]}#{$1})" + end + end + + if d[:oss_dep] && d[:saas_dep] && d[:oss_dep] != d[:saas_dep] + puts " #{d[:name]}: dep #{d[:saas_dep]} → #{d[:oss_dep]}" + patched_content = patch_dependency_requirement(patched_content, d[:name], d[:saas_dep], d[:oss_dep]) + end + + if d[:subdep_changes]&.any? + d[:subdep_changes].each do |sd| + if sd[:oss] && sd[:saas] + puts " #{d[:name]} → #{sd[:name]}: subdep #{sd[:saas]} → #{sd[:oss]}" + patched_content = patch_spec_subdependency(patched_content, d[:name], sd[:name], sd[:saas], sd[:oss]) + end + end + end + end + + File.write(GEMFILE_SAAS_LOCK, patched_content) + + puts "\n▸ Verifying alignment" + new_drift = GemfileDriftChecker.new.check + + if new_drift.empty? + puts "\n✓ Lock files are now in sync" + show_diff(original_content, patched_content) + else + puts "\n✗ Lock files still have drift after forwarding." + puts " Restoring original Gemfile.saas.lock." + File.write(GEMFILE_SAAS_LOCK, original_content) + exit 1 + end + end + + def patch_spec_subdependency(content, parent_name, dep_name, old_req, new_req) + in_parent_spec = false + content.lines.map do |line| + if line.match?(/\A {4}\S/) + in_parent_spec = line.match?(/\A {4}#{Regexp.escape(parent_name)} \(/) + elsif !line.match?(/\A {6}/) + in_parent_spec = false + end + + if in_parent_spec && line.match?(/\A {6}#{Regexp.escape(dep_name)} \(#{Regexp.escape(old_req)}\)/) + line.sub("#{dep_name} (#{old_req})", "#{dep_name} (#{new_req})") + else + line + end + end.join + end + + def patch_dependency_requirement(content, name, old_req, new_req) + in_deps = false + content.lines.map do |line| + if line.strip == "DEPENDENCIES" + in_deps = true + elsif in_deps && line.match?(/\A\S/) + in_deps = false + end + + if in_deps + line.sub(/#{Regexp.escape(name)} \(#{Regexp.escape(old_req)}\)/, "#{name} (#{new_req})") + else + line + end + end.join end - end - private def show_diff(original, patched) require "tempfile" @@ -176,6 +306,199 @@ when "correct" GemfileDriftCorrector.new.correct when "forward" GemfileDriftForwarder.new.forward +when "self-test" + require "minitest/autorun" + require "tmpdir" + + LOCKFILE_TEMPLATE = <<~LOCKFILE + GEM + remote: https://rubygems.org/ + specs: + shared_gem (%{shared_version}) + oss_only_gem (1.0.0) + saas_only_gem (2.0.0) + + PLATFORMS + ruby + + DEPENDENCIES + %{dependencies} + + BUNDLED WITH + 2.6.2 + LOCKFILE + + LOCKFILE_WITH_SUBDEPS_TEMPLATE = <<~LOCKFILE + GEM + remote: https://rubygems.org/ + specs: + child_gem (%{child_version}) + parent_gem (%{parent_version}) + child_gem (%{child_req}) + + PLATFORMS + ruby + + DEPENDENCIES + parent_gem (%{parent_dep}) + + BUNDLED WITH + 2.6.2 + LOCKFILE + + class GemfileDriftCheckerTest < Minitest::Test + def setup + @original_dir = Dir.pwd + @tmpdir = Dir.mktmpdir("bundle-drift-test") + Dir.chdir(@tmpdir) + end + + def teardown + Dir.chdir(@original_dir) + FileUtils.rm_rf(@tmpdir) + end + + def test_detects_spec_version_drift + write_lockfiles( + oss_version: "1.0.0", oss_deps: " shared_gem (~> 1.0)\n oss_only_gem", + saas_version: "2.0.0", saas_deps: " shared_gem (~> 2.0)\n saas_only_gem" + ) + + drift = GemfileDriftChecker.new.send(:find_drift) + + assert_equal 1, drift.length + assert_equal "shared_gem", drift.first[:name] + end + + def test_detects_dependency_requirement_drift_even_when_spec_versions_match + write_lockfiles( + oss_version: "1.4.0", oss_deps: " shared_gem (~> 1.4)\n oss_only_gem", + saas_version: "1.4.0", saas_deps: " shared_gem (~> 1.3)\n saas_only_gem" + ) + + drift = GemfileDriftChecker.new.send(:find_drift) + + assert_equal 1, drift.length + assert_equal "shared_gem", drift.first[:name] + end + + def test_reports_no_drift_when_specs_and_dependencies_match + write_lockfiles( + oss_version: "1.4.0", oss_deps: " shared_gem (~> 1.4)\n oss_only_gem", + saas_version: "1.4.0", saas_deps: " shared_gem (~> 1.4)\n saas_only_gem" + ) + + drift = GemfileDriftChecker.new.send(:find_drift) + + assert_empty drift + end + + def test_forward_patches_dependency_requirements_in_addition_to_spec_versions + write_lockfiles( + oss_version: "1.4.0", oss_deps: " shared_gem (~> 1.4)\n oss_only_gem", + saas_version: "1.3.2", saas_deps: " shared_gem (~> 1.3)\n saas_only_gem" + ) + + capture_io { GemfileDriftForwarder.new.forward } + + saas_content = File.read("Gemfile.saas.lock") + assert_includes saas_content, "shared_gem (1.4.0)" + assert_includes saas_content, "shared_gem (~> 1.4)" + refute_includes saas_content, "shared_gem (~> 1.3)" + end + + def test_detects_gem_in_oss_lock_missing_from_saas_lock + File.write("Gemfile.lock", <<~LOCK) + GEM + remote: https://rubygems.org/ + specs: + new_gem (1.0.0) + shared_gem (1.0.0) + + PLATFORMS + ruby + + DEPENDENCIES + new_gem + shared_gem + + BUNDLED WITH + 2.6.2 + LOCK + + File.write("Gemfile.saas.lock", <<~LOCK) + GEM + remote: https://rubygems.org/ + specs: + shared_gem (1.0.0) + + PLATFORMS + ruby + + DEPENDENCIES + shared_gem + + BUNDLED WITH + 2.6.2 + LOCK + + drift = GemfileDriftChecker.new.send(:find_drift) + + assert_equal 1, drift.length + assert_equal "new_gem", drift.first[:name] + assert drift.first[:missing] + end + + def test_detects_spec_subdependency_drift_even_when_versions_match + write_lockfiles_with_subdeps( + oss_child_req: "~> 3, >= 3.2.0", + saas_child_req: "~> 3, >= 3.1.0" + ) + + drift = GemfileDriftChecker.new.send(:find_drift) + + assert_equal 1, drift.length + assert_equal "parent_gem", drift.first[:name] + assert_equal 1, drift.first[:subdep_changes].length + assert_equal "child_gem", drift.first[:subdep_changes].first[:name] + end + + def test_no_drift_when_spec_subdependencies_match + write_lockfiles_with_subdeps( + oss_child_req: "~> 3, >= 3.2.0", + saas_child_req: "~> 3, >= 3.2.0" + ) + + drift = GemfileDriftChecker.new.send(:find_drift) + + assert_empty drift + end + + def test_forward_patches_spec_subdependency_requirements + write_lockfiles_with_subdeps( + oss_child_req: "~> 3, >= 3.2.0", + saas_child_req: "~> 3, >= 3.1.0" + ) + + capture_io { GemfileDriftForwarder.new.forward } + + saas_content = File.read("Gemfile.saas.lock") + assert_includes saas_content, "child_gem (~> 3, >= 3.2.0)" + refute_includes saas_content, "child_gem (~> 3, >= 3.1.0)" + end + + private + def write_lockfiles(oss_version:, oss_deps:, saas_version:, saas_deps:) + File.write("Gemfile.lock", LOCKFILE_TEMPLATE % { shared_version: oss_version, dependencies: oss_deps }) + File.write("Gemfile.saas.lock", LOCKFILE_TEMPLATE % { shared_version: saas_version, dependencies: saas_deps }) + end + + def write_lockfiles_with_subdeps(oss_child_req:, saas_child_req:) + common = { parent_version: "1.0.0", child_version: "3.2.0", parent_dep: "~> 1.0" } + File.write("Gemfile.lock", LOCKFILE_WITH_SUBDEPS_TEMPLATE % common.merge(child_req: oss_child_req)) + File.write("Gemfile.saas.lock", LOCKFILE_WITH_SUBDEPS_TEMPLATE % common.merge(child_req: saas_child_req)) + end + end else - abort "Usage: bin/bundle-drift [check|correct|forward]" + abort "Usage: bin/bundle-drift [check|correct|forward|self-test]" end diff --git a/bin/dev b/bin/dev index 4c11aa3b04..c8174be613 100755 --- a/bin/dev +++ b/bin/dev @@ -4,6 +4,15 @@ PORT=3006 USE_TAILSCALE=0 USE_PUSH=0 +if [ -t 1 ]; then + c_bar='\033[2m▎\033[0m' # dim + c_label='\033[37m' # gray + c_url='\033[96m' # cyan + c_reset='\033[0m' +else + c_bar='▎' c_label='' c_url='' c_reset='' +fi + for arg in "$@"; do case $arg in --tailscale) USE_TAILSCALE=1 ;; @@ -58,9 +67,14 @@ if [ "$USE_TAILSCALE" = "1" ]; then echo "Error: tailscale serve failed. On Linux, run once: sudo tailscale set --operator=\$USER" >&2 exit 1 fi - echo "Login with david@example.com to: https://$TS_HOSTNAME:$TS_PORT/" + DEV_URL="https://$TS_HOSTNAME:$TS_PORT/" else - echo "Login with david@example.com to: http://fizzy.localhost:$PORT/" + DEV_URL="http://app.fizzy.localhost:$PORT/" fi +printf "\n" +printf " ${c_bar} ${c_label}URL${c_reset} ${c_url}${DEV_URL}${c_reset}\n" +printf " ${c_bar} ${c_label}Login${c_reset} david@example.com\n" +printf "\n" + ./bin/rails server -b 0.0.0.0 -p $PORT diff --git a/bin/setup b/bin/setup index e095a41e53..0a6e83acaa 100755 --- a/bin/setup +++ b/bin/setup @@ -16,57 +16,21 @@ if [ -n "$SAAS" ]; then export BUNDLE_GEMFILE="Gemfile.saas" fi -# Install gum if needed -if ! command -v gum &>/dev/null; then - echo - echo "▸ Installing gum" - if command -v pacman &>/dev/null; then - sudo pacman -S --noconfirm gum - elif command -v brew &>/dev/null; then - brew install gum - else - echo "Please install gum: https://github.com/charmbracelet/gum" - exit 1 - fi - echo -fi - -# Install mise if needed -if ! command -v mise &>/dev/null; then - echo - echo "▸ Installing mise" - if command -v pacman &>/dev/null; then - sudo pacman -S --noconfirm mise - elif command -v brew &>/dev/null; then - brew install mise - else - echo "Please install mise: https://mise.jdx.dev/installing-mise.html#installation-methods" - exit 1 - fi - echo -fi - -# Install gh if needed -if ! command -v gh &>/dev/null; then - echo - echo "▸ Installing GitHub CLI" - if command -v pacman &>/dev/null; then - sudo pacman -S --noconfirm github-cli - elif command -v brew &>/dev/null; then - brew install gh - else - echo "Please install GitHub CLI: https://github.com/cli/cli#installation" - exit 1 - fi - echo -fi - +# gum is a mise-managed tool, so it isn't installed yet on a fresh machine. step() { local step_name="$1" shift - gum style --foreground 135 --bold "▸ $step_name" - gum style --foreground 240 "$*" + # gum may resolve to a mise shim that aborts before this config is trusted or + # mise meets the floor — and the shim dir is configurable, so probe by running + # gum rather than matching paths. Any failure falls back to plain echo. + if gum --version &> /dev/null; then + gum style --foreground 135 --bold "▸ $step_name" + gum style --foreground 240 "$*" + else + echo "▸ $step_name" + echo "$*" + fi "$@" @@ -75,6 +39,54 @@ step() { return $exit_code } +mise_min_version="2026.7.5" # keep in lockstep with min_version in .mise.toml + +mise_too_old() { + local current="$(mise --version 2>/dev/null | awk '{ print $1; exit }')" + [ "$(printf '%s\n' "$mise_min_version" "$current" | sort -V | head -1)" != "$mise_min_version" ] +} + +ensure_correct_mise_install() { + if ! command -v mise &> /dev/null; then + # brew installs are a macOS decision — a Linuxbrew host must not gain a + # brew-owned mise moments before the manager gate rejects or ignores it + if [ "$(uname -s)" = Darwin ] && command -v brew &> /dev/null; then + # refresh the formula index first: a stale one (fresh VM images, long-idle + # machines) resolves an old mise and the version floor is unreachable + brew update --quiet || true + brew install mise + elif command -v pacman &> /dev/null; then + sudo pacman -S --noconfirm --needed mise + else + echo "Please install mise: https://mise.jdx.dev/" + exit 1 + fi + fi + + if mise_too_old; then + # Upgrade the ACTIVE mise, classified by the resolved binary's owner — a brew + # keg can coexist with the pacman/dpkg/mise.run install PATH actually + # resolves, and upgrading an inactive copy would leave the floor unmet. + mise_path="$(readlink -f "$(command -v mise)")" + if command -v brew &> /dev/null && [[ "$mise_path" = "$(brew --prefix)"/* ]]; then + # refresh the formula index first: with a stale one (fresh VM images, + # long-idle machines) brew considers an old mise current and this upgrade + # is a no-op — found live on the fresh-macOS signoff VM + brew update --quiet || true + brew upgrade mise || true + elif command -v pacman &> /dev/null && pacman -Qo "$mise_path" &> /dev/null; then + sudo pacman -Syu --noconfirm mise || true + else + mise self-update --yes --no-plugins || true + fi + fi + + if mise_too_old; then + echo "mise $mise_min_version or newer is required. Please upgrade mise and rerun bin/setup." + exit 1 + fi +} + needs_seeding() { if [ "$CI" != "" ]; then return 1 @@ -106,32 +118,57 @@ oss_mysql_setup() { fi } -echo -gum style --foreground 153 " ˚ ∘ ∘ ˚ " -gum style --foreground 111 --bold " ∘˚˳°∘° 𝒻𝒾𝓏𝓏𝓎 °∘°˳˚∘ " -echo +step "Ensuring mise install" ensure_correct_mise_install +step "Trusting mise config" mise trust --yes "$app_root/.mise.toml" -step "Installing Ruby" mise install --yes -eval "$(mise hook-env -s bash)" +# Manager by OS, not PATH: a Linux machine with Homebrew installed must still +# converge its declared pacman packages, not the macOS Brewfile. +if [ "$(uname -s)" = Darwin ] && command -v brew &> /dev/null; then + manager=brew +elif [ "$(uname -s)" = Linux ] && command -v pacman &> /dev/null; then + manager=pacman +else + echo "Unsupported platform: bin/setup needs Homebrew (macOS) or pacman." + exit 1 +fi -if which pacman >/dev/null 2>&1; then - packages=(imagemagick mariadb-libs openslide libvips libheif libwebp libjxl libraw poppler-glib libcgif ffmpeg rav1e svt-av1 gitleaks) - if ! pacman -Q "${packages[@]}" >/dev/null 2>&1; then - step "Installing packages" sudo pacman -S --noconfirm --needed "${packages[@]}" +# Native packages before tools: Bundler builds native extensions against them. +if [ "$manager" = "brew" ]; then + step "Installing system packages" brew bundle --file="$app_root/Brewfile" +else + # apt refreshes package lists with --update; pacman must NOT — mise maps it to a + # forced `pacman -Sy` before a targeted -S, Arch's unsupported partial upgrade. + # Install against the existing synchronized database instead. + if [ "$manager" = pacman ]; then + step "Installing system packages" mise bootstrap packages apply --manager "$manager" --yes + else + step "Installing system packages" mise bootstrap packages apply --manager "$manager" --yes --update fi -elif which brew >/dev/null 2>&1; then - packages=(imagemagick openslide vips gitleaks) - missing_packages=() - for pkg in "${packages[@]}"; do - if ! brew list "$pkg" &>/dev/null; then - missing_packages+=("$pkg") - fi - done - if [ ${#missing_packages[@]} -gt 0 ]; then - step "Installing packages" brew install "${missing_packages[@]}" +fi + +step "Installing Ruby and tools" mise install --yes +eval "$(mise hook-env -s bash)" + +# Install gh if needed +if ! command -v gh &>/dev/null; then + echo + echo "▸ Installing GitHub CLI" + if command -v pacman &>/dev/null; then + sudo pacman -S --noconfirm github-cli + elif command -v brew &>/dev/null; then + brew install gh + else + echo "Please install GitHub CLI: https://github.com/cli/cli#installation" + exit 1 fi + echo fi +echo +gum style --foreground 153 " ˚ ∘ ∘ ˚ " +gum style --foreground 111 --bold " ∘˚˳°∘° 𝒻𝒾𝓏𝓏𝓎 °∘°˳˚∘ " +echo + bundle config set --local auto_install true step "Installing RubyGems" bundle install diff --git a/cloudron/start.sh b/cloudron/start.sh index 0f7b010193..d06bc33fc9 100755 --- a/cloudron/start.sh +++ b/cloudron/start.sh @@ -10,7 +10,9 @@ export DATABASE_ADAPTER="${DATABASE_ADAPTER:-mysql}" export RAILS_SERVE_STATIC_FILES="${RAILS_SERVE_STATIC_FILES:-1}" export RAILS_LOG_TO_STDOUT="${RAILS_LOG_TO_STDOUT:-1}" export LOG_LEVEL="${LOG_LEVEL:-info}" +export RAILS_LOG_LEVEL="${RAILS_LOG_LEVEL:-${LOG_LEVEL}}" export SOLID_QUEUE_IN_PUMA="${SOLID_QUEUE_IN_PUMA:-1}" +export JOB_CONCURRENCY="${JOB_CONCURRENCY:-1}" export RAILS_MAX_THREADS="${RAILS_MAX_THREADS:-5}" export PUMA_MIN_THREADS="${PUMA_MIN_THREADS:-${RAILS_MAX_THREADS}}" export RUBY_GC_HEAP_GROWTH_FACTOR="${RUBY_GC_HEAP_GROWTH_FACTOR:-1.1}" @@ -70,8 +72,15 @@ fi if [ -n "${CLOUDRON_APP_ORIGIN:-}" ] && [ -z "${APP_ORIGIN:-}" ]; then export APP_ORIGIN="${CLOUDRON_APP_ORIGIN}" fi +if [ -z "${BASE_URL:-}" ]; then + if [ -n "${APP_ORIGIN:-}" ]; then + export BASE_URL="${APP_ORIGIN}" + elif [ -n "${APP_HOST:-}" ]; then + export BASE_URL="https://${APP_HOST}" + fi +fi -# Map Cloudron sendmail addon vars into the names our initializer uses. +# Map Cloudron sendmail addon vars into the names Fizzy expects. if [ -n "${CLOUDRON_MAIL_SMTP_SERVER:-}" ] && [ -z "${MAIL_SMTP_SERVER:-}" ]; then export MAIL_SMTP_SERVER="${CLOUDRON_MAIL_SMTP_SERVER}" fi @@ -85,8 +94,12 @@ if [ -n "${CLOUDRON_MAIL_SMTP_PASSWORD:-}" ] && [ -z "${MAIL_SMTP_PASSWORD:-}" ] export MAIL_SMTP_PASSWORD="${CLOUDRON_MAIL_SMTP_PASSWORD}" fi -if [ -n "${MAIL_SMTP_SERVER:-}" ] && [ -z "${SMTP_ADDRESS:-}${SMTP_HOST:-}" ]; then - export SMTP_ADDRESS="${MAIL_SMTP_SERVER}" +if [ -z "${SMTP_ADDRESS:-}" ]; then + if [ -n "${SMTP_HOST:-}" ]; then + export SMTP_ADDRESS="${SMTP_HOST}" + elif [ -n "${MAIL_SMTP_SERVER:-}" ]; then + export SMTP_ADDRESS="${MAIL_SMTP_SERVER}" + fi fi if [ -n "${MAIL_SMTP_PORT:-}" ] && [ -z "${SMTP_PORT:-}" ]; then export SMTP_PORT="${MAIL_SMTP_PORT}" @@ -106,7 +119,11 @@ if [ -n "${CLOUDRON_MAIL_FROM_DISPLAY_NAME:-}" ] && [ -z "${MAIL_FROM_DISPLAY_NA export MAIL_FROM_DISPLAY_NAME="${CLOUDRON_MAIL_FROM_DISPLAY_NAME}" fi if [ -n "${MAIL_FROM:-}" ] && [ -z "${MAILER_FROM_ADDRESS:-}" ]; then - export MAILER_FROM_ADDRESS="${MAIL_FROM}" + if [ -n "${MAIL_FROM_DISPLAY_NAME:-}" ]; then + export MAILER_FROM_ADDRESS="${MAIL_FROM_DISPLAY_NAME} <${MAIL_FROM}>" + else + export MAILER_FROM_ADDRESS="${MAIL_FROM}" + fi fi if [ -n "${CLOUDRON_MAIL_SMTP_USERNAME:-}" ] && [ -z "${MAIL_FROM:-}${MAILER_FROM_ADDRESS:-}" ]; then export MAIL_FROM="${CLOUDRON_MAIL_SMTP_USERNAME}" @@ -134,10 +151,17 @@ if [ -z "${SECRET_KEY_BASE:-}" ]; then gosu "${APP_USER}":"${APP_USER}" bundle exec ruby -e "require 'securerandom'; File.write('/app/data/secret_key_base', SecureRandom.hex(64))" chown "${APP_USER}:${APP_USER}" /app/data/secret_key_base fi - export SECRET_KEY_BASE="$(cat /app/data/secret_key_base)" + SECRET_KEY_BASE="$(cat /app/data/secret_key_base)" + export SECRET_KEY_BASE +fi + +if { [ -n "${VAPID_PUBLIC_KEY:-}" ] && [ -z "${VAPID_PRIVATE_KEY:-}" ]; } || + { [ -z "${VAPID_PUBLIC_KEY:-}" ] && [ -n "${VAPID_PRIVATE_KEY:-}" ]; }; then + echo "VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY must be configured together" >&2 + exit 1 fi -if [ -z "${VAPID_PUBLIC_KEY:-}" ] || [ -z "${VAPID_PRIVATE_KEY:-}" ]; then +if [ -z "${VAPID_PUBLIC_KEY:-}" ]; then if [ ! -f /app/data/vapid.keys ]; then gosu "${APP_USER}":"${APP_USER}" bundle exec ruby -e "require 'web-push'; key = WebPush.generate_key; File.write('/app/data/vapid.keys', \"PUBLIC=#{key.public_key}\nPRIVATE=#{key.private_key}\n\")" chown "${APP_USER}:${APP_USER}" /app/data/vapid.keys diff --git a/config/cable.yml b/config/cable.yml index eed79b8407..3691576055 100644 --- a/config/cable.yml +++ b/config/cable.yml @@ -1,15 +1,15 @@ -defaults: &defaults +cable: &cable adapter: solid_cable connects_to: database: - writing: primary - reading: primary + writing: cable + reading: cable polling_interval: 0.1.seconds message_retention: 1.day -development: *defaults +development: *cable test: adapter: test -beta: *defaults -staging: *defaults -production: *defaults +beta: *cable +staging: *cable +production: *cable diff --git a/config/ci.rb b/config/ci.rb index 6a8cdca206..056de87ab9 100644 --- a/config/ci.rb +++ b/config/ci.rb @@ -9,7 +9,7 @@ CI.run do step "Setup", "bin/setup --skip-server" - step "Style: Ruby", "bin/rubocop" + step "Style: Ruby", "bin/rubocop -f simple" step "Gemfile: Drift check", "bin/bundle-drift check" step "Security: Gem audit", "bin/bundler-audit check --update" diff --git a/config/environments/development.rb b/config/environments/development.rb index 05dc335c2d..730a945dbd 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -34,8 +34,8 @@ # Store uploaded files on the local file system (see config/storage.yml for options). if Rails.root.join("tmp/minio-dev.txt").exist? config.active_storage.service = :devminio - config.x.content_security_policy.connect_src = "http://minio.localhost:39000" - config.x.content_security_policy.img_src = "http://minio.localhost:39000" + config.x.content_security_policy.connect_src = "http://minio.fizzy.localhost:39000" + config.x.content_security_policy.img_src = "http://minio.fizzy.localhost:39000" else config.active_storage.service = :local end @@ -86,7 +86,8 @@ end config.hosts = [ - "fizzy.localhost", + "app.fizzy.localhost", + "fizzy.localhost", # here for backwards compat, but will have CORS errors when using minio "localhost", "127.0.0.1", /fizzy-\d+/, # review apps: fizzy-123, fizzy-456:3000 diff --git a/config/environments/production.rb b/config/environments/production.rb index 11048e7304..9183871b73 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -94,8 +94,6 @@ .tap { |logger| logger.formatter = ::Logger::Formatter.new } .then { |logger| ActiveSupport::TaggedLogging.new(logger) } - # Respect LOG_LEVEL env (default info) so Cloudron logs include useful context. - config.log_level = ENV.fetch("LOG_LEVEL", "info").downcase.to_sym # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] @@ -112,9 +110,6 @@ config.solid_queue.connects_to = { database: { writing: :queue, reading: :queue } } # config.active_job.queue_name_prefix = "fizzy_production" - # Active Storage: default to disk unless overridden (Cloudron uses shared volume). - config.active_storage.service = ENV.fetch("ACTIVE_STORAGE_SERVICE", "local").to_sym - config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. diff --git a/config/initializers/active_job.rb b/config/initializers/active_job.rb index d8eed109d9..415fcc9092 100644 --- a/config/initializers/active_job.rb +++ b/config/initializers/active_job.rb @@ -1,39 +1,15 @@ # frozen_string_literal: true -# inspired from code in ActiveRecord::Tenanted -module FizzyActiveJobExtensions - extend ActiveSupport::Concern - - prepended do - attr_reader :account - self.enqueue_after_transaction_commit = true - end - - def initialize(...) - super - @account = Current.account - end - - def serialize - super.merge({ "account" => @account&.to_gid }) - end - - def deserialize(job_data) - super - if _account = job_data.fetch("account", nil) - @account = GlobalID::Locator.locate(_account) - end - end +ActiveSupport.on_load(:active_job) do + self.enqueue_after_transaction_commit = true +end - def perform_now - if account.present? - Current.with_account(account) { super } - else - super - end - end +ActiveSupport.on_load(:action_mailer) do + ActionMailer::MailDeliveryJob.prepend AccountTenanted end -ActiveSupport.on_load(:active_job) do - prepend FizzyActiveJobExtensions +Rails.application.config.after_initialize do + Turbo::Streams::ActionBroadcastJob.prepend AccountTenanted + Turbo::Streams::BroadcastJob.prepend AccountTenanted + Turbo::Streams::BroadcastStreamJob.prepend AccountTenanted end diff --git a/config/initializers/active_storage.rb b/config/initializers/active_storage.rb index 586c292a16..c4d6b43e97 100644 --- a/config/initializers/active_storage.rb +++ b/config/initializers/active_storage.rb @@ -19,15 +19,15 @@ def to_rich_text_attributes(*) end end -# Don't configure replica connections for ActiveStorage::Record. -# When ActiveStorage uses `connects_to`, it creates a separate connection pool -# from ApplicationRecord. This causes after_commit callbacks to fire in -# non-deterministic order - the Attachment's create_variants callback can fire -# before the User model's upload callback, causing FileNotFoundError when -# using `process: :immediately` for variants. -# See: https://github.com/rails/rails/issues/53694 +# ApplicationRecord calls `configure_replica_connections` to set up connection pools for the +# application models. We want ActiveStorage::Record to use the same pools for transactional +# integrity, proper callback invocation, joins, etc., however ActiveStorage::Record inherits from +# ActiveRecord::Base, not ApplicationRecord. This is how we make Active Storage always use the +# ApplicationRecord connection pool. ActiveSupport.on_load(:active_storage_record) do - configure_replica_connections + class << self + delegate :connection_pool, to: "ApplicationRecord" + end end module ActiveStorageControllerExtensions @@ -52,7 +52,7 @@ module ActiveStorageDirectUploadsControllerExtensions included do include Authentication include Authorization - skip_forgery_protection if: :authenticate_by_bearer_token + include RequestForgeryProtection end end diff --git a/config/initializers/active_storage_purge_on_last_attachment.rb b/config/initializers/active_storage_purge_on_last_attachment.rb index 91fa6e2697..2316ae1d08 100644 --- a/config/initializers/active_storage_purge_on_last_attachment.rb +++ b/config/initializers/active_storage_purge_on_last_attachment.rb @@ -21,9 +21,21 @@ def purge_later end private - def purge_dependent_blob_later - if (record.nil? || dependent == :purge_later) && !@purge_mode + # Rails registers `after_destroy_commit :purge_dependent_blob` (renamed from + # `purge_dependent_blob_later` upstream, which also now handles dependent: :purge). + # Override the current callback name so reused blobs (ActionText embeds) are only + # purged once the last attachment is gone, and skip when an explicit purge/purge_later + # is already driving the blob purge via `purge_blob_if_last` (@purge_mode set). + def purge_dependent_blob + return if @purge_mode + + # `record.nil?` must be checked first: `dependent` reads `record.attachment_reflections`, + # so it can't be evaluated for an orphaned attachment — an absent record falls back to + # purge_later. + if record.nil? || dependent == :purge_later purge_blob_if_last(:purge_later) + elsif dependent == :purge + purge_blob_if_last(:purge) end end diff --git a/config/initializers/cloudron.rb b/config/initializers/cloudron.rb index 4e738a87f0..f7a8719754 100644 --- a/config/initializers/cloudron.rb +++ b/config/initializers/cloudron.rb @@ -1,60 +1,26 @@ # frozen_string_literal: true -# Configure runtime settings driven by the environment so the app can boot -# cleanly when packaged (e.g. Cloudron). -Rails.application.configure do - # Default production log level is :fatal in this repo; relax it for packaged deployments - # so Fehler und Requests im STDOUT landen (überschreibbar via LOG_LEVEL). - config.log_level = ENV.fetch("LOG_LEVEL", "info").to_sym +require "fileutils" - # Fehlerseiten wieder wie Production, es sei denn SHOW_ERRORS explizit setzen. - if ENV.fetch("SHOW_ERRORS", "false") == "true" +# Cloudron captures STDOUT, but a persistent file log is useful when diagnosing +# restarts. Keep this initializer inert during regular development and tests. +Rails.application.configure do + if ActiveModel::Type::Boolean.new.cast(ENV["SHOW_ERRORS"]) config.consider_all_requests_local = true config.action_dispatch.show_exceptions = :all end - log_dir = ENV.fetch("LOG_DIR", "/app/data/log") - log_file = ENV.fetch("LOG_FILE") { File.join(log_dir, "#{Rails.env}.log") } - - begin - FileUtils.mkdir_p(File.dirname(log_file)) - file_logger = ActiveSupport::Logger.new(log_file) - file_logger.level = config.log_level - Rails.logger.extend ActiveSupport::Logger.broadcast(file_logger) - rescue => e - Rails.logger.warn "Cloudron log setup failed: #{e.class}: #{e.message}" - end - - host = ENV["APP_HOST"] || ENV["CLOUDRON_APP_DOMAIN"] - origin = ENV["APP_ORIGIN"] || ENV["CLOUDRON_APP_ORIGIN"] - protocol = ENV["APP_PROTOCOL"] || origin&.split("://")&.first || "https" - - if host - routes = Rails.application.routes - routes.default_url_options[:host] = host - routes.default_url_options[:protocol] = protocol - - config.action_mailer.default_url_options ||= {} - config.action_mailer.default_url_options[:host] ||= host - config.action_mailer.default_url_options[:protocol] ||= protocol - end - - from_address = ENV["MAILER_FROM_ADDRESS"] || ENV["MAIL_FROM"] - if from_address - config.action_mailer.default_options = config.action_mailer.default_options.to_h.merge(from: from_address) - end - - smtp_address = ENV["SMTP_ADDRESS"] || ENV["SMTP_HOST"] || ENV["MAIL_SMTP_SERVER"] - if smtp_address - config.action_mailer.delivery_method = :smtp - config.action_mailer.smtp_settings = { - address: smtp_address, - port: Integer(ENV.fetch("SMTP_PORT", ENV.fetch("MAIL_SMTP_PORT", 587))), - domain: ENV["SMTP_DOMAIN"] || ENV["MAIL_DOMAIN"] || host, - user_name: ENV["SMTP_USERNAME"] || ENV["MAIL_SMTP_USERNAME"], - password: ENV["SMTP_PASSWORD"] || ENV["MAIL_SMTP_PASSWORD"], - authentication: :login, - enable_starttls_auto: ENV.fetch("SMTP_ENABLE_STARTTLS_AUTO", "true") != "false" - }.compact + if ENV["CLOUDRON_APP_DOMAIN"].present? || ENV["LOG_FILE"].present? + log_dir = ENV.fetch("LOG_DIR", "/app/data/log") + log_file = ENV.fetch("LOG_FILE") { File.join(log_dir, "#{Rails.env}.log") } + + begin + FileUtils.mkdir_p(File.dirname(log_file)) + file_logger = ActiveSupport::Logger.new(log_file) + file_logger.level = Rails.logger.level + Rails.logger.broadcast_to(file_logger) + rescue StandardError => error + Rails.logger.warn "Cloudron log setup failed: #{error.class}: #{error.message}" + end end end diff --git a/config/puma.rb b/config/puma.rb index 1646aa3de3..980ab741f6 100644 --- a/config/puma.rb +++ b/config/puma.rb @@ -22,7 +22,7 @@ plugin :yabeda_prometheus end -if !Rails.env.local? +unless Rails.env.local? # Because we expect fewer I/O waits than Rails apps that connect to the # database over the network, let's start with a baseline config of 1 # worker per CPU, 1 thread per worker and tune it from there. diff --git a/config/routes.rb b/config/routes.rb index f00f3be514..8d68271013 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -28,6 +28,7 @@ resources :boards do scope module: :boards do + resources :accesses, only: :index resource :subscriptions resource :involvement resource :publication @@ -39,7 +40,11 @@ resource :closed end - resources :columns + resources :columns do + scope module: :columns do + resources :cards, only: :index + end + end end resources :cards, only: :create @@ -47,6 +52,7 @@ resources :webhooks do scope module: :webhooks do resource :activation, only: :create + resources :deliveries, only: :index, defaults: { format: :json } end end end @@ -88,7 +94,6 @@ resource :triage resource :watch resource :self_assignment, only: :create - resource :reading resources :reactions resources :assignments @@ -132,6 +137,7 @@ end end + resources :activities, only: :index resources :events, only: :index namespace :events do resources :days @@ -159,14 +165,12 @@ end end - if SignupToggle.allowed? - get "/signup", to: redirect("/signup/new") + get "/signup", to: redirect("/signup/new") - resource :signup, only: %i[ new create ] do - collection do - scope module: :signups, as: :signup do - resource :completion, only: %i[ new create ] - end + resource :signup, only: %i[ new create ] do + collection do + scope module: :signups, as: :signup do + resource :completion, only: %i[ new create ] end end end @@ -185,7 +189,6 @@ namespace :prompts do resources :cards - resources :tags resources :users resources :boards do diff --git a/config/storage.oss.yml b/config/storage.oss.yml index 063aaa9639..fb6f2841a4 100644 --- a/config/storage.oss.yml +++ b/config/storage.oss.yml @@ -1,21 +1,15 @@ -<% - storage_root = ENV.fetch("STORAGE_PATH") do - Rails.root.join("storage", Rails.env, "files") - end -%> - test: service: Disk - root: <%= storage_root %> + root: <%= Rails.root.join("tmp/storage/files") %> local: service: Disk - root: <%= storage_root %> + root: <%= Rails.root.join("storage", Rails.env, "files") %> devminio: service: S3 bucket: fizzy-dev-activestorage - endpoint: "http://minio.localhost:39000" + endpoint: "http://minio.fizzy.localhost:39000" force_path_style: true request_checksum_calculation: when_required # default is when_supported with CRC64NVME checksum which FlashBlade doesn't support response_checksum_validation: when_required # default is when_supported with CRC64NVME checksum which FlashBlade doesn't support diff --git a/db/migrate/20260709120000_add_account_board_status_index_to_cards.rb b/db/migrate/20260709120000_add_account_board_status_index_to_cards.rb new file mode 100644 index 0000000000..fd7171cc17 --- /dev/null +++ b/db/migrate/20260709120000_add_account_board_status_index_to_cards.rb @@ -0,0 +1,5 @@ +class AddAccountBoardStatusIndexToCards < ActiveRecord::Migration[8.2] + def change + add_index :cards, [ :account_id, :board_id, :status ] + end +end diff --git a/db/schema.rb b/db/schema.rb index 99e6be953e..58218ff103 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.2].define(version: 2026_02_18_120000) do +ActiveRecord::Schema[8.2].define(version: 2026_07_09_120000) do create_table "accesses", id: :uuid, charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| t.datetime "accessed_at" t.uuid "account_id", null: false @@ -227,6 +227,7 @@ t.string "status", default: "drafted", null: false t.string "title" t.datetime "updated_at", null: false + t.index ["account_id", "board_id", "status"], name: "index_cards_on_account_id_and_board_id_and_status" t.index ["account_id", "last_active_at", "status"], name: "index_cards_on_account_id_and_last_active_at_and_status" t.index ["account_id", "number"], name: "index_cards_on_account_id_and_number", unique: true t.index ["board_id"], name: "index_cards_on_board_id" diff --git a/db/schema_sqlite.rb b/db/schema_sqlite.rb index 00125d1d6a..9e4f050dc2 100644 --- a/db/schema_sqlite.rb +++ b/db/schema_sqlite.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.2].define(version: 2026_02_18_120000) do +ActiveRecord::Schema[8.2].define(version: 2026_07_09_120000) do create_table "accesses", id: :uuid, force: :cascade do |t| t.datetime "accessed_at" t.uuid "account_id", null: false @@ -227,6 +227,7 @@ t.string "status", limit: 255, default: "drafted", null: false t.string "title", limit: 255 t.datetime "updated_at", null: false + t.index ["account_id", "board_id", "status"], name: "index_cards_on_account_id_and_board_id_and_status" t.index ["account_id", "last_active_at", "status"], name: "index_cards_on_account_id_and_last_active_at_and_status" t.index ["account_id", "number"], name: "index_cards_on_account_id_and_number", unique: true t.index ["board_id"], name: "index_cards_on_board_id" diff --git a/docs/API.md b/docs/API.md deleted file mode 100644 index e8b60697c2..0000000000 --- a/docs/API.md +++ /dev/null @@ -1,1779 +0,0 @@ -# Fizzy API - -Fizzy has an API that allows you to integrate your application with it or to create -a bot to perform various actions for you. - -## Authentication - -There are two ways to authenticate with the Fizzy API: - -1. **Personal access tokens** - Long-lived tokens for scripts and integrations -2. **Magic link authentication** - Session-based authentication for native apps - -### Personal Access Tokens - -To use the API you'll need an access token. To get one, go to your profile, then, -in the API section, click on "Personal access tokens" and then click on -"Generate new access token". - -Give it a description and pick what kind of permission you want the access token to have: -- `Read`: allows reading data from your account -- `Read + Write`: allows reading and writing data to your account on your behalf - -Then click on "Generate access token". - -
- Access token generation guide with screenshots - - | Step | Description | Screenshot | - |:----:|-------------|:----------:| - | 1 | Go to your profile | Profile page with API section | - | 2 | In the API section click on "Personal access token" | Personal access tokens page | - | 3 | Click on "Generate a new access token" | Generate new access token dialog | - | 4 | Give it a description and assign it a permission | Access token created | -
- -> [!IMPORTANT] -> __An access token is like a password, keep it secret and do not share it with anyone.__ -> Any person or application that has your access token can perform actions on your behalf. - -To authenticate a request using your access token, include it in the `Authorization` header: - -```bash -curl -H "Authorization: Bearer put-your-access-token-here" -H "Accept: application/json" https://app.fizzy.do/my/identity -``` - -### Magic Link Authentication - -For native apps, you can authenticate users via magic links. This is a two-step process: - -#### 1. Request a magic link - -Send the user's email address to request a magic link be sent to them: - -```bash -curl -X POST \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - -d '{"email_address": "user@example.com"}' \ - https://app.fizzy.do/session -``` - -__Response:__ - -``` -HTTP/1.1 201 Created -Set-Cookie: pending_authentication_token=...; HttpOnly; SameSite=Lax -``` - -```json -{ - "pending_authentication_token": "eyJfcmFpbHMi..." -} -``` - -The response includes a `pending_authentication_token` both in the JSON body and as a cookie. -Native apps should store this token and include it as a cookie when submitting the magic link code. - -__Error responses:__ - -| Status Code | Description | -|--------|-------------| -| `422 Unprocessable entity` | Invalid email address, if sign ups are enabled and the value isn't a valid email address | -| `429 Too Many Requests` | Rate limit exceeded | - -#### 2. Submit the magic link code - -Once the user receives the magic link email, they'll have a 6-character code. Submit it to complete authentication: - -```bash -curl -X POST \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - -H "Cookie: pending_authentication_token=eyJfcmFpbHMi..." \ - -d '{"code": "ABC123"}' \ - https://app.fizzy.do/session/magic_link -``` - -__Response:__ - -```json -{ - "session_token": "eyJfcmFpbHMi..." -} -``` - -The `session_token` can be used to authenticate subsequent requests by including it as a cookie: - -```bash -curl -H "Cookie: session_token=eyJfcmFpbHMi..." \ - -H "Accept: application/json" \ - https://app.fizzy.do/my/identity -``` - -__Error responses:__ - -| Status Code | Description | -|--------|-------------| -| `401 Unauthorized` | Invalid `pending_authentication_token` or `code` | -| `429 Too Many Requests` | Rate limit exceeded | - - -#### Delete server-side session (_log out_) - -To log out and destroy the server-side session: - -```bash -curl -X DELETE \ - -H "Accept: application/json" \ - -H "Cookie: session_token=eyJfcmFpbHMi..." \ - https://app.fizzy.do/session -``` - -__Response:__ - -Returns `204 No Content` on success. - -#### Create an access token via the API - -You can programmatically create a personal access token using either a session cookie or an existing Bearer token: - -```bash -curl -X POST \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - -H "Cookie: session_token=eyJfcmFpbHMi..." \ - -d '{"access_token": {"description": "Fizzy CLI", "permission": "write"}}' \ - https://app.fizzy.do/1234567/my/access_tokens -``` - -Or with a Bearer token (must have `write` permission): - -```bash -curl -X POST \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - -H "Authorization: Bearer put-your-access-token-here" \ - -d '{"access_token": {"description": "Fizzy CLI", "permission": "write"}}' \ - https://app.fizzy.do/1234567/my/access_tokens -``` - -The `permission` field accepts `read` or `write`. - -__Response:__ - -``` -HTTP/1.1 201 Created -``` - -```json -{ - "token": "4f9Q6d2wXr8Kp1Ls0Vz3BnTa", - "description": "Fizzy CLI", - "permission": "write" -} -``` - -Store the `token` value securely — it won't be retrievable again. Use it as a Bearer token for subsequent API requests. - -## Caching - -Most endpoints return [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag) and [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control) headers. You can use these to avoid re-downloading unchanged data. - -### Using ETags - -When you make a request, the response includes an `ETag` header: - -``` -HTTP/1.1 200 OK -ETag: "abc123" -Cache-Control: max-age=0, private, must-revalidate -``` - -On subsequent requests, include the ETag value in the `If-None-Match` header: - -``` -GET /1234567/cards/42.json -If-None-Match: "abc123" -``` - -If the resource hasn't changed, you'll receive a `304 Not Modified` response with no body, saving bandwidth and processing time: - -``` -HTTP/1.1 304 Not Modified -ETag: "abc123" -``` - -If the resource has changed, you'll receive the full response with a new ETag. - -__Example in Ruby:__ - -```ruby -# Store the ETag from the response -etag = response.headers["ETag"] - -# On next request, send it back -headers = { "If-None-Match" => etag } -response = client.get("/1234567/cards/42.json", headers: headers) - -if response.status == 304 - # Nothing to do, the card hasn't changed -else - # The card has changed, process the new data -end -``` - -## Error Responses - -When a request fails, the API response will communicate the source of the problem through the HTTP status code. - -| Status Code | Description | -|-------------|-------------| -| `400 Bad Request` | The request was malformed or missing required parameters | -| `401 Unauthorized` | Authentication failed or access token is invalid | -| `403 Forbidden` | You don't have permission to perform this action | -| `404 Not Found` | The requested resource doesn't exist or you don't have access to it | -| `422 Unprocessable Entity` | Validation failed (see error response format above) | -| `500 Internal Server Error` | An unexpected error occurred on the server | - -If a request contains invalid data for fields, such as entering a string into a number field, in most cases the API will respond with a `500 Internal Server Error`. Clients are expected to perform some validation on their end before making a request. - -A validation error will produce a `422 Unprocessable Entity` response, which will sometimes be accompanied by details about the error: - -```json -{ - "avatar": ["must be a JPEG, PNG, GIF, or WebP image"] -} -``` - -## Pagination - -All endpoints that return a list of items are paginated. The page size can vary from endpoint to endpoint, -and we use a dynamic page size where initial pages return fewer results than later pages. - -If there are more results to fetch, the response will include a `Link` header with a `rel="next"` link to the next page of results: - -```bash -curl -H "Authorization: Bearer put-your-access-token-here" -H "Accept: application/json" -v http://fizzy.localhost:3006/686465299/cards -# ... -< link: ; rel="next" -# ... -``` - -## List parameters - -When an endpoint accepts a list of values as a parameter, you can provide multiple values by repeating the parameter name: - -``` -?tag_ids[]=tag1&tag_ids[]=tag2&tag_ids[]=tag3 -``` - -List parameters always end with `[]`. - -## File Uploads - -Some endpoints accept file uploads. To upload a file, send a `multipart/form-data` request instead of JSON. -You can combine file uploads with other parameters in the same request. - -__Example using curl:__ - -```bash -curl -X PUT \ - -H "Authorization: Bearer put-your-access-token-here" \ - -F "user[name]=David H. Hansson" \ - -F "user[avatar]=@/path/to/avatar.jpg" \ - http://fizzy.localhost:3006/686465299/users/03f5v9zjw7pz8717a4no1h8a7 -``` - -## Rich Text Fields - -Some fields accept rich text content. These fields accept HTML input, which will be sanitized to remove unsafe tags and attributes. - -```json -{ - "card": { - "title": "My card", - "description": "

This is bold and this is italic.

  • Item 1
  • Item 2
" - } -} -``` - -### Attaching files to rich text - -To attach files (images, documents) to rich text fields, use ActionText's direct upload flow: - -#### 1. Create a direct upload - -First, request a direct upload URL by sending file metadata: - -```bash -curl -X POST \ - -H "Authorization: Bearer put-your-access-token-here" \ - -H "Content-Type: application/json" \ - -d '{ - "blob": { - "filename": "screenshot.png", - "byte_size": 12345, - "checksum": "GQ5SqLsM7ylnji0Wgd9wNA==", - "content_type": "image/png" - } - }' \ - https://app.fizzy.do/123456/rails/active_storage/direct_uploads -``` - -The `checksum` is a Base64-encoded MD5 hash of the file content. -The direct upload endpoint is scoped to your account (replace `/123456` with your account slug). - -__Response:__ - -```json -{ - "id": "abc123", - "key": "abc123def456", - "filename": "screenshot.png", - "content_type": "image/png", - "byte_size": 12345, - "checksum": "GQ5SqLsM7ylnji0Wgd9wNA==", - "direct_upload": { - "url": "https://storage.example.com/...", - "headers": { - "Content-Type": "image/png", - "Content-MD5": "GQ5SqLsM7ylnji0Wgd9wNA==" - } - }, - "signed_id": "eyJfcmFpbHMi..." -} -``` - -#### 2. Upload the file - -Upload the file directly to the provided URL with the specified headers: - -```bash -curl -X PUT \ - -H "Content-Type: image/png" \ - -H "Content-MD5: GQ5SqLsM7ylnji0Wgd9wNA==" \ - --data-binary @screenshot.png \ - "https://storage.example.com/..." -``` - -#### 3. Reference the file in rich text - -Use the `signed_id` from step 1 to embed the file in your rich text using an `` tag: - -```json -{ - "card": { - "title": "Card with image", - "description": "

Here's a screenshot:

" - } -} -``` - -The `sgid` attribute should contain the `signed_id` returned from the direct upload response. - -## Identity - -An Identity represents a person using Fizzy. - -### `GET /my/identity` - -Returns a list of accounts the identity has access to, including the user for each account. - -```json -{ - "accounts": [ - { - "id": "03f5v9zjskhcii2r45ih3u1rq", - "name": "37signals", - "slug": "/897362094", - "created_at": "2025-12-05T19:36:35.377Z", - "user": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/users/03f5v9zjw7pz8717a4no1h8a7" - } - }, - { - "id": "03f5v9zpko7mmhjzwum3youpp", - "name": "Honcho", - "slug": "/686465299", - "created_at": "2025-12-05T19:36:36.746Z", - "user": { - "id": "03f5v9zppzlksuj4mxba2nbzn", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:36.783Z", - "url": "http://fizzy.localhost:3006/users/03f5v9zppzlksuj4mxba2nbzn" - } - } - ] -} -``` - -## Boards - -Boards are where you organize your work - they contain your cards. - -### `GET /:account_slug/boards` - -Returns a list of boards that you can access in the specified account. - -__Response:__ - -```json -[ - { - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "Fizzy", - "all_access": true, - "created_at": "2025-12-05T19:36:35.534Z", - "auto_postpone_period_in_days": 30, - "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - } - } -] -``` - -### `GET /:account_slug/boards/:board_id` - -Returns the specified board. - -__Response:__ - -```json -{ - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "Fizzy", - "all_access": true, - "created_at": "2025-12-05T19:36:35.534Z", - "auto_postpone_period_in_days": 30, - "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "public_url": "http://fizzy.localhost:3006/897362094/public/boards/aB3dEfGhIjKlMnOp" -} -``` - -The `public_url` field is only present when the board is published. - -### `POST /:account_slug/boards` - -Creates a new Board in the account. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `name` | string | Yes | The name of the board | -| `all_access` | boolean | No | Whether any user in the account can access this board. Defaults to `true` | -| `auto_postpone_period_in_days` | integer | No | Number of days of inactivity before cards are automatically postponed (e.g. `30`) | -| `public_description` | string | No | Rich text description shown on the public board page | - -__Request:__ - -```json -{ - "board": { - "name": "My new board", - } -} -``` - -__Response:__ - -Returns `201 Created` with a `Location` header pointing to the new board: - -``` -HTTP/1.1 201 Created -Location: /897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm.json -``` - -### `PUT /:account_slug/boards/:board_id` - -Updates a Board. Only board administrators can update a board. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `name` | string | No | The name of the board | -| `all_access` | boolean | No | Whether any user in the account can access this board | -| `auto_postpone_period_in_days` | integer | No | Number of days of inactivity before cards are automatically postponed (e.g. `30`) | -| `public_description` | string | No | Rich text description shown on the public board page | -| `user_ids` | array | No | Array of *all* user IDs who should have access to this board (only applicable when `all_access` is `false`) | - -__Request:__ - -```json -{ - "board": { - "name": "Updated board name", - "auto_postpone_period_in_days": 30, - "public_description": "This is a **public** description of the board.", - "all_access": false, - "user_ids": [ - "03f5v9zppzlksuj4mxba2nbzn", - "03f5v9zjw7pz8717a4no1h8a7" - ] - } -} -``` - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/boards/:board_id` - -Deletes a Board. Only board administrators can delete a board. - -__Response:__ - -Returns `204 No Content` on success. - -## Board Publications - -Publishing a board makes it publicly accessible via a shareable link, without requiring authentication. Only board administrators can publish or unpublish a board. - -### `POST /:account_slug/boards/:board_id/publication` - -Publishes a board, generating a shareable public link. - -__Response:__ - -``` -HTTP/1.1 201 Created -``` - -```json -{ - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "Fizzy", - "all_access": true, - "created_at": "2025-12-05T19:36:35.534Z", - "auto_postpone_period_in_days": 30, - "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "public_url": "http://fizzy.localhost:3006/897362094/public/boards/aB3dEfGhIjKlMnOp" -} -``` - -If the board is already published, the existing publication is returned. - -### `DELETE /:account_slug/boards/:board_id/publication` - -Unpublishes a board, removing public access. - -__Response:__ - -Returns `204 No Content` on success. - -## Account - -### `GET /account/settings` - -Returns the current account. - -__Response:__ - -```json -{ - "id": "03f5v9zjvypwh0t0e2rfh0h7k", - "name": "37signals", - "cards_count": 5, - "created_at": "2025-12-05T19:36:35.401Z", - "auto_postpone_period_in_days": 30 -} -``` - -The `auto_postpone_period_in_days` is the account-level default in days (e.g. `30`). Cards are automatically moved to "Not Now" after this period of inactivity. Each board can override this with its own value. - -### `PUT /account/entropy` - -Updates the account-level default auto close period. Requires admin role. - -__Request:__ - -```json -{ - "entropy": { - "auto_postpone_period_in_days": 30 - } -} -``` - -__Response:__ - -Returns the account object: - -```json -{ - "id": "03f5v9zjvypwh0t0e2rfh0h7k", - "name": "37signals", - "cards_count": 5, - "created_at": "2025-12-05T19:36:35.401Z", - "auto_postpone_period_in_days": 30 -} -``` - -### `PUT /:account_slug/boards/:board_id/entropy` - -Updates the auto close period for a specific board. Requires board admin permission. - -__Request:__ - -```json -{ - "board": { - "auto_postpone_period_in_days": 90 - } -} -``` - -__Response:__ - -Returns the board object. - -## Webhooks - -Webhooks notify another application when something happens on a board. Only account admins can list, view, create, update, delete, or reactivate webhooks. - -### `GET /:account_slug/boards/:board_id/webhooks` - -Returns a paginated list of webhooks for a board. - -__Response:__ - -```json -[ - { - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "Production API", - "payload_url": "https://api.example.com/webhooks", - "active": true, - "signing_secret": "p94Bx2HjempCdYB4DTyZkY1b", - "subscribed_actions": ["card_published", "card_assigned", "card_closed"], - "created_at": "2025-12-05T19:36:35.534Z", - "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcy/webhooks/03f5v9zkft4hj9qq0lsn9ohcm", - "board": { - "id": "03f5v9zkft4hj9qq0lsn9ohcy", - "name": "Fizzy", - "all_access": true, - "created_at": "2025-12-05T19:36:35.534Z", - "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcy", - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - } - } - } -] -``` - -### `GET /:account_slug/boards/:board_id/webhooks/:id` - -Returns a single webhook. - -__Response:__ - -Returns the same webhook shape shown above. - -### `POST /:account_slug/boards/:board_id/webhooks` - -Creates a webhook. - -__Request:__ - -```json -{ - "webhook": { - "name": "Production API", - "url": "https://api.example.com/webhooks", - "subscribed_actions": ["card_published", "card_assigned", "card_closed"] - } -} -``` - -`subscribed_actions` accepts any of: -`card_assigned`, `card_closed`, `card_postponed`, `card_auto_postponed`, `card_board_changed`, `card_published`, `card_reopened`, `card_sent_back_to_triage`, `card_triaged`, `card_unassigned`, `comment_created` - -__Response:__ - -``` -HTTP/1.1 201 Created -Location: http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcy/webhooks/03f5v9zkft4hj9qq0lsn9ohcm.json -``` - -Returns the created webhook in the response body. - -### `PATCH /:account_slug/boards/:board_id/webhooks/:id` - -Updates a webhook. - -__Request:__ - -```json -{ - "webhook": { - "name": "Production API", - "subscribed_actions": ["card_closed"] - } -} -``` - -The `url` is immutable after creation and is ignored on update. - -__Response:__ - -Returns the updated webhook. - -### `DELETE /:account_slug/boards/:board_id/webhooks/:id` - -Deletes a webhook. - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/boards/:board_id/webhooks/:id/activation` - -Reactivates a deactivated webhook. - -__Response:__ - -``` -HTTP/1.1 201 Created -``` - -Returns the reactivated webhook in the response body. - -## Cards - -Cards are tasks or items of work on a board. They can be organized into columns, tagged, assigned to users, and have comments. - -### `GET /:account_slug/cards` - -Returns a paginated list of cards you have access to. Results can be filtered using query parameters. - -__Query Parameters:__ - -| Parameter | Description | -|-----------|-------------| -| `board_ids[]` | Filter by board ID(s) | -| `tag_ids[]` | Filter by tag ID(s) | -| `assignee_ids[]` | Filter by assignee user ID(s) | -| `creator_ids[]` | Filter by card creator ID(s) | -| `closer_ids[]` | Filter by user ID(s) who closed the cards | -| `card_ids[]` | Filter to specific card ID(s) | -| `indexed_by` | Filter by: `all` (default), `closed`, `not_now`, `stalled`, `postponing_soon`, `golden` | -| `sorted_by` | Sort order: `latest` (default), `newest`, `oldest` | -| `assignment_status` | Filter by assignment status: `unassigned` | -| `creation` | Filter by creation date: `today`, `yesterday`, `thisweek`, `lastweek`, `thismonth`, `lastmonth`, `thisyear`, `lastyear` | -| `closure` | Filter by closure date: `today`, `yesterday`, `thisweek`, `lastweek`, `thismonth`, `lastmonth`, `thisyear`, `lastyear` | -| `terms[]` | Search terms to filter cards | - -__Response:__ - -```json -[ - { - "id": "03f5vaeq985jlvwv3arl4srq2", - "number": 1, - "title": "First!", - "status": "published", - "description": "Hello, World!", - "description_html": "

Hello, World!

", - "image_url": null, - "has_attachments": false, - "tags": ["programming"], - "golden": false, - "last_active_at": "2025-12-05T19:38:48.553Z", - "created_at": "2025-12-05T19:38:48.540Z", - "url": "http://fizzy.localhost:3006/897362094/cards/4", - "board": { - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "Fizzy", - "all_access": true, - "created_at": "2025-12-05T19:36:35.534Z", - "auto_postpone_period_in_days": 30, - "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - } - }, - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "comments_url": "http://fizzy.localhost:3006/897362094/cards/4/comments", - "reactions_url": "http://fizzy.localhost:3006/897362094/cards/4/reactions" - }, -] -``` - -### `GET /:account_slug/cards/:card_number` - -Returns a specific card by its number. - -__Response:__ - -```json -{ - "id": "03f5vaeq985jlvwv3arl4srq2", - "number": 1, - "title": "First!", - "status": "published", - "description": "Hello, World!", - "description_html": "

Hello, World!

", - "image_url": null, - "has_attachments": false, - "tags": ["programming"], - "closed": false, - "golden": false, - "last_active_at": "2025-12-05T19:38:48.553Z", - "created_at": "2025-12-05T19:38:48.540Z", - "url": "http://fizzy.localhost:3006/897362094/cards/4", - "board": { - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "Fizzy", - "all_access": true, - "created_at": "2025-12-05T19:36:35.534Z", - "auto_postpone_period_in_days": 30, - "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - } - }, - "column": { - "id": "03f5v9zkft4hj9qq0lsn9ohcn", - "name": "In Progress", - "color": { - "name": "Lime", - "value": "var(--color-card-4)" - }, - "created_at": "2025-12-05T19:36:35.534Z" - }, - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "comments_url": "http://fizzy.localhost:3006/897362094/cards/4/comments", - "reactions_url": "http://fizzy.localhost:3006/897362094/cards/4/reactions", - "steps": [ - { - "id": "03f8huu0sog76g3s975963b5e", - "content": "This is the first step", - "completed": false - }, - { - "id": "03f8huu0sog76g3s975969734", - "content": "This is the second step", - "completed": false - } - ] -} -``` - -> **Note:** The `closed` field indicates whether the card is in the "Done" state. The `column` field is only present when the card has been triaged into a column; cards in "Maybe?", "Not Now" or "Done" will not have this field. - -### `POST /:account_slug/boards/:board_id/cards` - -Creates a new card in a board. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `title` | string | Yes | The title of the card | -| `description` | string | No | Rich text description of the card | -| `status` | string | No | Initial status: `published` (default), `drafted` | -| `image` | file | No | Header image for the card | -| `tag_ids` | array | No | Array of tag IDs to apply to the card | -| `created_at` | datetime | No | Override creation timestamp (ISO 8601 format) | -| `last_active_at` | datetime | No | Override last activity timestamp (ISO 8601 format) | - -__Request:__ - -```json -{ - "card": { - "title": "Add dark mode support", - "description": "We need to add dark mode to the app" - } -} -``` - -__Response:__ - -Returns `201 Created` with a `Location` header pointing to the new card. - -### `PUT /:account_slug/cards/:card_number` - -Updates a card. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `title` | string | No | The title of the card | -| `description` | string | No | Rich text description of the card | -| `status` | string | No | Card status: `drafted`, `published` | -| `image` | file | No | Header image for the card | -| `tag_ids` | array | No | Array of tag IDs to apply to the card | -| `last_active_at` | datetime | No | Override last activity timestamp (ISO 8601 format) | - -__Request:__ - -```json -{ - "card": { - "title": "Add dark mode support (Updated)" - } -} -``` - -__Response:__ - -Returns the updated card. - -### `DELETE /:account_slug/cards/:card_number` - -Deletes a card. Only the card creator or board administrators can delete cards. - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/cards/:card_number/image` - -Removes the header image from a card. - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/cards/:card_number/closure` - -Closes a card. - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/cards/:card_number/closure` - -Reopens a closed card. - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/cards/:card_number/not_now` - -Moves a card to "Not Now" status. - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/cards/:card_number/triage` - -Moves a card into a column. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `column_id` | string | Yes | The ID of the column to move the card into | - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/cards/:card_number/triage` - -Sends a card back to triage. - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/cards/:card_number/taggings` - -Toggles a tag on or off for a card. If the tag doesn't exist, it will be created. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `tag_title` | string | Yes | The title of the tag (leading `#` is stripped) | - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/cards/:card_number/assignments` - -Toggles assignment of a user to/from a card. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `assignee_id` | string | Yes | The ID of the user to assign/unassign | - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/cards/:card_number/watch` - -Subscribes the current user to notifications for this card. - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/cards/:card_number/watch` - -Unsubscribes the current user from notifications for this card. - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/cards/:card_number/goldness` - -Marks a card as golden. - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/cards/:card_number/goldness` - -Removes golden status from a card. - -__Response:__ - -Returns `204 No Content` on success. - -## Pins - -Pins let users keep quick access to important cards. - -### `POST /:account_slug/cards/:card_number/pin` - -Pins a card for the current user. - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/cards/:card_number/pin` - -Unpins a card for the current user. - -__Response:__ - -Returns `204 No Content` on success. - -### `GET /my/pins` - -Returns the current user's pinned cards. This endpoint is not paginated and returns up to 100 cards. - -__Response:__ - -```json -[ - { - "id": "03f5vaeq985jlvwv3arl4srq2", - "number": 1, - "title": "First!", - "status": "published", - "description": "Hello, World!", - "description_html": "

Hello, World!

", - "image_url": null, - "has_attachments": false, - "tags": ["programming"], - "golden": false, - "last_active_at": "2025-12-05T19:38:48.553Z", - "created_at": "2025-12-05T19:38:48.540Z", - "url": "http://fizzy.localhost:3006/897362094/cards/4", - "board": { - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "Fizzy", - "all_access": true, - "created_at": "2025-12-05T19:36:35.534Z", - "auto_postpone_period_in_days": 30, - "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7", - "avatar_url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7/avatar" - } - }, - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7", - "avatar_url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7/avatar" - }, - "comments_url": "http://fizzy.localhost:3006/897362094/cards/4/comments" - } -] -``` - -## Comments - -Comments are attached to cards and support rich text. - -### `GET /:account_slug/cards/:card_number/comments` - -Returns a paginated list of comments on a card, sorted chronologically (oldest first). - -__Response:__ - -```json -[ - { - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "created_at": "2025-12-05T19:36:35.534Z", - "updated_at": "2025-12-05T19:36:35.534Z", - "body": { - "plain_text": "This looks great!", - "html": "
This looks great!
" - }, - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "card": { - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "url": "http://fizzy.localhost:3006/897362094/cards/03f5v9zo9qlcwwpyc0ascnikz" - }, - "reactions_url": "http://fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz/reactions", - "url": "http://fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz" - } -] -``` - -### `GET /:account_slug/cards/:card_number/comments/:comment_id` - -Returns a specific comment. - -__Response:__ - -```json -{ - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "created_at": "2025-12-05T19:36:35.534Z", - "updated_at": "2025-12-05T19:36:35.534Z", - "body": { - "plain_text": "This looks great!", - "html": "
This looks great!
" - }, - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "card": { - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "url": "http://fizzy.localhost:3006/897362094/cards/03f5v9zo9qlcwwpyc0ascnikz" - }, - "reactions_url": "http://fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz/reactions", - "url": "http://fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz" -} -``` - -### `POST /:account_slug/cards/:card_number/comments` - -Creates a new comment on a card. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `body` | string | Yes | The comment body (supports rich text) | -| `created_at` | datetime | No | Override creation timestamp (ISO 8601 format) | - -__Request:__ - -```json -{ - "comment": { - "body": "This looks great!" - } -} -``` - -__Response:__ - -Returns `201 Created` with a `Location` header pointing to the new comment. - -### `PUT /:account_slug/cards/:card_number/comments/:comment_id` - -Updates a comment. Only the comment creator can update their comments. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `body` | string | Yes | The updated comment body | - -__Request:__ - -```json -{ - "comment": { - "body": "This looks even better now!" - } -} -``` - -__Response:__ - -Returns the updated comment. - -### `DELETE /:account_slug/cards/:card_number/comments/:comment_id` - -Deletes a comment. Only the comment creator can delete their comments. - -__Response:__ - -Returns `204 No Content` on success. - -## Card Reactions (Boosts) - -Card reactions (also called "boosts") let users add short responses directly to cards. These are limited to 16 characters. - -### `GET /:account_slug/cards/:card_number/reactions` - -Returns a list of reactions on a card. - -__Response:__ - -```json -[ - { - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "content": "👍", - "reacter": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "url": "http://fizzy.localhost:3006/897362094/cards/3/reactions/03f5v9zo9qlcwwpyc0ascnikz" - } -] -``` - -### `POST /:account_slug/cards/:card_number/reactions` - -Adds a reaction (boost) to a card. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `content` | string | Yes | The reaction text (max 16 characters) | - -__Request:__ - -```json -{ - "reaction": { - "content": "Great 👍" - } -} -``` - -__Response:__ - -Returns `201 Created` on success. - -### `DELETE /:account_slug/cards/:card_number/reactions/:reaction_id` - -Removes your reaction from a card. Only the reaction creator can remove their own reactions. - -__Response:__ - -Returns `204 No Content` on success. - -## Comment Reactions - -Reactions are short (16-character max) responses to comments. - -### `GET /:account_slug/cards/:card_number/comments/:comment_id/reactions` - -Returns a list of reactions on a comment. - -__Response:__ - -```json -[ - { - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "content": "👍", - "reacter": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "url": "http://fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz/reactions/03f5v9zo9qlcwwpyc0ascnikz" - } -] -``` - -### `POST /:account_slug/cards/:card_number/comments/:comment_id/reactions` - -Adds a reaction to a comment. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `content` | string | Yes | The reaction text | - -__Request:__ - -```json -{ - "reaction": { - "content": "Great 👍" - } -} -``` - -__Response:__ - -Returns `201 Created` on success. - -### `DELETE /:account_slug/cards/:card_number/comments/:comment_id/reactions/:reaction_id` - -Removes your reaction from a comment. - -__Response:__ - -Returns `204 No Content` on success. - -## Steps - -Steps are to-do items on a card. - -### `GET /:account_slug/cards/:card_number/steps/:step_id` - -Returns a specific step. - -__Response:__ - -```json -{ - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "content": "Write tests", - "completed": false -} -``` - -### `POST /:account_slug/cards/:card_number/steps` - -Creates a new step on a card. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `content` | string | Yes | The step text | -| `completed` | boolean | No | Whether the step is completed (default: `false`) | - -__Request:__ - -```json -{ - "step": { - "content": "Write tests" - } -} -``` - -__Response:__ - -Returns `201 Created` with a `Location` header pointing to the new step. - -### `PUT /:account_slug/cards/:card_number/steps/:step_id` - -Updates a step. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `content` | string | No | The step text | -| `completed` | boolean | No | Whether the step is completed | - -__Request:__ - -```json -{ - "step": { - "completed": true - } -} -``` - -__Response:__ - -Returns the updated step. - -### `DELETE /:account_slug/cards/:card_number/steps/:step_id` - -Deletes a step. - -__Response:__ - -Returns `204 No Content` on success. - -## Tags - -Tags are labels that can be applied to cards for organization and filtering. - -### `GET /:account_slug/tags` - -Returns a list of all tags in the account, sorted alphabetically. - -__Response:__ - -```json -[ - { - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "title": "bug", - "created_at": "2025-12-05T19:36:35.534Z", - "url": "http://fizzy.localhost:3006/897362094/cards?tag_ids[]=03f5v9zo9qlcwwpyc0ascnikz" - }, - { - "id": "03f5v9zo9qlcwwpyc0ascnilz", - "title": "feature", - "created_at": "2025-12-05T19:36:35.534Z", - "url": "http://fizzy.localhost:3006/897362094/cards?tag_ids[]=03f5v9zo9qlcwwpyc0ascnilz" - } -] -``` - -## Columns - -Columns represent stages in a workflow on a board. Cards move through columns as they progress. - -### `GET /:account_slug/boards/:board_id/columns` - -Returns a list of columns on a board, sorted by position. - -__Response:__ - -```json -[ - { - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "Recording", - "color": "var(--color-card-default)", - "created_at": "2025-12-05T19:36:35.534Z" - }, - { - "id": "03f5v9zkft4hj9qq0lsn9ohcn", - "name": "Published", - "color": "var(--color-card-4)", - "created_at": "2025-12-05T19:36:35.534Z" - } -] -``` - -### `GET /:account_slug/boards/:board_id/columns/:column_id` - -Returns the specified column. - -__Response:__ - -```json -{ - "id": "03f5v9zkft4hj9qq0lsn9ohcm", - "name": "In Progress", - "color": "var(--color-card-default)", - "created_at": "2025-12-05T19:36:35.534Z" -} -``` - -### `POST /:account_slug/boards/:board_id/columns` - -Creates a new column on the board. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `name` | string | Yes | The name of the column | -| `color` | string | No | The column color. One of: `var(--color-card-default)` (Blue), `var(--color-card-1)` (Gray), `var(--color-card-2)` (Tan), `var(--color-card-3)` (Yellow), `var(--color-card-4)` (Lime), `var(--color-card-5)` (Aqua), `var(--color-card-6)` (Violet), `var(--color-card-7)` (Purple), `var(--color-card-8)` (Pink) | - -__Request:__ - -```json -{ - "column": { - "name": "In Progress", - "color": "var(--color-card-4)" - } -} -``` - -__Response:__ - -Returns `201 Created` with a `Location` header pointing to the new column. - -### `PUT /:account_slug/boards/:board_id/columns/:column_id` - -Updates a column. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `name` | string | No | The name of the column | -| `color` | string | No | The column color | - -__Request:__ - -```json -{ - "column": { - "name": "Done" - } -} -``` - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/boards/:board_id/columns/:column_id` - -Deletes a column. - -__Response:__ - -Returns `204 No Content` on success. - -## Users - -Users represent people who have access to an account. - -### `GET /:account_slug/users` - -Returns a list of active users in the account. - -__Response:__ - -```json -[ - { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - { - "id": "03f5v9zjysoy0fqs9yg0ei3hq", - "name": "Jason Fried", - "role": "member", - "active": true, - "email_address": "jason@example.com", - "created_at": "2025-12-05T19:36:35.419Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjysoy0fqs9yg0ei3hq" - }, - { - "id": "03f5v9zk1dtqduod5bkhv3k8m", - "name": "Jason Zimdars", - "role": "member", - "active": true, - "email_address": "jz@example.com", - "created_at": "2025-12-05T19:36:35.435Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zk1dtqduod5bkhv3k8m" - }, - { - "id": "03f5v9zk3nw9ja92e7s4h2wbe", - "name": "Kevin Mcconnell", - "role": "member", - "active": true, - "email_address": "kevin@example.com", - "created_at": "2025-12-05T19:36:35.451Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zk3nw9ja92e7s4h2wbe" - } -] -``` - -### `GET /:account_slug/users/:user_id` - -Returns the specified user. - -__Response:__ - -```json -{ - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" -} -``` - -### `PUT /:account_slug/users/:user_id` - -Updates a user. You can only update users you have permission to change. - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `name` | string | No | The user's display name | -| `avatar` | file | No | The user's avatar image | - -__Request:__ - -```json -{ - "user": { - "name": "David H. Hansson" - } -} -``` - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/users/:user_id` - -Deactivates a user. You can only deactivate users you have permission to change. - -__Response:__ - -Returns `204 No Content` on success. - -## Notifications - -Notifications inform users about events that happened in the account, such as comments, assignments, and card updates. - -### `GET /:account_slug/notifications` - -Returns a list of notifications for the current user. Unread notifications are returned first, followed by read notifications. - -__Response:__ - -```json -[ - { - "id": "03f5va03bpuvkcjemcxl73ho2", - "read": false, - "read_at": null, - "created_at": "2025-11-19T04:03:58.000Z", - "title": "Plain text mentions", - "body": "Assigned to self", - "creator": { - "id": "03f5v9zjw7pz8717a4no1h8a7", - "name": "David Heinemeier Hansson", - "role": "owner", - "active": true, - "email_address": "david@example.com", - "created_at": "2025-12-05T19:36:35.401Z", - "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" - }, - "card": { - "id": "03f5v9zo9qlcwwpyc0ascnikz", - "title": "Plain text mentions", - "status": "published", - "url": "http://fizzy.localhost:3006/897362094/cards/3" - }, - "url": "http://fizzy.localhost:3006/897362094/notifications/03f5va03bpuvkcjemcxl73ho2" - } -] -``` - -### `POST /:account_slug/notifications/:notification_id/reading` - -Marks a notification as read. - -__Response:__ - -Returns `204 No Content` on success. - -### `DELETE /:account_slug/notifications/:notification_id/reading` - -Marks a notification as unread. - -__Response:__ - -Returns `204 No Content` on success. - -### `POST /:account_slug/notifications/bulk_reading` - -Marks all unread notifications as read. - -__Response:__ - -Returns `204 No Content` on success. diff --git a/docs/api/README.md b/docs/api/README.md new file mode 100644 index 0000000000..e8a476e06c --- /dev/null +++ b/docs/api/README.md @@ -0,0 +1,148 @@ +# Fizzy API + +Fizzy has an API that allows you to integrate your application with it or to create +a bot to perform various actions for you. + +## API Endpoints + +- [Authentication](sections/authentication.md) +- [Identity](sections/identity.md) +- [Account](sections/account.md) +- [Boards](sections/boards.md) +- [Columns](sections/columns.md) +- [Cards](sections/cards.md) +- [Pins](sections/pins.md) +- [Steps](sections/steps.md) +- [Comments](sections/comments.md) +- [Reactions](sections/reactions.md) +- [Tags](sections/tags.md) +- [Users](sections/users.md) +- [Activities](sections/activities.md) +- [Notifications](sections/notifications.md) +- [Rich Text](sections/rich_text.md) +- [Exports](sections/exports.md) +- [Webhooks](sections/webhooks.md) + +## Authentication + +There are two ways to authenticate with the Fizzy API: + +1. **Personal access tokens** - Long-lived tokens for scripts and integrations +2. **Magic link authentication** - Session-based authentication for native apps + +Read the [authentication guide](sections/authentication.md) to get started. + +## Caching + +Most endpoints return [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag) and [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control) headers. You can use these to avoid re-downloading unchanged data. + +### Using ETags + +When you make a request, the response includes an `ETag` header: + +``` +HTTP/1.1 200 OK +ETag: "abc123" +Cache-Control: max-age=0, private, must-revalidate +``` + +On subsequent requests, include the ETag value in the `If-None-Match` header: + +``` +GET /1234567/cards/42.json +If-None-Match: "abc123" +``` + +If the resource hasn't changed, you'll receive a `304 Not Modified` response with no body, saving bandwidth and processing time: + +``` +HTTP/1.1 304 Not Modified +ETag: "abc123" +``` + +If the resource has changed, you'll receive the full response with a new ETag. + +__Example in Ruby:__ + +```ruby +# Store the ETag from the response +etag = response.headers["ETag"] + +# On next request, send it back +headers = { "If-None-Match" => etag } +response = client.get("/1234567/cards/42.json", headers: headers) + +if response.status == 304 + # Nothing to do, the card hasn't changed +else + # The card has changed, process the new data +end +``` + +## Error Responses + +When a request fails, the API response will communicate the source of the problem through the HTTP status code. + +| Status Code | Description | +|-------------|-------------| +| `400 Bad Request` | The request was malformed or missing required parameters | +| `401 Unauthorized` | Authentication failed or access token is invalid | +| `403 Forbidden` | You don't have permission to perform this action | +| `404 Not Found` | The requested resource doesn't exist or you don't have access to it | +| `422 Unprocessable Entity` | Validation failed (see error response format above) | +| `500 Internal Server Error` | An unexpected error occurred on the server | + +If a request contains invalid data for fields, such as entering a string into a number field, in most cases the API will respond with a `500 Internal Server Error`. Clients are expected to perform some validation on their end before making a request. + +A validation error will produce a `422 Unprocessable Entity` response, which will sometimes be accompanied by details about the error: + +```json +{ + "avatar": ["must be a JPEG, PNG, GIF, or WebP image"] +} +``` + +## Pagination + +All endpoints that return a list of items are paginated. The page size can vary from endpoint to endpoint, +and we use a dynamic page size where initial pages return fewer results than later pages. + +If there are more results to fetch, the response will include a `Link` header with a `rel="next"` link to the next page of results: + +```bash +curl -H "Authorization: Bearer put-your-access-token-here" -H "Accept: application/json" -v http://app.fizzy.localhost:3006/686465299/cards +# ... +< link: ; rel="next" +# ... +``` + +## List parameters + +When an endpoint accepts a list of values as a parameter, you can provide multiple values by repeating the parameter name: + +``` +?tag_ids[]=tag1&tag_ids[]=tag2&tag_ids[]=tag3 +``` + +List parameters always end with `[]`. + +## File Uploads + +Some endpoints accept file uploads. To upload a file, send a `multipart/form-data` request instead of JSON. +You can combine file uploads with other parameters in the same request. + +__Example using curl:__ + +```bash +curl -X PUT \ + -H "Authorization: Bearer put-your-access-token-here" \ + -F "user[name]=David H. Hansson" \ + -F "user[avatar]=@/path/to/avatar.jpg" \ + http://app.fizzy.localhost:3006/686465299/users/03f5v9zjw7pz8717a4no1h8a7 +``` + +## Rich Text Fields + +Some fields accept rich text content. These fields accept HTML input, which will be sanitized to remove unsafe tags and attributes. + +See the [rich text guide](sections/rich_text.md) for more information, including how to attach files to rich text fields using the direct upload flow. diff --git a/docs/api/sections/account.md b/docs/api/sections/account.md new file mode 100644 index 0000000000..7984aeefbe --- /dev/null +++ b/docs/api/sections/account.md @@ -0,0 +1,113 @@ +# Account + +## `GET /:account_slug/account/settings` + +Returns the current account. + +__Response:__ + +```json +{ + "id": "03f5v9zjvypwh0t0e2rfh0h7k", + "name": "37signals", + "cards_count": 5, + "created_at": "2025-12-05T19:36:35.401Z", + "auto_postpone_period_in_days": 30 +} +``` + +The `auto_postpone_period_in_days` is the account-level default in days (e.g. `30`). Cards are automatically moved to "Not Now" after this period of inactivity. Each board can override this with its own value. + +## `GET /:account_slug/account/join_code` + +Returns the account's join code for inviting new users. The join code URL can be shared with people to let them join the account. + +__Response:__ + +```json +{ + "code": "abc123", + "usage_count": 3, + "usage_limit": 10, + "url": "http://app.fizzy.localhost:3006/897362094/join/abc123", + "active": true +} +``` + +A join code is `active` when `usage_count` is less than `usage_limit`. + +## `PUT /:account_slug/account/join_code` + +Updates the join code's usage limit. Requires admin role. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `usage_limit` | integer | Yes | Maximum number of times the join code can be used | + +__Request:__ + +```json +{ + "account_join_code": { + "usage_limit": 10 + } +} +``` + +__Response:__ + +Returns `204 No Content` on success. + +## `DELETE /:account_slug/account/join_code` + +Resets the join code, generating a new one and invalidating the old code. Requires admin role. + +__Response:__ + +Returns `204 No Content` on success. + +## `PUT /:account_slug/account/entropy` + +Updates the account-level default auto close period. Requires admin role. + +__Request:__ + +```json +{ + "entropy": { + "auto_postpone_period_in_days": 30 + } +} +``` + +__Response:__ + +Returns the account object: + +```json +{ + "id": "03f5v9zjvypwh0t0e2rfh0h7k", + "name": "37signals", + "cards_count": 5, + "created_at": "2025-12-05T19:36:35.401Z", + "auto_postpone_period_in_days": 30 +} +``` + +## `PUT /:account_slug/boards/:board_id/entropy` + +Updates the auto close period for a specific board. Requires board admin permission. + +__Request:__ + +```json +{ + "board": { + "auto_postpone_period_in_days": 90 + } +} +``` + +__Response:__ + +Returns the board object. diff --git a/docs/api/sections/activities.md b/docs/api/sections/activities.md new file mode 100644 index 0000000000..33bf1bf70b --- /dev/null +++ b/docs/api/sections/activities.md @@ -0,0 +1,161 @@ +# Activities + +Activities are the activity stream for an account — a record of significant actions like cards being published, assigned, closed, and commented on. + +## `GET /:account_slug/activities` + +Returns a paginated flat list of activities the current user can access, sorted newest first. + +__Query Parameters:__ + +| Parameter | Description | +|-----------|-------------| +| `creator_ids[]` | Filter to activities created by specific user ID(s). Multiple values are ORed. | +| `board_ids[]` | Filter to activities on specific board ID(s). Multiple values are ORed. | + +Different filter params are ANDed together: `creator_ids[]=A&board_ids[]=X` means activities created by A on board X. + +To fetch activity for a specific user, use `creator_ids[]=USER_ID`. + +__Supported actions:__ + +| `action` | `eventable_type` | `particulars` shape | +|----------|-----------------|---------------------| +| `card_assigned` | `Card` | `{ "assignee_ids": [USER_ID, ...] }` | +| `card_auto_postponed` | `Card` | `{}` | +| `card_board_changed` | `Card` | `{ "old_board": STRING, "new_board": STRING }` | +| `card_closed` | `Card` | `{}` | +| `card_postponed` | `Card` | `{}` | +| `card_published` | `Card` | `{}` | +| `card_reopened` | `Card` | `{}` | +| `card_sent_back_to_triage` | `Card` | `{}` | +| `card_title_changed` | `Card` | `{ "old_title": STRING, "new_title": STRING }` | +| `card_triaged` | `Card` | `{ "column": STRING }` | +| `card_unassigned` | `Card` | `{ "assignee_ids": [USER_ID, ...] }` | +| `comment_created` | `Comment` | `{}` | + +`particulars` is always an object. It contains action-specific metadata in a normalized format intended for API clients. It does not necessarily mirror the internal event JSON stored by Fizzy. Unknown keys may appear in the future and should be ignored. For `card_assigned` and `card_unassigned`, `assignee_ids` is currently a single-element array in practice. + +__`particulars` examples:__ + +```json +{ "action": "card_assigned", "particulars": { "assignee_ids": ["03f5user123"] } } +{ "action": "card_unassigned", "particulars": { "assignee_ids": ["03f5user123"] } } +{ "action": "card_board_changed", "particulars": { "old_board": "Backlog", "new_board": "Mobile" } } +{ "action": "card_title_changed", "particulars": { "old_title": "Fix login", "new_title": "Fix mobile login" } } +{ "action": "card_triaged", "particulars": { "column": "In Progress" } } +{ "action": "card_closed", "particulars": {} } +``` + +The practical `eventable_type` values are `Card` and `Comment`. Clients should handle unknown future values conservatively. + +Activities whose underlying `Card` or `Comment` has been deleted or is inaccessible to the current user are omitted from the feed. The endpoint never returns `eventable: null`. + +The top-level `board` field reflects the activity's current board association. If a card moves boards, all its activities move with it for the purposes of this feed and `board_ids[]` filtering. + +This endpoint is a paginated activity feed, not an immutable audit-log. `description`, `eventable`, `board`, and `creator` may reflect current resource state. Re-fetch recent pages to get fresh activity data. + +__Response:__ + +```json +[ + { + "id": "03faevt004", + "action": "card_closed", + "created_at": "2026-03-25T15:11:04.000Z", + "description": "David Heinemeier Hansson moved \"Fix mobile login\" to \"Done\"", + "particulars": {}, + "url": "http://app.fizzy.localhost:3006/897362094/cards/42", + "eventable_type": "Card", + "eventable": { + "id": "03f6card042", + "number": 42, + "title": "Fix mobile login", + "status": "closed", + "description": "Users cannot complete login on iOS.", + "description_html": "
Users cannot complete login on iOS.
", + "image_url": null, + "has_attachments": false, + "tags": ["ios", "auth"], + "closed": true, + "postponed": false, + "golden": false, + "last_active_at": "2026-03-25T15:11:04.000Z", + "created_at": "2026-03-25T09:00:00.000Z", + "url": "http://app.fizzy.localhost:3006/897362094/cards/42" + }, + "board": { + "id": "03f6abc123", + "name": "Mobile", + "all_access": true, + "created_at": "2026-03-01T10:00:00.000Z", + "auto_postpone_period_in_days": 14, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f6abc123" + }, + "creator": { + "id": "03f5user123", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2026-03-01T09:00:00.000Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5user123", + "avatar_url": "http://app.fizzy.localhost:3006/897362094/users/03f5user123/avatar" + } + }, + { + "id": "03faevt003", + "action": "comment_created", + "created_at": "2026-03-25T14:17:22.000Z", + "description": "David Heinemeier Hansson commented on \"Fix mobile login\"", + "particulars": {}, + "url": "http://app.fizzy.localhost:3006/897362094/cards/42#comment_03facomment9", + "eventable_type": "Comment", + "eventable": { + "id": "03facomment9", + "created_at": "2026-03-25T14:17:22.000Z", + "updated_at": "2026-03-25T14:17:22.000Z", + "body": { + "plain_text": "I found the regression in the callback flow.", + "html": "
I found the regression in the callback flow.
" + }, + "creator": { + "id": "03f5user123", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2026-03-01T09:00:00.000Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5user123", + "avatar_url": "http://app.fizzy.localhost:3006/897362094/users/03f5user123/avatar" + }, + "card": { + "id": "03f6card042", + "url": "http://app.fizzy.localhost:3006/897362094/cards/42" + }, + "reactions_url": "http://app.fizzy.localhost:3006/897362094/cards/42/comments/03facomment9/reactions", + "url": "http://app.fizzy.localhost:3006/897362094/cards/42/comments/03facomment9" + }, + "board": { + "id": "03f6abc123", + "name": "Mobile", + "all_access": true, + "created_at": "2026-03-01T10:00:00.000Z", + "auto_postpone_period_in_days": 14, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f6abc123" + }, + "creator": { + "id": "03f5user123", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2026-03-01T09:00:00.000Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5user123", + "avatar_url": "http://app.fizzy.localhost:3006/897362094/users/03f5user123/avatar" + } + } +] +``` + +All `url` fields are opaque absolute URLs for the current Fizzy instance. Clients should not construct them. diff --git a/docs/api/sections/authentication.md b/docs/api/sections/authentication.md new file mode 100644 index 0000000000..f06ea6e882 --- /dev/null +++ b/docs/api/sections/authentication.md @@ -0,0 +1,210 @@ +# Authentication + +There are two ways to authenticate with the Fizzy API: + +1. **Personal access tokens** - Long-lived tokens for scripts and integrations +2. **Magic link authentication** - Session-based authentication for native apps + +## Personal Access Tokens + +To use the API you'll need an access token. To get one, go to your profile, then, +in the API section, click on "Personal access tokens" and then click on +"Generate new access token". + +Give it a description and pick what kind of permission you want the access token to have: +- `Read`: allows reading data from your account +- `Read + Write`: allows reading and writing data to your account on your behalf + +Then click on "Generate access token". + +
+ Access token generation guide with screenshots + + | Step | Description | Screenshot | + |:----:|-------------|:----------:| + | 1 | Go to your profile | Profile page with API section | + | 2 | In the API section click on "Personal access token" | Personal access tokens page | + | 3 | Click on "Generate a new access token" | Generate new access token dialog | + | 4 | Give it a description and assign it a permission | Access token created | +
+ +> [!IMPORTANT] +> __An access token is like a password, keep it secret and do not share it with anyone.__ +> Any person or application that has your access token can perform actions on your behalf. + +To authenticate a request using your access token, include it in the `Authorization` header: + +```bash +curl -H "Authorization: Bearer put-your-access-token-here" -H "Accept: application/json" https://app.fizzy.do/my/identity +``` + +## Magic Link Authentication + +For native apps, you can authenticate users via magic links. This is a two-step process: + +### 1. Request a magic link + +Send the user's email address to request a magic link be sent to them: + +```bash +curl -X POST \ + -H "Content-Type: application/json" \ + -H "Accept: application/json" \ + -d '{"email_address": "user@example.com"}' \ + https://app.fizzy.do/session +``` + +__Response:__ + +``` +HTTP/1.1 201 Created +Set-Cookie: pending_authentication_token=...; HttpOnly; SameSite=Lax +``` + +```json +{ + "pending_authentication_token": "eyJfcmFpbHMi..." +} +``` + +The response includes a `pending_authentication_token` both in the JSON body and as a cookie. +Native apps should store this token and include it as a cookie when submitting the magic link code. + +__Error responses:__ + +| Status Code | Description | +|--------|-------------| +| `422 Unprocessable entity` | Invalid email address, if sign ups are enabled and the value isn't a valid email address | +| `429 Too Many Requests` | Rate limit exceeded | + +### 2. Submit the magic link code + +Once the user receives the magic link email, they'll have a 6-character code. Submit it to complete authentication: + +```bash +curl -X POST \ + -H "Content-Type: application/json" \ + -H "Accept: application/json" \ + -H "Cookie: pending_authentication_token=eyJfcmFpbHMi..." \ + -d '{"code": "ABC123"}' \ + https://app.fizzy.do/session/magic_link +``` + +__Response:__ + +```json +{ + "session_token": "eyJfcmFpbHMi..." +} +``` + +The `session_token` can be used to authenticate subsequent requests by including it as a cookie: + +```bash +curl -H "Cookie: session_token=eyJfcmFpbHMi..." \ + -H "Accept: application/json" \ + https://app.fizzy.do/my/identity +``` + +__Error responses:__ + +| Status Code | Description | +|--------|-------------| +| `401 Unauthorized` | Invalid `pending_authentication_token` or `code` | +| `429 Too Many Requests` | Rate limit exceeded | + + +### Delete server-side session (_log out_) + +To log out and destroy the server-side session: + +```bash +curl -X DELETE \ + -H "Accept: application/json" \ + -H "Cookie: session_token=eyJfcmFpbHMi..." \ + https://app.fizzy.do/session +``` + +__Response:__ + +Returns `204 No Content` on success. + +### Create an access token via the API + +You can programmatically create a personal access token using either a session cookie or an existing Bearer token: + +```bash +curl -X POST \ + -H "Content-Type: application/json" \ + -H "Accept: application/json" \ + -H "Cookie: session_token=eyJfcmFpbHMi..." \ + -d '{"access_token": {"description": "Fizzy CLI", "permission": "write"}}' \ + https://app.fizzy.do/1234567/my/access_tokens +``` + +Or with a Bearer token (must have `write` permission): + +```bash +curl -X POST \ + -H "Content-Type: application/json" \ + -H "Accept: application/json" \ + -H "Authorization: Bearer put-your-access-token-here" \ + -d '{"access_token": {"description": "Fizzy CLI", "permission": "write"}}' \ + https://app.fizzy.do/1234567/my/access_tokens +``` + +The `permission` field accepts `read` or `write`. + +__Response:__ + +``` +HTTP/1.1 201 Created +``` + +```json +{ + "token": "4f9Q6d2wXr8Kp1Ls0Vz3BnTa", + "description": "Fizzy CLI", + "permission": "write" +} +``` + +Store the `token` value securely — it won't be retrievable again. Use it as a Bearer token for subsequent API requests. + +### List access tokens + +Returns all access tokens for the authenticated identity. + +```bash +curl -H "Authorization: Bearer put-your-access-token-here" \ + -H "Accept: application/json" \ + https://app.fizzy.do/my/access_tokens +``` + +__Response:__ + +```json +[ + { + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "description": "Fizzy CLI", + "permission": "write", + "created_at": "2025-12-05T19:36:35.534Z" + } +] +``` + +Note: The raw token value is only returned once at creation time and cannot be retrieved again. + +### Delete an access token + +```bash +curl -X DELETE \ + -H "Authorization: Bearer put-your-access-token-here" \ + -H "Accept: application/json" \ + https://app.fizzy.do/my/access_tokens/:id +``` + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/boards.md b/docs/api/sections/boards.md new file mode 100644 index 0000000000..11e5a43fb7 --- /dev/null +++ b/docs/api/sections/boards.md @@ -0,0 +1,258 @@ +# Boards + +Boards are where you organize your work - they contain your cards. + +## `GET /:account_slug/boards` + +Returns a list of boards that you can access in the specified account. + +__Response:__ + +```json +[ + { + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Fizzy", + "all_access": true, + "created_at": "2025-12-05T19:36:35.534Z", + "auto_postpone_period_in_days": 30, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + } + } +] +``` + +## `GET /:account_slug/boards/:board_id` + +Returns the specified board. + +__Response:__ + +```json +{ + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Fizzy", + "all_access": false, + "created_at": "2025-12-05T19:36:35.534Z", + "auto_postpone_period_in_days": 30, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "public_description": "Follow along with public product updates.", + "public_description_html": "

Follow along with public product updates.

", + "user_ids": [ + "03f5v9zjw7pz8717a4no1h8a7", + "03f5v9zppzlksuj4mxba2nbzn" + ], + "public_url": "http://app.fizzy.localhost:3006/897362094/public/boards/aB3dEfGhIjKlMnOp" +} +``` + +The `public_description`, `public_description_html`, and `public_url` fields are only present when the board is published. The `user_ids` field is only present when `all_access` is `false`; use `GET /:account_slug/users` to resolve those IDs to user records if needed. + +## `POST /:account_slug/boards` + +Creates a new Board in the account. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `name` | string | Yes | The name of the board | +| `all_access` | boolean | No | Whether any user in the account can access this board. Defaults to `true` | +| `auto_postpone_period_in_days` | integer | No | Number of days of inactivity before cards are automatically postponed (e.g. `30`) | +| `public_description` | string | No | Rich text description shown on the public board page | + +__Request:__ + +```json +{ + "board": { + "name": "My new board" + } +} +``` + +__Response:__ + +Returns `201 Created` with a `Location` header pointing to the new board: + +``` +HTTP/1.1 201 Created +Location: /897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm.json +``` + +## `PUT /:account_slug/boards/:board_id` + +Updates a Board. Only board administrators can update a board. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `name` | string | No | The name of the board | +| `all_access` | boolean | No | Whether any user in the account can access this board | +| `auto_postpone_period_in_days` | integer | No | Number of days of inactivity before cards are automatically postponed (e.g. `30`) | +| `public_description` | string | No | Rich text description shown on the public board page | +| `user_ids` | array | No | Array of *all* user IDs who should have access to this board (only applicable when `all_access` is `false`) | + +__Request:__ + +```json +{ + "board": { + "name": "Updated board name", + "auto_postpone_period_in_days": 30, + "public_description": "This is a **public** description of the board.", + "all_access": false, + "user_ids": [ + "03f5v9zppzlksuj4mxba2nbzn", + "03f5v9zjw7pz8717a4no1h8a7" + ] + } +} +``` + +__Response:__ + +Returns `200 OK` with the updated board in the same shape as `GET /:account_slug/boards/:board_id`: + +```json +{ + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Updated board name", + "all_access": false, + "created_at": "2025-12-05T19:36:35.534Z", + "auto_postpone_period_in_days": 30, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "user_ids": [ + "03f5v9zppzlksuj4mxba2nbzn", + "03f5v9zjw7pz8717a4no1h8a7" + ] +} +``` + +If the update succeeds but removes the requesting user's own access to the board, the endpoint instead returns `204 No Content`. + +## `DELETE /:account_slug/boards/:board_id` + +Deletes a Board. Only board administrators can delete a board. + +__Response:__ + +Returns `204 No Content` on success. + +## Board Accesses + +Board accesses let you see who has access to a board and their involvement level (watching or access only). Any board member can view this information. + +### `GET /:account_slug/boards/:board_id/accesses` + +Returns a paginated list of active account users with their access status for the specified board. + +__Response:__ + +```json +{ + "board_id": "03f5v9zkft4hj9qq0lsn9ohcm", + "all_access": false, + "users": [ + { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7", + "avatar_url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7/avatar", + "has_access": true, + "involvement": "watching" + }, + { + "id": "03f5v9zppzlksuj4mxba2nbzn", + "name": "Kevin Clark", + "role": "admin", + "active": true, + "email_address": "kevin@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zppzlksuj4mxba2nbzn", + "avatar_url": "http://fizzy.localhost:3006/897362094/users/03f5v9zppzlksuj4mxba2nbzn/avatar", + "has_access": false, + "involvement": null + } + ] +} +``` + +- `has_access` indicates whether the user has access to the board +- `involvement` is `"watching"`, `"access_only"`, or `null` (when the user does not have access) +- When `all_access` is `true`, all active account users have access to the board +- The `users` array contains the current page of results; if there are more users, follow the `Link` response header with `rel="next"` + +To change who has access, use `PUT /:account_slug/boards/:board_id` with the `user_ids` parameter. + +## Board Publications + +Publishing a board makes it publicly accessible via a shareable link, without requiring authentication. Only board administrators can publish or unpublish a board. + +## `POST /:account_slug/boards/:board_id/publication` + +Publishes a board, generating a shareable public link. + +__Response:__ + +``` +HTTP/1.1 201 Created +``` + +```json +{ + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Fizzy", + "all_access": true, + "created_at": "2025-12-05T19:36:35.534Z", + "auto_postpone_period_in_days": 30, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "public_url": "http://app.fizzy.localhost:3006/897362094/public/boards/aB3dEfGhIjKlMnOp" +} +``` + +If the board is already published, the existing publication is returned. + +## `DELETE /:account_slug/boards/:board_id/publication` + +Unpublishes a board, removing public access. + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/cards.md b/docs/api/sections/cards.md new file mode 100644 index 0000000000..800ed82088 --- /dev/null +++ b/docs/api/sections/cards.md @@ -0,0 +1,348 @@ +# Cards + +Cards are tasks or items of work on a board. They can be organized into columns, tagged, assigned to users, and have comments. + +## `GET /:account_slug/cards` + +Returns a paginated list of cards you have access to. Results can be filtered using query parameters. + +__Query Parameters:__ + +| Parameter | Description | +|-----------|-------------| +| `board_ids[]` | Filter by board ID(s) | +| `tag_ids[]` | Filter by tag ID(s) | +| `assignee_ids[]` | Filter by assignee user ID(s) | +| `creator_ids[]` | Filter by card creator ID(s) | +| `closer_ids[]` | Filter by user ID(s) who closed the cards | +| `card_ids[]` | Filter to specific card ID(s) | +| `column_ids[]` | Filter by workflow column ID(s) | +| `indexed_by` | Filter by: `all` (default), `maybe`, `closed`, `not_now`, `stalled`, `postponing_soon`, `golden` | +| `sorted_by` | Sort order: `latest` (default), `newest`, `oldest` | +| `assignment_status` | Filter by assignment status: `unassigned` | +| `creation` | Filter by creation date: `today`, `yesterday`, `thisweek`, `lastweek`, `thismonth`, `lastmonth`, `thisyear`, `lastyear` | +| `closure` | Filter by closure date: `today`, `yesterday`, `thisweek`, `lastweek`, `thismonth`, `lastmonth`, `thisyear`, `lastyear` | +| `terms[]` | Search terms to filter cards | + +Repeated `column_ids[]` values are ORed together. Other filters combine with AND. + +Example: +- `column_ids[]=03f...` — cards in a workflow column by ID + +__Response:__ + +```json +[ + { + "id": "03f5vaeq985jlvwv3arl4srq2", + "number": 1, + "title": "First!", + "status": "published", + "description": "Hello, World!", + "description_html": "

Hello, World!

", + "image_url": null, + "has_attachments": false, + "tags": ["programming"], + "golden": false, + "last_active_at": "2025-12-05T19:38:48.553Z", + "created_at": "2025-12-05T19:38:48.540Z", + "url": "http://app.fizzy.localhost:3006/897362094/cards/4", + "board": { + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Fizzy", + "all_access": true, + "created_at": "2025-12-05T19:36:35.534Z", + "auto_postpone_period_in_days": 30, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + } + }, + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "comments_url": "http://app.fizzy.localhost:3006/897362094/cards/4/comments", + "reactions_url": "http://app.fizzy.localhost:3006/897362094/cards/4/reactions" + } +] +``` + +## `GET /:account_slug/cards/:card_number` + +Returns a specific card by its number. + +__Response:__ + +```json +{ + "id": "03f5vaeq985jlvwv3arl4srq2", + "number": 1, + "title": "First!", + "status": "published", + "description": "Hello, World!", + "description_html": "

Hello, World!

", + "image_url": null, + "has_attachments": false, + "tags": ["programming"], + "closed": false, + "golden": false, + "last_active_at": "2025-12-05T19:38:48.553Z", + "created_at": "2025-12-05T19:38:48.540Z", + "url": "http://app.fizzy.localhost:3006/897362094/cards/4", + "board": { + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Fizzy", + "all_access": true, + "created_at": "2025-12-05T19:36:35.534Z", + "auto_postpone_period_in_days": 30, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + } + }, + "column": { + "id": "03f5v9zkft4hj9qq0lsn9ohcn", + "name": "In Progress", + "color": { + "name": "Lime", + "value": "var(--color-card-4)" + }, + "created_at": "2025-12-05T19:36:35.534Z" + }, + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "comments_url": "http://app.fizzy.localhost:3006/897362094/cards/4/comments", + "reactions_url": "http://app.fizzy.localhost:3006/897362094/cards/4/reactions", + "steps": [ + { + "id": "03f8huu0sog76g3s975963b5e", + "content": "This is the first step", + "completed": false + }, + { + "id": "03f8huu0sog76g3s975969734", + "content": "This is the second step", + "completed": false + } + ] +} +``` + +> **Note:** The `closed` field indicates whether the card is in the "Done" state. The `column` field is only present when the card has been triaged into a column; cards in "Maybe?", "Not Now" or "Done" will not have this field. + +## `POST /:account_slug/boards/:board_id/cards` + +Creates a new card in a board. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `title` | string | Yes | The title of the card | +| `description` | string | No | Rich text description of the card | +| `status` | string | No | Initial status: `published` (default), `drafted` | +| `image` | file | No | Header image for the card | +| `tag_ids` | array | No | Array of tag IDs to apply to the card | +| `created_at` | datetime | No | Override creation timestamp (ISO 8601 format) | +| `last_active_at` | datetime | No | Override last activity timestamp (ISO 8601 format) | + +__Request:__ + +```json +{ + "card": { + "title": "Add dark mode support", + "description": "We need to add dark mode to the app" + } +} +``` + +__Response:__ + +Returns `201 Created` with a `Location` header pointing to the new card. + +## `PUT /:account_slug/cards/:card_number` + +Updates a card. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `title` | string | No | The title of the card | +| `description` | string | No | Rich text description of the card | +| `status` | string | No | Card status: `drafted`, `published` | +| `image` | file | No | Header image for the card | +| `tag_ids` | array | No | Array of tag IDs to apply to the card | +| `last_active_at` | datetime | No | Override last activity timestamp (ISO 8601 format) | + +__Request:__ + +```json +{ + "card": { + "title": "Add dark mode support (Updated)" + } +} +``` + +__Response:__ + +Returns the updated card. + +## `DELETE /:account_slug/cards/:card_number` + +Deletes a card. Only the card creator or board administrators can delete cards. + +__Response:__ + +Returns `204 No Content` on success. + +## `DELETE /:account_slug/cards/:card_number/image` + +Removes the header image from a card. + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/cards/:card_number/closure` + +Closes a card. + +__Response:__ + +Returns `204 No Content` on success. + +## `DELETE /:account_slug/cards/:card_number/closure` + +Reopens a closed card. + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/cards/:card_number/not_now` + +Moves a card to "Not Now" status. + +__Response:__ + +Returns `204 No Content` on success. + +## `PUT /:account_slug/cards/:card_number/board` + +Moves a card to a different board. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `board_id` | string | Yes | The ID of the board to move the card to | + +__Request:__ + +```json +{ + "board_id": "03f5v9zkft4hj9qq0lsn9ohcm" +} +``` + +__Response:__ + +Returns `200 OK` with the moved card in the same shape as `GET /:account_slug/cards/:card_number`. The `board` field reflects the new board. + +## `POST /:account_slug/cards/:card_number/triage` + +Moves a card into a column. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `column_id` | string | Yes | The ID of the column to move the card into | + +__Response:__ + +Returns `204 No Content` on success. + +## `DELETE /:account_slug/cards/:card_number/triage` + +Sends a card back to triage. + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/cards/:card_number/taggings` + +Toggles a tag on or off for a card. If the tag doesn't exist, it will be created. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `tag_title` | string | Yes | The title of the tag (leading `#` is stripped) | + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/cards/:card_number/assignments` + +Toggles assignment of a user to/from a card. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `assignee_id` | string | Yes | The ID of the user to assign/unassign | + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/cards/:card_number/watch` + +Subscribes the current user to notifications for this card. + +__Response:__ + +Returns `204 No Content` on success. + +## `DELETE /:account_slug/cards/:card_number/watch` + +Unsubscribes the current user from notifications for this card. + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/cards/:card_number/goldness` + +Marks a card as golden. + +__Response:__ + +Returns `204 No Content` on success. + +## `DELETE /:account_slug/cards/:card_number/goldness` + +Removes golden status from a card. + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/columns.md b/docs/api/sections/columns.md new file mode 100644 index 0000000000..481ad50351 --- /dev/null +++ b/docs/api/sections/columns.md @@ -0,0 +1,181 @@ +# Columns + +Columns represent stages in a workflow on a board. Cards move through columns as they progress. + +## `GET /:account_slug/boards/:board_id/columns` + +Returns a list of columns on a board, sorted by position. + +__Response:__ + +```json +[ + { + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Recording", + "color": "var(--color-card-default)", + "created_at": "2025-12-05T19:36:35.534Z", + "cards_url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm/columns/03f5v9zkft4hj9qq0lsn9ohcm/cards" + }, + { + "id": "03f5v9zkft4hj9qq0lsn9ohcn", + "name": "Published", + "color": "var(--color-card-4)", + "created_at": "2025-12-05T19:36:35.534Z", + "cards_url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm/columns/03f5v9zkft4hj9qq0lsn9ohcn/cards" + } +] +``` + +## `GET /:account_slug/boards/:board_id/columns/:column_id` + +Returns the specified column metadata. + +__Response:__ + +```json +{ + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "In Progress", + "color": "var(--color-card-default)", + "created_at": "2025-12-05T19:36:35.534Z", + "cards_url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm/columns/03f5v9zkft4hj9qq0lsn9ohcm/cards" +} +``` + +## `GET /:account_slug/boards/:board_id/columns/:column_id/cards` + +Returns a paginated list of open cards in the specified workflow column. +This only includes cards triaged into that column. Cards in "Maybe?", "Not Now", and "Done" +are not included. + +The response items have the same shape as `GET /:account_slug/cards`. + +__Response:__ + +```json +[ + { + "id": "03f5vaeq985jlvwv3arl4srq2", + "number": 1, + "title": "First!", + "status": "published", + "description": "Hello, World!", + "description_html": "

Hello, World!

", + "image_url": null, + "has_attachments": false, + "tags": ["programming"], + "closed": false, + "postponed": false, + "golden": false, + "last_active_at": "2025-12-05T19:38:48.553Z", + "created_at": "2025-12-05T19:38:48.540Z", + "url": "http://fizzy.localhost:3006/897362094/cards/4", + "board": { + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Fizzy", + "all_access": true, + "created_at": "2025-12-05T19:36:35.534Z", + "auto_postpone_period_in_days": 30, + "url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7", + "avatar_url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7/avatar" + } + }, + "column": { + "id": "03f5v9zkft4hj9qq0lsn9ohcn", + "name": "In Progress", + "color": "var(--color-card-4)", + "created_at": "2025-12-05T19:36:35.534Z", + "cards_url": "http://fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm/columns/03f5v9zkft4hj9qq0lsn9ohcn/cards" + }, + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7", + "avatar_url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7/avatar" + }, + "assignees": [ + { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7", + "avatar_url": "http://fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7/avatar" + } + ], + "has_more_assignees": false, + "comments_url": "http://fizzy.localhost:3006/897362094/cards/4/comments", + "reactions_url": "http://fizzy.localhost:3006/897362094/cards/4/reactions" + } +] +``` + +## `POST /:account_slug/boards/:board_id/columns` + +Creates a new column on the board. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `name` | string | Yes | The name of the column | +| `color` | string | No | The column color. One of: `var(--color-card-default)` (Blue), `var(--color-card-1)` (Gray), `var(--color-card-2)` (Tan), `var(--color-card-3)` (Yellow), `var(--color-card-4)` (Lime), `var(--color-card-5)` (Aqua), `var(--color-card-6)` (Violet), `var(--color-card-7)` (Purple), `var(--color-card-8)` (Pink) | + +__Request:__ + +```json +{ + "column": { + "name": "In Progress", + "color": "var(--color-card-4)" + } +} +``` + +__Response:__ + +Returns `201 Created` with a `Location` header pointing to the new column. + +## `PUT /:account_slug/boards/:board_id/columns/:column_id` + +Updates a column. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `name` | string | No | The name of the column | +| `color` | string | No | The column color | + +__Request:__ + +```json +{ + "column": { + "name": "Done" + } +} +``` + +__Response:__ + +Returns `200 OK` with the updated column in the same shape as `GET /:account_slug/boards/:board_id/columns/:column_id`. + +## `DELETE /:account_slug/boards/:board_id/columns/:column_id` + +Deletes a column. + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/comments.md b/docs/api/sections/comments.md new file mode 100644 index 0000000000..80a5f13dad --- /dev/null +++ b/docs/api/sections/comments.md @@ -0,0 +1,124 @@ +# Comments + +Comments are attached to cards and support rich text. + +## `GET /:account_slug/cards/:card_number/comments` + +Returns a paginated list of comments on a card, sorted chronologically (oldest first). + +__Response:__ + +```json +[ + { + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "created_at": "2025-12-05T19:36:35.534Z", + "updated_at": "2025-12-05T19:36:35.534Z", + "body": { + "plain_text": "This looks great!", + "html": "
This looks great!
" + }, + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "card": { + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "url": "http://app.fizzy.localhost:3006/897362094/cards/03f5v9zo9qlcwwpyc0ascnikz" + }, + "reactions_url": "http://app.fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz/reactions", + "url": "http://app.fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz" + } +] +``` + +## `GET /:account_slug/cards/:card_number/comments/:comment_id` + +Returns a specific comment. + +__Response:__ + +```json +{ + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "created_at": "2025-12-05T19:36:35.534Z", + "updated_at": "2025-12-05T19:36:35.534Z", + "body": { + "plain_text": "This looks great!", + "html": "
This looks great!
" + }, + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "card": { + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "url": "http://app.fizzy.localhost:3006/897362094/cards/03f5v9zo9qlcwwpyc0ascnikz" + }, + "reactions_url": "http://app.fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz/reactions", + "url": "http://app.fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz" +} +``` + +## `POST /:account_slug/cards/:card_number/comments` + +Creates a new comment on a card. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `body` | string | Yes | The comment body (supports rich text) | +| `created_at` | datetime | No | Override creation timestamp (ISO 8601 format) | + +__Request:__ + +```json +{ + "comment": { + "body": "This looks great!" + } +} +``` + +__Response:__ + +Returns `201 Created` with a `Location` header pointing to the new comment. + +## `PUT /:account_slug/cards/:card_number/comments/:comment_id` + +Updates a comment. Only the comment creator can update their comments. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `body` | string | Yes | The updated comment body | + +__Request:__ + +```json +{ + "comment": { + "body": "This looks even better now!" + } +} +``` + +__Response:__ + +Returns the updated comment. + +## `DELETE /:account_slug/cards/:card_number/comments/:comment_id` + +Deletes a comment. Only the comment creator can delete their comments. + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/exports.md b/docs/api/sections/exports.md new file mode 100644 index 0000000000..10ea38b102 --- /dev/null +++ b/docs/api/sections/exports.md @@ -0,0 +1,77 @@ +# Exports + +Exports are asynchronous jobs. Start an export with `POST`, then poll the export resource with `GET` until it reaches `completed`. When the export file is ready, the response includes a temporary `download_url`. + +Possible export statuses are: +- `pending` +- `processing` +- `completed` +- `failed` + +Completed export files expire after 24 hours. When that happens, request a new export. + +## `POST /:account_slug/account/exports` + +Starts an account export for the current account. Only account admins and owners can create account exports. + +__Response:__ + +Returns `201 Created` with the export object: + +```json +{ + "id": "03f8huu0sog76g3s97596abcd", + "status": "pending", + "created_at": "2026-04-02T12:34:56Z" +} +``` + +## `GET /:account_slug/account/exports/:id` + +Returns the status of an account export created by the current user. + +__Response:__ + +```json +{ + "id": "03f8huu0sog76g3s97596abcd", + "status": "completed", + "created_at": "2026-04-02T12:34:56Z", + "download_url": "https://app.fizzy.do/rails/active_storage/blobs/redirect/.../fizzy-account-export.zip" +} +``` + +The `download_url` field is only present when the export is completed and the export file is still available. Download requests still require normal authenticated access as the export owner. + +## `POST /:account_slug/users/:user_id/data_exports` + +Starts a personal data export for the current user. You can only create exports for your own user record. + +__Response:__ + +Returns `201 Created` with the export object: + +```json +{ + "id": "03f8huu0sog76g3s97596wxyz", + "status": "pending", + "created_at": "2026-04-02T12:34:56Z" +} +``` + +## `GET /:account_slug/users/:user_id/data_exports/:id` + +Returns the status of one of your personal data exports. + +__Response:__ + +```json +{ + "id": "03f8huu0sog76g3s97596wxyz", + "status": "completed", + "created_at": "2026-04-02T12:34:56Z", + "download_url": "https://app.fizzy.do/rails/active_storage/blobs/redirect/.../fizzy-user-data-export.zip" +} +``` + +The `download_url` field is only present when the export is completed and the export file is still available. Download requests still require normal authenticated access as the export owner. diff --git a/docs/api/sections/identity.md b/docs/api/sections/identity.md new file mode 100644 index 0000000000..8edcc07a6b --- /dev/null +++ b/docs/api/sections/identity.md @@ -0,0 +1,66 @@ +# Identity + +An Identity represents a person using Fizzy. + +## `GET /my/identity` + +Returns a list of accounts the identity has access to, including the user for each account. + +__Response:__ + +```json +{ + "accounts": [ + { + "id": "03f5v9zjskhcii2r45ih3u1rq", + "name": "37signals", + "slug": "/897362094", + "created_at": "2025-12-05T19:36:35.377Z", + "user": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/users/03f5v9zjw7pz8717a4no1h8a7" + } + }, + { + "id": "03f5v9zpko7mmhjzwum3youpp", + "name": "Honcho", + "slug": "/686465299", + "created_at": "2025-12-05T19:36:36.746Z", + "user": { + "id": "03f5v9zppzlksuj4mxba2nbzn", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:36.783Z", + "url": "http://app.fizzy.localhost:3006/users/03f5v9zppzlksuj4mxba2nbzn" + } + } + ] +} +``` + +## `PATCH /:account_slug/my/timezone` + +Updates the current user's timezone. This affects how times are displayed in notification emails. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `timezone_name` | string | Yes | IANA timezone identifier (e.g. `America/New_York`, `Europe/London`, `Asia/Tokyo`) | + +__Request:__ + +```json +{ + "timezone_name": "America/New_York" +} +``` + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/notifications.md b/docs/api/sections/notifications.md new file mode 100644 index 0000000000..6bddff141c --- /dev/null +++ b/docs/api/sections/notifications.md @@ -0,0 +1,98 @@ +# Notifications + +Notifications inform users about events that happened in the account, such as comments, assignments, and card updates. + +## `GET /:account_slug/notifications` + +Returns a list of notifications for the current user. Unread notifications are returned first, followed by read notifications. + +__Response:__ + +```json +[ + { + "id": "03f5va03bpuvkcjemcxl73ho2", + "read": false, + "read_at": null, + "created_at": "2025-11-19T04:03:58.000Z", + "title": "Plain text mentions", + "body": "Assigned to self", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "card": { + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "title": "Plain text mentions", + "status": "published", + "url": "http://app.fizzy.localhost:3006/897362094/cards/3" + }, + "url": "http://app.fizzy.localhost:3006/897362094/notifications/03f5va03bpuvkcjemcxl73ho2" + } +] +``` + +## `POST /:account_slug/notifications/:notification_id/reading` + +Marks a notification as read. + +__Response:__ + +Returns `204 No Content` on success. + +## `DELETE /:account_slug/notifications/:notification_id/reading` + +Marks a notification as unread. + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/notifications/bulk_reading` + +Marks all unread notifications as read. + +__Response:__ + +Returns `204 No Content` on success. + +## `GET /:account_slug/notifications/settings` + +Returns the current user's notification settings. + +__Response:__ + +```json +{ + "bundle_email_frequency": "every_few_hours" +} +``` + +Possible values for `bundle_email_frequency`: `never`, `every_few_hours`, `daily`, `weekly`. + +## `PUT /:account_slug/notifications/settings` + +Updates the current user's notification settings. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `bundle_email_frequency` | string | Yes | How often to bundle notification emails. One of: `never`, `every_few_hours`, `daily`, `weekly` | + +__Request:__ + +```json +{ + "user_settings": { + "bundle_email_frequency": "daily" + } +} +``` + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/pins.md b/docs/api/sections/pins.md new file mode 100644 index 0000000000..ec22df568b --- /dev/null +++ b/docs/api/sections/pins.md @@ -0,0 +1,74 @@ +# Pins + +Pins let users keep quick access to important cards. + +## `POST /:account_slug/cards/:card_number/pin` + +Pins a card for the current user. + +__Response:__ + +Returns `204 No Content` on success. + +## `DELETE /:account_slug/cards/:card_number/pin` + +Unpins a card for the current user. + +__Response:__ + +Returns `204 No Content` on success. + +## `GET /:account_slug/my/pins` + +Returns the current user's pinned cards. This endpoint is not paginated and returns up to 100 cards. + +__Response:__ + +```json +[ + { + "id": "03f5vaeq985jlvwv3arl4srq2", + "number": 1, + "title": "First!", + "status": "published", + "description": "Hello, World!", + "description_html": "

Hello, World!

", + "image_url": null, + "has_attachments": false, + "tags": ["programming"], + "golden": false, + "last_active_at": "2025-12-05T19:38:48.553Z", + "created_at": "2025-12-05T19:38:48.540Z", + "url": "http://app.fizzy.localhost:3006/897362094/cards/4", + "board": { + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Fizzy", + "all_access": true, + "created_at": "2025-12-05T19:36:35.534Z", + "auto_postpone_period_in_days": 30, + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcm", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7", + "avatar_url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7/avatar" + } + }, + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7", + "avatar_url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7/avatar" + }, + "comments_url": "http://app.fizzy.localhost:3006/897362094/cards/4/comments" + } +] +``` diff --git a/docs/api/sections/reactions.md b/docs/api/sections/reactions.md new file mode 100644 index 0000000000..4eb5e78f02 --- /dev/null +++ b/docs/api/sections/reactions.md @@ -0,0 +1,119 @@ +# Reactions + +## Card Reactions (Boosts) + +Card reactions (also called "boosts") let users add short responses directly to cards. These are limited to 16 characters. + +## `GET /:account_slug/cards/:card_number/reactions` + +Returns a list of reactions on a card. + +__Response:__ + +```json +[ + { + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "content": "👍", + "reacter": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "url": "http://app.fizzy.localhost:3006/897362094/cards/3/reactions/03f5v9zo9qlcwwpyc0ascnikz" + } +] +``` + +## `POST /:account_slug/cards/:card_number/reactions` + +Adds a reaction (boost) to a card. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `content` | string | Yes | The reaction text (max 16 characters) | + +__Request:__ + +```json +{ + "reaction": { + "content": "Great 👍" + } +} +``` + +__Response:__ + +Returns `201 Created` on success. + +## `DELETE /:account_slug/cards/:card_number/reactions/:reaction_id` + +Removes your reaction from a card. Only the reaction creator can remove their own reactions. + +__Response:__ + +Returns `204 No Content` on success. + +## Comment Reactions + +Reactions are short (16-character max) responses to comments. + +## `GET /:account_slug/cards/:card_number/comments/:comment_id/reactions` + +Returns a list of reactions on a comment. + +__Response:__ + +```json +[ + { + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "content": "👍", + "reacter": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + "url": "http://app.fizzy.localhost:3006/897362094/cards/3/comments/03f5v9zo9qlcwwpyc0ascnikz/reactions/03f5v9zo9qlcwwpyc0ascnikz" + } +] +``` + +## `POST /:account_slug/cards/:card_number/comments/:comment_id/reactions` + +Adds a reaction to a comment. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `content` | string | Yes | The reaction text | + +__Request:__ + +```json +{ + "reaction": { + "content": "Great 👍" + } +} +``` + +__Response:__ + +Returns `201 Created` on success. + +## `DELETE /:account_slug/cards/:card_number/comments/:comment_id/reactions/:reaction_id` + +Removes your reaction from a comment. + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/rich_text.md b/docs/api/sections/rich_text.md new file mode 100644 index 0000000000..18cbb28f72 --- /dev/null +++ b/docs/api/sections/rich_text.md @@ -0,0 +1,86 @@ +# Rich Text Fields + +Some fields accept rich text content. These fields accept HTML input, which will be sanitized to remove unsafe tags and attributes. + +```json +{ + "card": { + "title": "My card", + "description": "

This is bold and this is italic.

  • Item 1
  • Item 2
" + } +} +``` + +## Attaching files to rich text + +To attach files (images, documents) to rich text fields, use ActionText's direct upload flow: + +### 1. Create a direct upload + +First, request a direct upload URL by sending file metadata: + +```bash +curl -X POST \ + -H "Authorization: Bearer put-your-access-token-here" \ + -H "Content-Type: application/json" \ + -d '{ + "blob": { + "filename": "screenshot.png", + "byte_size": 12345, + "checksum": "GQ5SqLsM7ylnji0Wgd9wNA==", + "content_type": "image/png" + } + }' \ + https://app.fizzy.do/123456/rails/active_storage/direct_uploads +``` + +The `checksum` is a Base64-encoded MD5 hash of the file content. +The direct upload endpoint is scoped to your account (replace `/123456` with your account slug). + +__Response:__ + +```json +{ + "id": "abc123", + "key": "abc123def456", + "filename": "screenshot.png", + "content_type": "image/png", + "byte_size": 12345, + "checksum": "GQ5SqLsM7ylnji0Wgd9wNA==", + "direct_upload": { + "url": "https://storage.example.com/...", + "headers": { + "Content-Type": "image/png", + "Content-MD5": "GQ5SqLsM7ylnji0Wgd9wNA==" + } + }, + "signed_id": "eyJfcmFpbHMi..." +} +``` + +### 2. Upload the file + +Upload the file directly to the provided URL with the specified headers: + +```bash +curl -X PUT \ + -H "Content-Type: image/png" \ + -H "Content-MD5: GQ5SqLsM7ylnji0Wgd9wNA==" \ + --data-binary @screenshot.png \ + "https://storage.example.com/..." +``` + +### 3. Reference the file in rich text + +Use the `signed_id` from step 1 to embed the file in your rich text using an `` tag: + +```json +{ + "card": { + "title": "Card with image", + "description": "

Here's a screenshot:

" + } +} +``` + +The `sgid` attribute should contain the `signed_id` returned from the direct upload response. diff --git a/docs/api/sections/steps.md b/docs/api/sections/steps.md new file mode 100644 index 0000000000..668957d37c --- /dev/null +++ b/docs/api/sections/steps.md @@ -0,0 +1,71 @@ +# Steps + +Steps are to-do items on a card. + +## `GET /:account_slug/cards/:card_number/steps/:step_id` + +Returns a specific step. + +__Response:__ + +```json +{ + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "content": "Write tests", + "completed": false +} +``` + +## `POST /:account_slug/cards/:card_number/steps` + +Creates a new step on a card. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `content` | string | Yes | The step text | +| `completed` | boolean | No | Whether the step is completed (default: `false`) | + +__Request:__ + +```json +{ + "step": { + "content": "Write tests" + } +} +``` + +__Response:__ + +Returns `201 Created` with a `Location` header pointing to the new step. + +## `PUT /:account_slug/cards/:card_number/steps/:step_id` + +Updates a step. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `content` | string | No | The step text | +| `completed` | boolean | No | Whether the step is completed | + +__Request:__ + +```json +{ + "step": { + "completed": true + } +} +``` + +__Response:__ + +Returns the updated step. + +## `DELETE /:account_slug/cards/:card_number/steps/:step_id` + +Deletes a step. + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/tags.md b/docs/api/sections/tags.md new file mode 100644 index 0000000000..89e1c4550c --- /dev/null +++ b/docs/api/sections/tags.md @@ -0,0 +1,26 @@ +# Tags + +Tags are labels that can be applied to cards for organization and filtering. + +## `GET /:account_slug/tags` + +Returns a list of all tags in the account, sorted alphabetically. + +__Response:__ + +```json +[ + { + "id": "03f5v9zo9qlcwwpyc0ascnikz", + "title": "bug", + "created_at": "2025-12-05T19:36:35.534Z", + "url": "http://app.fizzy.localhost:3006/897362094/cards?tag_ids[]=03f5v9zo9qlcwwpyc0ascnikz" + }, + { + "id": "03f5v9zo9qlcwwpyc0ascnilz", + "title": "feature", + "created_at": "2025-12-05T19:36:35.534Z", + "url": "http://app.fizzy.localhost:3006/897362094/cards?tag_ids[]=03f5v9zo9qlcwwpyc0ascnilz" + } +] +``` diff --git a/docs/api/sections/users.md b/docs/api/sections/users.md new file mode 100644 index 0000000000..6af8e88c2c --- /dev/null +++ b/docs/api/sections/users.md @@ -0,0 +1,150 @@ +# Users + +Users represent people who have access to an account. + +## `GET /:account_slug/users` + +Returns a list of active users in the account. + +__Response:__ + +```json +[ + { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + }, + { + "id": "03f5v9zjysoy0fqs9yg0ei3hq", + "name": "Jason Fried", + "role": "member", + "active": true, + "email_address": "jason@example.com", + "created_at": "2025-12-05T19:36:35.419Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjysoy0fqs9yg0ei3hq" + }, + { + "id": "03f5v9zk1dtqduod5bkhv3k8m", + "name": "Jason Zimdars", + "role": "member", + "active": true, + "email_address": "jz@example.com", + "created_at": "2025-12-05T19:36:35.435Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zk1dtqduod5bkhv3k8m" + }, + { + "id": "03f5v9zk3nw9ja92e7s4h2wbe", + "name": "Kevin Mcconnell", + "role": "member", + "active": true, + "email_address": "kevin@example.com", + "created_at": "2025-12-05T19:36:35.451Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zk3nw9ja92e7s4h2wbe" + } +] +``` + +## `GET /:account_slug/users/:user_id` + +Returns the specified user. + +__Response:__ + +```json +{ + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" +} +``` + +## `PUT /:account_slug/users/:user_id` + +Updates a user. You can only update users you have permission to change. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `name` | string | No | The user's display name | +| `avatar` | file | No | The user's avatar image | + +__Request:__ + +```json +{ + "user": { + "name": "David H. Hansson" + } +} +``` + +__Response:__ + +Returns `200 OK` with the updated user in the same shape as `GET /:account_slug/users/:user_id`. + +## `DELETE /:account_slug/users/:user_id/avatar` + +Removes the user's avatar image. You can only remove avatars for users you have permission to change. + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/users/:user_id/email_addresses` + +Initiates an email address change for the user. A confirmation email is sent to the new address with a token link. You can only change your own email address. + +This is a two-step process, similar to magic link authentication: + +1. Request the change (this endpoint) — a confirmation email is sent to the new address +2. Confirm the change (`POST .../confirmation`) — the token from the email is submitted to complete the change + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `email_address` | string | Yes | The new email address | + +__Response:__ + +Returns `201 Created` on success. The user must check the new email address for a confirmation link. + +__Error responses:__ + +| Status Code | Description | +|--------|-------------| +| `400 Bad Request` | Missing `email_address` parameter | +| `404 Not Found` | User is not your own | +| `422 Unprocessable Entity` | Invalid email format, same as current email, or already belongs to a user in the same account | +| `429 Too Many Requests` | Rate limit exceeded (5 per hour) | + +## `POST /:account_slug/users/:user_id/email_addresses/:token/confirmation` + +Confirms an email address change using the token from the confirmation email. This endpoint does not require authentication — the token itself serves as proof of access to the new email. + +The token is the full value from the confirmation URL sent in the email. It expires after 30 minutes. + +__Response:__ + +Returns `204 No Content` on success. The user's email address has been changed. + +__Error responses:__ + +| Status Code | Description | +|--------|-------------| +| `422 Unprocessable Entity` | Token is invalid or has expired | +| `429 Too Many Requests` | Rate limit exceeded (5 per hour) | + +## `DELETE /:account_slug/users/:user_id` + +Deactivates a user. You can only deactivate users you have permission to change. + +__Response:__ + +Returns `204 No Content` on success. diff --git a/docs/api/sections/webhooks.md b/docs/api/sections/webhooks.md new file mode 100644 index 0000000000..a4f48b5b14 --- /dev/null +++ b/docs/api/sections/webhooks.md @@ -0,0 +1,161 @@ +# Webhooks + +Webhooks notify another application when something happens on a board. Only account admins can list, view, create, update, delete, or reactivate webhooks. + +## `GET /:account_slug/boards/:board_id/webhooks` + +Returns a paginated list of webhooks for a board. + +__Response:__ + +```json +[ + { + "id": "03f5v9zkft4hj9qq0lsn9ohcm", + "name": "Production API", + "payload_url": "https://api.example.com/webhooks", + "active": true, + "signing_secret": "p94Bx2HjempCdYB4DTyZkY1b", + "subscribed_actions": ["card_published", "card_assigned", "card_closed"], + "created_at": "2025-12-05T19:36:35.534Z", + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcy/webhooks/03f5v9zkft4hj9qq0lsn9ohcm", + "board": { + "id": "03f5v9zkft4hj9qq0lsn9ohcy", + "name": "Fizzy", + "all_access": true, + "created_at": "2025-12-05T19:36:35.534Z", + "url": "http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcy", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson", + "role": "owner", + "active": true, + "email_address": "david@example.com", + "created_at": "2025-12-05T19:36:35.401Z", + "url": "http://app.fizzy.localhost:3006/897362094/users/03f5v9zjw7pz8717a4no1h8a7" + } + } + } +] +``` + +## `GET /:account_slug/boards/:board_id/webhooks/:id` + +Returns a single webhook. + +__Response:__ + +Returns the same webhook shape shown above. + +## `POST /:account_slug/boards/:board_id/webhooks` + +Creates a webhook. + +__Request:__ + +```json +{ + "webhook": { + "name": "Production API", + "url": "https://api.example.com/webhooks", + "subscribed_actions": ["card_published", "card_assigned", "card_closed"] + } +} +``` + +`subscribed_actions` accepts any of: +`card_assigned`, `card_closed`, `card_postponed`, `card_auto_postponed`, `card_board_changed`, `card_published`, `card_reopened`, `card_sent_back_to_triage`, `card_triaged`, `card_unassigned`, `comment_created` + +__Response:__ + +``` +HTTP/1.1 201 Created +Location: http://app.fizzy.localhost:3006/897362094/boards/03f5v9zkft4hj9qq0lsn9ohcy/webhooks/03f5v9zkft4hj9qq0lsn9ohcm.json +``` + +Returns the created webhook in the response body. + +## `PATCH /:account_slug/boards/:board_id/webhooks/:id` + +Updates a webhook. + +__Request:__ + +```json +{ + "webhook": { + "name": "Production API", + "subscribed_actions": ["card_closed"] + } +} +``` + +The `url` is immutable after creation and is ignored on update. + +__Response:__ + +Returns the updated webhook. + +## `DELETE /:account_slug/boards/:board_id/webhooks/:id` + +Deletes a webhook. + +__Response:__ + +Returns `204 No Content` on success. + +## `POST /:account_slug/boards/:board_id/webhooks/:id/activation` + +Reactivates a deactivated webhook. + +__Response:__ + +``` +HTTP/1.1 201 Created +``` + +Returns the reactivated webhook in the response body. + +## `GET /:account_slug/boards/:board_id/webhooks/:webhook_id/deliveries` + +Returns a paginated list of deliveries for a webhook. Only account admins can access delivery history. + +__Response:__ + +```json +[ + { + "id": "03f5v9zkft4hj9qq0lsn9ohdn", + "state": "completed", + "created_at": "2025-12-05T19:36:35.534Z", + "updated_at": "2025-12-05T19:36:36.102Z", + "request": { + "headers": { + "User-Agent": "fizzy/1.0.0 Webhook", + "Content-Type": "application/json", + "X-Webhook-Timestamp": "2025-12-05T19:36:35.401Z" + } + }, + "response": { + "code": 200, + "error": null + }, + "event": { + "id": "03f5v9zkft4hj9qq0lsn9ohde", + "action": "card_closed", + "created_at": "2025-12-05T19:36:35.401Z", + "creator": { + "id": "03f5v9zjw7pz8717a4no1h8a7", + "name": "David Heinemeier Hansson" + }, + "eventable": { + "type": "Card", + "id": "03f5v9zkft4hj9qq0lsn9ohdb", + "url": "http://app.fizzy.localhost:3006/897362094/cards/1" + } + } + } +] +``` + +`request` and `response` can be `null` for deliveries that have not started yet or are still in progress. The delivery request headers omit the `X-Webhook-Signature` header. diff --git a/docs/cloudron.md b/docs/cloudron.md index 792745c06e..f56d34387e 100644 --- a/docs/cloudron.md +++ b/docs/cloudron.md @@ -49,7 +49,7 @@ cloudron update --image ghcr.io/patattzel/fizzy-cloudron:stable --app fizzy.your ``` The manual image flow is secondary. The authoritative package metadata remains `CloudronManifest.json` plus `CloudronVersions.json`. -Use `stable` or an explicit package version such as `ghcr.io/patattzel/fizzy-cloudron:1.2.4`. Do not use `latest`. +Use `stable` or an explicit package version such as `ghcr.io/patattzel/fizzy-cloudron:1.2.5`. Do not use `latest`. ## Runtime configuration @@ -59,6 +59,7 @@ Use `stable` or an explicit package version such as `ghcr.io/patattzel/fizzy-clo - The package health check path is `/up`. - `APP_HOST` defaults from `CLOUDRON_APP_DOMAIN`. - `APP_ORIGIN` defaults from `CLOUDRON_APP_ORIGIN`. +- `BASE_URL` defaults from `APP_ORIGIN` so links generated by Rails use the public Cloudron URL. ### Database @@ -70,9 +71,10 @@ Use `stable` or an explicit package version such as `ghcr.io/patattzel/fizzy-clo - `CLOUDRON_MYSQL_USERNAME` -> `MYSQL_USER` - `CLOUDRON_MYSQL_PASSWORD` -> `MYSQL_PASSWORD` -The entrypoint runs: +The entrypoint prepares the primary schema, seeds the secondary Solid Queue/Cache/Cable schemas into Cloudron’s single MySQL database when needed, and then runs: - `bundle exec rails db:prepare` +- `bundle exec rails db:migrate` - `bundle exec rails db:migrate:cable db:migrate:queue db:migrate:cache` ### Mail @@ -86,7 +88,7 @@ Cloudron sendmail values are mapped into Fizzy mail settings: - `CLOUDRON_MAIL_FROM` -> `MAIL_FROM` / `MAILER_FROM_ADDRESS` - `CLOUDRON_MAIL_FROM_DISPLAY_NAME` -> `MAIL_FROM_DISPLAY_NAME` -If SMTP is configured, `config/initializers/cloudron.rb` switches Action Mailer to SMTP automatically. +The entrypoint maps these values to Fizzy’s standard `SMTP_*` variables, so the upstream production configuration enables SMTP automatically. ### Persistent data @@ -104,6 +106,7 @@ Cloudron mounts `/app/data`. The container keeps runtime state there: - `SECRET_KEY_BASE` is generated on first boot if not set. - `VAPID_PUBLIC_KEY` and `VAPID_PRIVATE_KEY` are generated on first boot if not set. - `SOLID_QUEUE_IN_PUMA=1` is enabled by default so background jobs run with Puma. +- `JOB_CONCURRENCY=1` keeps the default Solid Queue process count suitable for a 2 GB Cloudron container; override it for larger installations. ### Signup toggle @@ -113,10 +116,9 @@ To change it later: ```sh echo false > /app/data/allow_signups -cloudron restart --app fizzy.your-cloudron.tld ``` -Set it back to `true` to re-enable public signups. +The change takes effect on the next request. Set it back to `true` to re-enable public signups. ## Maintainer release process @@ -131,7 +133,7 @@ Community package releases are driven by both metadata files. 7. Push to `main` to validate metadata and publish the moving `stable` image. 8. Push a matching Git tag `v` to publish the immutable version tag and refresh `stable`. -The publish automation lives in [`../.github/workflows/publish-image.yml`](../.github/workflows/publish-image.yml). The Rails CI workflows remain unchanged because they still validate the underlying application code. +The publish automation lives in [`../.github/workflows/publish-image.yml`](../.github/workflows/publish-image.yml). The fork’s OSS CI validates the underlying application code; Basecamp’s private SaaS job is intentionally not run here. ## Local development diff --git a/docs/development.md b/docs/development.md index 8fa1e54674..3b7e16e903 100644 --- a/docs/development.md +++ b/docs/development.md @@ -15,7 +15,7 @@ And then run the development server: bin/dev ``` -You'll be able to access the app in development at http://fizzy.localhost:3006. +You'll be able to access the app in development at http://app.fizzy.localhost:3006. To login, enter `david@example.com` and grab the verification code from the browser console to sign in. @@ -62,7 +62,7 @@ The remote CI pipeline will run tests against both SQLite and MySQL. ### Outbound Emails -You can view email previews at http://fizzy.localhost:3006/rails/mailers. +You can view email previews at http://app.fizzy.localhost:3006/rails/mailers. You can enable or disable [`letter_opener`](https://github.com/ryanb/letter_opener) to open sent emails automatically with: diff --git a/docs/docker-deployment.md b/docs/docker-deployment.md index c74efe2915..219bcab1da 100644 --- a/docs/docker-deployment.md +++ b/docs/docker-deployment.md @@ -143,6 +143,9 @@ If you're using a provider other than AWS, you will also need some of the follow - `S3_REQUEST_CHECKSUM_CALCULATION` - `S3_RESPONSE_CHECKSUM_VALIDATION` +If your storage provider is on a different site than your Fizzy instance and doesn't return CORS headers on presigned URL responses, inline images may fail to load. +In that case, set `SERVICE_WORKER_CORS_ENABLED=false` so the service worker fetches uploaded files without CORS mode. + #### Multi-tenant mode By default, when you run the Fizzy Docker image you'll be limited to creating a single account (although that account can have as many users as you like). diff --git a/lib/rails_ext/active_record_optimizer_hints.rb b/lib/rails_ext/active_record_optimizer_hints.rb new file mode 100644 index 0000000000..8b79a44a8f --- /dev/null +++ b/lib/rails_ext/active_record_optimizer_hints.rb @@ -0,0 +1,86 @@ +# frozen_string_literal: true + +# Query optimizer hints for ActiveRecord +# +# Provides methods to pass optimizer hints to the database query planner. +# Uses MySQL 8 optimizer hint query comments. Other databases (MariaDB, SQLite, etc.) +# ignore these comments, making this a safe no-op across all databases. +# +# Documentation: +# * https://dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html +# +# Examples: +# Card.use_index(:index_cards_on_account_id_and_board_id_and_status).where(...) +# Event.joins(:recording).join_prefix(:events) + +module ActiveRecordBaseOptimizerHintExtensions + # Pass index hints to the query optimizer + # + # @param indexes [Array] Index names to use + # @return [ActiveRecord::Relation] + # @example + # Card.use_index(:index_cards_on_account_id_and_board_id_and_status).where(...) + def use_index(*indexes) + all.use_index(*indexes) + end + + # Override the default join order + # + # @param table [String, Symbol] Table name to join first + # @return [ActiveRecord::Relation] + # @example + # Event.joins(:recording).join_prefix(:events) + def join_prefix(table) + all.join_prefix(table) + end +end + +module ActiveRecordRelationOptimizerHintExtensions + # Pass index hints to the query optimizer using SQL comment hints. + # Uses MySQL 8 optimizer hint query comments. Other databases (MariaDB, SQLite, etc.) + # ignore these comments, making this a safe no-op across all databases. + # + # Documentation: + # * https://dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html + # + # Example: + # Card.use_index(:index_cards_on_account_id_and_board_id_and_status) + # + # => Card Load (0.5ms) SELECT /*+ INDEX(`cards` index_cards_on_account_id_and_board_id_and_status) */ `cards`.* + # FROM `cards` WHERE ... + # + # Multiple indexes: + # Card.use_index(:index_a, :index_b) + # + # => Card Load (0.5ms) SELECT /*+ INDEX(`cards` index_a, index_b) */ `cards`.* FROM `cards` + # + # Calling use_index again replaces a previously hinted index for the same table, so the most + # specific scope wins. MySQL only honors the first INDEX hint per table and silently ignores + # the rest, so appending a second hint would have no effect: + # Card.use_index(:index_a).use_index(:index_b) + # + # => Card Load (0.5ms) SELECT /*+ INDEX(`cards` index_b) */ `cards`.* FROM `cards` + def use_index(*indexes) + kept_hints = optimizer_hints_values.reject { |hint| hint.to_s.start_with?("INDEX(#{quoted_table_name} ") } + except(:optimizer_hints).optimizer_hints(*kept_hints, "INDEX(#{quoted_table_name} #{indexes.join(', ')})") + end + + # Optimizer hint to override the default join order. + # Uses MySQL 8 optimizer hints. Other databases ignore these hints. + # + # Documentation: + # https://dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html#optimizer-hints-join-order + # + # Example: + # Event.joins(:recording).join_prefix(:events) + # + # => Event Load (0.9ms) SELECT /*+ JOIN_PREFIX(`events`) */ `events`.* FROM `events` + # INNER JOIN `recordings` ON `recordings`.`id` = `events`.`recording_id` + # + def join_prefix(table) + optimizer_hints "JOIN_PREFIX(#{connection.quote_table_name(table)})" + end +end + +ActiveRecord::Base.singleton_class.prepend(ActiveRecordBaseOptimizerHintExtensions) +ActiveRecord::Relation.prepend(ActiveRecordRelationOptimizerHintExtensions) diff --git a/lib/rails_ext/active_storage_authorization.rb b/lib/rails_ext/active_storage_authorization.rb index 7d6fa8510b..0e13407666 100644 --- a/lib/rails_ext/active_storage_authorization.rb +++ b/lib/rails_ext/active_storage_authorization.rb @@ -31,6 +31,10 @@ module ActiveStorage::Authorize end private + def bearer_token_authenticatable_request? + true + end + def publicly_accessible_blob? @blob.publicly_accessible? end @@ -41,8 +45,8 @@ def ensure_accessible end end - def http_cache_forever(public: false, &block) - super(public: public && publicly_accessible_blob?, &block) + def http_cache_forever(public: false, **options, &block) + super(public: public && publicly_accessible_blob?, **options, &block) end end diff --git a/mise.saas.toml b/mise.saas.toml new file mode 100644 index 0000000000..ba089d07ac --- /dev/null +++ b/mise.saas.toml @@ -0,0 +1,10 @@ +# SaaS-only mise overlay, loaded when MISE_ENV=saas (mise environment +# configs: mise.saas.toml loads above .mise.toml in the same directory). +# +# Private Basecamp infrastructure is declared ONLY here — the OSS root +# .mise.toml must never reference it. Consumed by saas/bin/setup, which runs +# the repos phase under MISE_ENV=saas after proving https git auth. +min_version = "2026.7.5" + +[bootstrap.repos] +"~/Work/basecamp/docker-dev" = { url = "https://github.com/basecamp/docker-dev.git", ref = "master" } diff --git a/saas/Dockerfile b/saas/Dockerfile index 92fd9c4ec6..9353046d92 100644 --- a/saas/Dockerfile +++ b/saas/Dockerfile @@ -1,5 +1,5 @@ # Make sure RUBY_VERSION matches the Ruby version in .ruby-version -ARG RUBY_VERSION=3.4.7 +ARG RUBY_VERSION=3.4.8 FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim AS base # Rails app lives here diff --git a/saas/README.md b/saas/README.md index bec3b279f2..28b0891e2d 100644 --- a/saas/README.md +++ b/saas/README.md @@ -74,14 +74,11 @@ This environment uses a FlashBlade bucket for blob storage. Beta is primarily intended for testing product features. It uses the same production database and Active Storage configuration. -There are 4 beta environments: +There is 1 beta environment: - https://beta1.fizzy-beta.com -- https://beta2.fizzy-beta.com -- https://beta3.fizzy-beta.com -- https://beta4.fizzy-beta.com -Deploy with: `bin/kamal deploy -d beta1` (or `-d beta2`, `-d beta3`, `-d beta4`) +Deploy with: `bin/kamal deploy -d beta1` ### Staging @@ -89,6 +86,22 @@ Staging is primarily intended for testing infrastructure changes. It uses produc - https://app.fizzy-staging.com/ +## Maintenance mode + +To take production offline for maintenance, run `kamal-proxy stop` on the load balancers via `knife ssh`: + +```bash +knife ssh 'hostname:fizzy-lb-*' "sudo docker exec fizzy-load-balancer kamal-proxy stop fizzy --message='Sorry! Fizzy is undergoing some maintenance and will be back shortly.'" +``` + +Verify maintenance is enabled by visiting https://app.fizzy.do/. + +To lift maintenance mode: + +```bash +knife ssh 'hostname:fizzy-lb-*' 'sudo docker exec fizzy-load-balancer kamal-proxy resume fizzy' +``` + ## License fizzy-saas is released under the [O'Saasy License](LICENSE.md). diff --git a/saas/bin/setup b/saas/bin/setup index bdebb3a1ad..b29247d516 100755 --- a/saas/bin/setup +++ b/saas/bin/setup @@ -4,9 +4,46 @@ set -eo pipefail # SaaS-specific setup tasks # This script is called from the main Fizzy bin/setup when SAAS is enabled +# docker-dev is declared in mise.saas.toml — the SaaS-only overlay, loaded via +# MISE_ENV=saas — and converged declaratively through mise's repos phase. The +# OSS root .mise.toml never references it; OSS setups never reach this file. +step "Trusting SaaS mise overlay" mise trust --yes "$app_root/mise.saas.toml" + +# shipyard-block: docker-dev-origin v1 +# mise syncs docker-dev from the declared https URL: its repos preflight doesn't +# equate ssh with https origins, and fresh clones use the URL as-is. docker-dev is +# private and gh being installed does not imply its git credential helper is +# configured (gh auth setup-git is a separate step), so prove https auth with a +# noninteractive probe wherever mise is about to need it: before a fresh clone, and +# before rewriting the canonical ssh origin of an existing checkout. On failure, +# stop with guidance and leave any working ssh remote untouched. Forks, mirrors, +# and dirty checkouts are left for mise to flag. +docker_dev="$HOME/Work/basecamp/docker-dev" +docker_dev_url="https://github.com/basecamp/docker-dev.git" +docker_dev_https_ok() { + GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=true git ls-remote "$docker_dev_url" HEAD > /dev/null 2>&1 +} +docker_dev_auth_required() { + echo "docker-dev syncs from $docker_dev_url, but https git auth isn't set up." >&2 + echo "Run: gh auth setup-git — then rerun bin/setup." >&2 + exit 1 +} +if [ ! -e "$docker_dev/.git" ]; then + docker_dev_https_ok || docker_dev_auth_required +else + case "$(git -C "$docker_dev" config --get remote.origin.url || true)" in + git@github.com:basecamp/docker-dev|git@github.com:basecamp/docker-dev.git|ssh://git@github.com/basecamp/docker-dev|ssh://git@github.com/basecamp/docker-dev.git) + docker_dev_https_ok || docker_dev_auth_required + git -C "$docker_dev" remote set-url origin "$docker_dev_url";; + esac +fi +# shipyard-block-end: docker-dev-origin + +step "Syncing docker-dev" env MISE_ENV=saas mise bootstrap --only repos --yes + if [ -e tmp/minio-dev.txt ]; then - step "Starting Docker services" bash -c "[ -d ~/Work/basecamp/docker-dev ] && git -C ~/Work/basecamp/docker-dev pull || gh repo clone basecamp/docker-dev ~/Work/basecamp/docker-dev && ~/Work/basecamp/docker-dev/setup minio" + step "Starting Docker services" ~/Work/basecamp/docker-dev/setup minio step "Configuring MinIO" bin/minio-setup fi -step "Starting mysql" bash -c "[ -d ~/Work/basecamp/docker-dev ] && git -C ~/Work/basecamp/docker-dev pull || gh repo clone basecamp/docker-dev ~/Work/basecamp/docker-dev && ~/Work/basecamp/docker-dev/setup mysql80" +step "Starting mysql" ~/Work/basecamp/docker-dev/setup mysql80 diff --git a/saas/config/deploy.beta.yml b/saas/config/deploy.beta.yml index b3a39bda68..7e60f41a40 100644 --- a/saas/config/deploy.beta.yml +++ b/saas/config/deploy.beta.yml @@ -10,36 +10,6 @@ "dbs" => { "solidqueue" => "fizzy-beta-solidqueue-db-101.df-iad-int.37signals.com" } - }, - "2" => { - "hosts" => { - "web" => ["fizzy-beta-app-102.df-iad-int.37signals.com"], - "jobs" => ["fizzy-beta-jobs-102.df-iad-int.37signals.com"], - "lb" => "fizzy-beta-lb-102.df-iad-int.37signals.com" - }, - "dbs" => { - "solidqueue" => "fizzy-beta-solidqueue-db-102.df-iad-int.37signals.com" - } - }, - "3" => { - "hosts" => { - "web" => ["fizzy-beta-app-103.df-iad-int.37signals.com"], - "jobs" => ["fizzy-beta-jobs-103.df-iad-int.37signals.com"], - "lb" => "fizzy-beta-lb-103.df-iad-int.37signals.com" - }, - "dbs" => { - "solidqueue" => "fizzy-beta-solidqueue-db-103.df-iad-int.37signals.com" - } - }, - "4" => { - "hosts" => { - "web" => ["fizzy-beta-app-104.df-iad-int.37signals.com"], - "jobs" => ["fizzy-beta-jobs-104.df-iad-int.37signals.com"], - "lb" => "fizzy-beta-lb-104.df-iad-int.37signals.com" - }, - "dbs" => { - "solidqueue" => "fizzy-beta-solidqueue-db-104.df-iad-int.37signals.com" - } } } @beta_number = ENV["BETA_NUMBER"] diff --git a/saas/config/deploy.beta2.yml b/saas/config/deploy.beta2.yml deleted file mode 100644 index 97d348be63..0000000000 --- a/saas/config/deploy.beta2.yml +++ /dev/null @@ -1,2 +0,0 @@ -<% ENV["BETA_NUMBER"] = "2" %> -<%= ERB.new(File.read(File.join(Gem::Specification.find_by_name("fizzy-saas").gem_dir, "config", "deploy.beta.yml")), trim_mode: 2).result %> diff --git a/saas/config/deploy.beta3.yml b/saas/config/deploy.beta3.yml deleted file mode 100644 index fc20f4c027..0000000000 --- a/saas/config/deploy.beta3.yml +++ /dev/null @@ -1,2 +0,0 @@ -<% ENV["BETA_NUMBER"] = "3" %> -<%= ERB.new(File.read(File.join(Gem::Specification.find_by_name("fizzy-saas").gem_dir, "config", "deploy.beta.yml")), trim_mode: 2).result %> diff --git a/saas/config/deploy.beta4.yml b/saas/config/deploy.beta4.yml deleted file mode 100644 index 966c17fd4e..0000000000 --- a/saas/config/deploy.beta4.yml +++ /dev/null @@ -1,2 +0,0 @@ -<% ENV["BETA_NUMBER"] = "4" %> -<%= ERB.new(File.read(File.join(Gem::Specification.find_by_name("fizzy-saas").gem_dir, "config", "deploy.beta.yml")), trim_mode: 2).result %> diff --git a/saas/config/deploy.production.yml b/saas/config/deploy.production.yml index b666c8fc0c..d1dd705b0a 100644 --- a/saas/config/deploy.production.yml +++ b/saas/config/deploy.production.yml @@ -9,6 +9,8 @@ servers: - fizzy-app-102.df-iad-int.37signals.com: df_iad - fizzy-app-401.df-ams-int.37signals.com: df_ams - fizzy-app-402.df-ams-int.37signals.com: df_ams + - fizzy-app-501.sjc-int.37signals.com: sjc + - fizzy-app-502.sjc-int.37signals.com: sjc labels: otel_scrape_enabled: true jobs: @@ -67,7 +69,8 @@ env: PRIMARY_DATACENTER: true df_ams: MYSQL_SOLID_CACHE_HOST: fizzy-solidcache-db-401.df-ams-int.37signals.com - + sjc: + MYSQL_SOLID_CACHE_HOST: fizzy-solidcache-db-501.sjc-int.37signals.com accessories: load-balancer: @@ -79,6 +82,8 @@ accessories: - fizzy-lb-02.sc-chi-int.37signals.com - fizzy-lb-401.df-ams-int.37signals.com - fizzy-lb-402.df-ams-int.37signals.com + - fizzy-lb-501.sjc-int.37signals.com + - fizzy-lb-502.sjc-int.37signals.com labels: otel_role: load-balancer otel_service: fizzy-load-balancer diff --git a/saas/config/deploy.staging.yml b/saas/config/deploy.staging.yml index cc03e6b9d5..b45fabcdd1 100644 --- a/saas/config/deploy.staging.yml +++ b/saas/config/deploy.staging.yml @@ -9,6 +9,8 @@ servers: - fizzy-staging-app-02.sc-chi-int.37signals.com: sc_chi - fizzy-staging-app-401.df-ams-int.37signals.com: df_ams - fizzy-staging-app-402.df-ams-int.37signals.com: df_ams + - fizzy-staging-app-501.sjc-int.37signals.com: sjc + - fizzy-staging-app-502.sjc-int.37signals.com: sjc labels: otel_scrape_enabled: true jobs: @@ -64,7 +66,8 @@ env: PRIMARY_DATACENTER: true df_ams: MYSQL_SOLID_CACHE_HOST: fizzy-staging-solidcache-db-401.df-ams-int.37signals.com - + sjc: + MYSQL_SOLID_CACHE_HOST: fizzy-staging-solidcache-db-501.sjc-int.37signals.com accessories: load-balancer: @@ -73,6 +76,7 @@ accessories: - fizzy-staging-lb-01.sc-chi-int.37signals.com - fizzy-staging-lb-101.df-iad-int.37signals.com - fizzy-staging-lb-401.df-ams-int.37signals.com + - fizzy-staging-lb-501.sjc-int.37signals.com labels: otel_role: load-balancer otel_service: fizzy-load-balancer diff --git a/saas/config/storage.yml b/saas/config/storage.yml index a149ccf7b3..3825e95bea 100644 --- a/saas/config/storage.yml +++ b/saas/config/storage.yml @@ -9,7 +9,7 @@ local: devminio: service: S3 bucket: fizzy-dev-activestorage - endpoint: "http://minio.localhost:39000" + endpoint: "http://minio.fizzy.localhost:39000" force_path_style: true request_checksum_calculation: when_required # default is when_supported with CRC64NVME checksum which FlashBlade doesn't support response_checksum_validation: when_required # default is when_supported with CRC64NVME checksum which FlashBlade doesn't support diff --git a/saas/lib/fizzy/saas/engine.rb b/saas/lib/fizzy/saas/engine.rb index 1b967b1d5d..3074e7e546 100644 --- a/saas/lib/fizzy/saas/engine.rb +++ b/saas/lib/fizzy/saas/engine.rb @@ -90,6 +90,34 @@ class Engine < ::Rails::Engine end end + # Rails edge (actioncable 647ce6769c, 2026-05-28) extracted WebSocket handling + # into ActionCable::Server::Socket, which now calls connection.handle_open / + # handle_close *publicly*. sentry-rails (through 6.6.2 and master as of 2026-07) + # still prepends these onto ActionCable::Connection::Base as `private`, matching + # the old internal calling convention, so the external call raises NoMethodError + # and every WebSocket connection dies. Restore public visibility on Sentry's + # module until sentry-ruby adapts to the refactor. + # + # sentry-rails prepends its module via on_load(:action_cable_connection), which + # fires lazily when ActionCable::Connection::Base first loads. Register our own + # hook so it runs right after Sentry's (on_load callbacks fire in registration + # order); doing it from after_initialize guarantees ours queues after Sentry's. + # Remove once https://github.com/getsentry/sentry-ruby ships a compatible release. + config.after_initialize do + ActiveSupport.on_load(:action_cable_connection) do + if defined?(Sentry::Rails::ActionCableExtensions::Connection) + Sentry::Rails::ActionCableExtensions::Connection.class_eval do + # Guard per method: a future sentry-rails may rename/remove one, and calling + # `public` on an undefined method raises NameError — which would break SaaS + # boot here. Only flip the visibility of methods that actually exist. + %i[ handle_open handle_close ].each do |method| + public method if method_defined?(method) || private_method_defined?(method) + end + end + end + end + end + initializer "fizzy_saas.yabeda" do require "prometheus/client/support/puma" @@ -112,6 +140,12 @@ class Engine < ::Rails::Engine require "yabeda/gvl" Yabeda::GVL.install! + require "yabeda/active_support_cache" + Yabeda::ActiveSupportCache.install! + + require "yabeda/solid_cache" + Yabeda::SolidCache.install! + require_relative "metrics" end diff --git a/saas/lib/yabeda/active_support_cache.rb b/saas/lib/yabeda/active_support_cache.rb new file mode 100644 index 0000000000..f19e4ed7f7 --- /dev/null +++ b/saas/lib/yabeda/active_support_cache.rb @@ -0,0 +1,44 @@ +module Yabeda + module ActiveSupportCache + def self.install! + Yabeda.configure do + tag_names = %i[ store operation ] + + group :active_support + + counter :cache_requests_total, comment: "Active Support cache requests", tags: tag_names + counter :cache_hits_total, comment: "Active Support cache hits", tags: tag_names + counter :cache_operations_total, comment: "Count of Active Support cache operations", tags: tag_names + counter :cache_operations_seconds_total, comment: "Seconds spent on Active Support cache operations", tags: tag_names + + ActiveSupport::Notifications.monotonic_subscribe /cache_[a-z_]+\.active_support/ do |name, start, finish, id, payload| + store = payload[:store] + next if store == "ActiveSupport::Cache::FileStore" # sprockets + + operation = name.match(/^cache_([^.]*)/)[1] + tags = { store: store, operation: operation } + requests, hits = ActiveSupportCache.requests_and_hits(operation, payload) + + next if operation == "read_multi" && requests == 0 # no-op + + active_support_cache_requests_total.increment(tags, by: requests) if requests > 0 + active_support_cache_hits_total.increment(tags, by: hits) if hits > 0 + active_support_cache_operations_total.increment(tags) + active_support_cache_operations_seconds_total.increment(tags, by: finish - start) + end + end + end + + private + def self.requests_and_hits(operation, payload) + case operation + when "read" + [ 1, payload[:hit] ? 1 : 0 ] + when "read_multi" + [ payload[:key]&.count || 0, payload[:hits]&.count || 0 ] + else + [ 0, 0 ] + end + end + end +end diff --git a/saas/lib/yabeda/solid_cache.rb b/saas/lib/yabeda/solid_cache.rb new file mode 100644 index 0000000000..c6e7322265 --- /dev/null +++ b/saas/lib/yabeda/solid_cache.rb @@ -0,0 +1,116 @@ +module Yabeda + module SolidCache + SECONDS_PER_DAY = 86_400 + DEFAULT_METRIC_VALUE = 0 + + def self.install! + Yabeda.configure do + group :fizzy + + gauge :solid_cache_max_age_seconds, comment: "Solid Cache max age in seconds", tags: %i[ shard ], aggregation: :most_recent + gauge :solid_cache_oldest_age_seconds, comment: "Solid Cache oldest entry age in seconds", tags: %i[ shard ], aggregation: :most_recent + gauge :solid_cache_max_entries, comment: "Solid Cache max entries", tags: %i[ shard ], aggregation: :most_recent + gauge :solid_cache_entries_total, comment: "Solid Cache entries", tags: %i[ shard ], aggregation: :most_recent + + collect do + Yabeda::SolidCache.collect_stats if defined?(::SolidCache::Entry) + end + end + end + + def self.collect_stats + return unless ::Rails.cache.is_a?(::SolidCache::Store) + + enrichment = enrichment_from_cache_stats + ages = oldest_ages_per_shard + + (enrichment.keys + ages.keys).uniq.each do |shard| + set_shard_metrics(shard, enrichment[shard], ages[shard]) + end + rescue => error + ::Rails.logger.warn "Failed to collect Solid Cache stats: #{error.message}" + end + + private + # Active shards contribute enrichment data via ::Rails.cache.stats; every shard + # (including inactive ones) contributes an oldest-entry age via each_shard. We + # set whatever metrics we have for each shard we find in either source. + def self.set_shard_metrics(shard, enrichment, age_days) + if enrichment && age_days + set_metrics shard, + max_age: enrichment[:max_age], + oldest_age: (age_days * SECONDS_PER_DAY).to_i, + entries: enrichment[:entries], + max_entries: enrichment[:max_entries] + elsif enrichment + set_metrics shard, + max_age: enrichment[:max_age], + oldest_age: enrichment[:oldest_age], + entries: enrichment[:entries], + max_entries: enrichment[:max_entries] + elsif age_days + oldest_age = (age_days * SECONDS_PER_DAY).to_i + set_metrics shard, + max_age: oldest_age, + oldest_age: oldest_age, + entries: DEFAULT_METRIC_VALUE, + max_entries: DEFAULT_METRIC_VALUE + end + rescue => error + ::Rails.logger.warn "Failed to collect Solid Cache stats for shard #{shard}: #{error.message}" + end + + def self.set_metrics(shard, max_age:, oldest_age:, entries:, max_entries:) + tags = { shard: shard } + Yabeda.fizzy.solid_cache_max_age_seconds.set(tags, max_age) + Yabeda.fizzy.solid_cache_oldest_age_seconds.set(tags, oldest_age) + Yabeda.fizzy.solid_cache_entries_total.set(tags, entries) + Yabeda.fizzy.solid_cache_max_entries.set(tags, max_entries) + end + + def self.enrichment_from_cache_stats + connection_stats = ::Rails.cache.stats&.dig(:connection_stats) + return {} unless connection_stats + + connection_stats.each_with_object({}) do |(shard, stats), enrichment| + enrichment[shard.to_s] = normalize_shard_stats(stats) if stats + end + rescue => error + ::Rails.logger.warn "Failed to read Solid Cache stats: #{error.message}" + {} + end + + def self.oldest_ages_per_shard + return {} unless ::SolidCache::Record.respond_to?(:each_shard) + + {}.tap do |ages| + ::SolidCache::Record.each_shard do + shard = ::SolidCache::Record.connection_db_config.name + if age_days = oldest_entry_age_in_days + ages[shard] = age_days + end + rescue => error + ::Rails.logger.warn "Failed to read Solid Cache age for a shard: #{error.message}" + end + end + rescue => error + ::Rails.logger.warn "Failed to read Solid Cache shard ages: #{error.message}" + {} + end + + def self.oldest_entry_age_in_days + if oldest_entry = ::SolidCache::Entry.order(:id).first + (Time.current - oldest_entry.created_at) / SECONDS_PER_DAY + end + end + + def self.normalize_shard_stats(stats) + { + max_age: stats[:max_age]&.to_i || DEFAULT_METRIC_VALUE, + oldest_age: stats[:oldest_age]&.to_i || DEFAULT_METRIC_VALUE, + max_entries: stats[:max_entries]&.to_i || DEFAULT_METRIC_VALUE, + entries: stats[:entries]&.to_i || DEFAULT_METRIC_VALUE + } + end + end +end diff --git a/saas/script/configure-lb-beta.sh b/saas/script/configure-lb-beta.sh index 89895c67d5..1857e05580 100755 --- a/saas/script/configure-lb-beta.sh +++ b/saas/script/configure-lb-beta.sh @@ -10,30 +10,3 @@ ssh app@fizzy-beta-lb-101.df-iad-int.37signals.com \ --tls \ --host=beta1.fizzy-beta.com \ --target=fizzy-beta-app-101.df-iad-int.37signals.com - -# Beta 2: fizzy-beta-lb-102 -> fizzy-beta-app-102 -ssh app@fizzy-beta-lb-102.df-iad-int.37signals.com \ - docker exec fizzy-load-balancer \ - kamal-proxy deploy fizzy \ - --force \ - --tls \ - --host=beta2.fizzy-beta.com \ - --target=fizzy-beta-app-102.df-iad-int.37signals.com - -# Beta 3: fizzy-beta-lb-103 -> fizzy-beta-app-103 -ssh app@fizzy-beta-lb-103.df-iad-int.37signals.com \ - docker exec fizzy-load-balancer \ - kamal-proxy deploy fizzy \ - --force \ - --tls \ - --host=beta3.fizzy-beta.com \ - --target=fizzy-beta-app-103.df-iad-int.37signals.com - -# Beta 4: fizzy-beta-lb-104 -> fizzy-beta-app-104 -ssh app@fizzy-beta-lb-104.df-iad-int.37signals.com \ - docker exec fizzy-load-balancer \ - kamal-proxy deploy fizzy \ - --force \ - --tls \ - --host=beta4.fizzy-beta.com \ - --target=fizzy-beta-app-104.df-iad-int.37signals.com diff --git a/saas/script/configure-lb-production.sh b/saas/script/configure-lb-production.sh index a3e914d3f2..94a8a16297 100755 --- a/saas/script/configure-lb-production.sh +++ b/saas/script/configure-lb-production.sh @@ -92,3 +92,34 @@ ssh app@fizzy-lb-402.df-ams-int.37signals.com \ --target=fizzy-app-102.df-iad-int.37signals.com \ --read-target=fizzy-app-401.df-ams-int.37signals.com \ --read-target=fizzy-app-402.df-ams-int.37signals.com + +# fizzy-lb-501.sjc-int.37signals.com +# +ssh app@fizzy-lb-501.sjc-int.37signals.com \ + docker exec fizzy-load-balancer \ + kamal-proxy deploy fizzy \ + --force \ + --tls \ + --host=app.fizzy.do \ + --writer-affinity-timeout=0 \ + --tls-acme-cache-path=/certificates \ + --target=fizzy-app-101.df-iad-int.37signals.com \ + --target=fizzy-app-102.df-iad-int.37signals.com \ + --read-target=fizzy-app-501.sjc-int.37signals.com \ + --read-target=fizzy-app-502.sjc-int.37signals.com + + +# fizzy-lb-502.sjc-int.37signals.com +# +ssh app@fizzy-lb-502.sjc-int.37signals.com \ + docker exec fizzy-load-balancer \ + kamal-proxy deploy fizzy \ + --force \ + --tls \ + --host=app.fizzy.do \ + --writer-affinity-timeout=0 \ + --tls-acme-cache-path=/certificates \ + --target=fizzy-app-101.df-iad-int.37signals.com \ + --target=fizzy-app-102.df-iad-int.37signals.com \ + --read-target=fizzy-app-501.sjc-int.37signals.com \ + --read-target=fizzy-app-502.sjc-int.37signals.com diff --git a/saas/script/configure-lb-staging.sh b/saas/script/configure-lb-staging.sh index 770014403c..7093291237 100755 --- a/saas/script/configure-lb-staging.sh +++ b/saas/script/configure-lb-staging.sh @@ -43,5 +43,19 @@ ssh app@fizzy-staging-lb-401.df-ams-int.37signals.com \ --target=fizzy-staging-app-101.df-iad-int.37signals.com \ --target=fizzy-staging-app-102.df-iad-int.37signals.com \ --read-target=fizzy-staging-app-401.df-ams-int.37signals.com \ - --read-target=fizzy-staging-app-402.df-ams-int.37signals.com + --read-target=fizzy-staging-app-402.df-ams-int.37signals.com +# fizzy-staging-lb-501.sjc-int.37signals.com +# +ssh app@fizzy-staging-lb-501.sjc-int.37signals.com \ + docker exec fizzy-load-balancer \ + kamal-proxy deploy fizzy \ + --force \ + --tls \ + --host=app.fizzy-staging.com \ + --writer-affinity-timeout=0 \ + --tls-acme-cache-path=/certificates \ + --target=fizzy-staging-app-101.df-iad-int.37signals.com \ + --target=fizzy-staging-app-102.df-iad-int.37signals.com \ + --read-target=fizzy-staging-app-501.sjc-int.37signals.com \ + --read-target=fizzy-staging-app-502.sjc-int.37signals.com diff --git a/saas/test/lib/yabeda/active_support_cache_test.rb b/saas/test/lib/yabeda/active_support_cache_test.rb new file mode 100644 index 0000000000..242ad9ea46 --- /dev/null +++ b/saas/test/lib/yabeda/active_support_cache_test.rb @@ -0,0 +1,54 @@ +require "test_helper" +require "yabeda/testing" + +class Yabeda::ActiveSupportCacheTest < ActiveSupport::TestCase + setup do + Yabeda::TestAdapter.instance.reset! + end + + test "counts operations" do + with_caching_enabled do + Rails.cache.write("entry1", 1) + + assert_equal 1, count(:cache_operations_total, operation: "write") + assert_operator count(:cache_operations_seconds_total, operation: "write"), :>, 0 + end + end + + test "counts hits from read" do + with_caching_enabled do + Rails.cache.write("entry1", 1) + Rails.cache.read("entry1") + Rails.cache.read("entry2") + Rails.cache.read("entry3") + + assert_equal 1, count(:cache_hits_total, operation: "read") + assert_equal 3, count(:cache_requests_total, operation: "read") + end + end + + test "counts hits from read_multi" do + with_caching_enabled do + Rails.cache.write("entry1", 1) + Rails.cache.write("entry3", 3) + Rails.cache.read_multi("entry1", "entry2", "entry3") + + assert_equal 2, count(:cache_hits_total, operation: "read_multi") + assert_equal 3, count(:cache_requests_total, operation: "read_multi") + end + end + + private + def with_caching_enabled + old_cache = Rails.cache + Rails.cache = ActiveSupport::Cache.lookup_store(:memory_store) + yield + ensure + Rails.cache = old_cache + end + + def count(metric, operation:) + tags = { store: "ActiveSupport::Cache::MemoryStore", operation: operation } + Yabeda::TestAdapter.instance.counters.fetch(Yabeda.active_support.public_send(metric))[tags] + end +end diff --git a/saas/test/lib/yabeda/solid_cache_test.rb b/saas/test/lib/yabeda/solid_cache_test.rb new file mode 100644 index 0000000000..bf1778f2c6 --- /dev/null +++ b/saas/test/lib/yabeda/solid_cache_test.rb @@ -0,0 +1,56 @@ +require "test_helper" +require "yabeda/testing" + +class Yabeda::SolidCacheTest < ActiveSupport::TestCase + setup do + Yabeda::TestAdapter.instance.reset! + end + + test "sets gauges from cache stats and shard ages" do + freeze_time do + stub_solid_cache \ + connection_stats: { cache: { max_age: 100, oldest_age: 200, max_entries: 50, entries: 10 } }, + oldest_entry_created_at: 3.days.ago + + Yabeda::SolidCache.collect_stats + + assert_equal 100, gauge(:solid_cache_max_age_seconds) + assert_equal 3.days.to_i, gauge(:solid_cache_oldest_age_seconds) + assert_equal 10, gauge(:solid_cache_entries_total) + assert_equal 50, gauge(:solid_cache_max_entries) + end + end + + test "is a no-op when not using the Solid Cache store" do + Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new) + + Yabeda::SolidCache.collect_stats + + assert_nil gauge(:solid_cache_max_age_seconds) + end + + test "swallows stats errors so a scrape never fails" do + store = ::SolidCache::Store.allocate + store.stubs(:stats).raises(StandardError.new("boom")) + Rails.stubs(:cache).returns(store) + ::SolidCache::Record.stubs(:each_shard) + + assert_nothing_raised { Yabeda::SolidCache.collect_stats } + assert_nil gauge(:solid_cache_max_age_seconds) + end + + private + def stub_solid_cache(connection_stats:, oldest_entry_created_at:) + store = ::SolidCache::Store.allocate + store.stubs(:stats).returns(connection_stats: connection_stats) + Rails.stubs(:cache).returns(store) + + ::SolidCache::Record.stubs(:each_shard).yields + ::SolidCache::Record.stubs(:connection_db_config).returns(stub(name: "cache")) + ::SolidCache::Entry.stubs(:order).returns(stub(first: stub(created_at: oldest_entry_created_at))) + end + + def gauge(metric, shard: "cache") + Yabeda::TestAdapter.instance.gauges[Yabeda.fizzy.public_send(metric)][{ shard: shard }] + end +end diff --git a/script/import-account b/script/import-account new file mode 100755 index 0000000000..bde4f07e52 --- /dev/null +++ b/script/import-account @@ -0,0 +1,76 @@ +#!/usr/bin/env ruby + +# Imports a Fizzy account export into this instance. +# +# Usage: +# script/import-account +# +# Example: +# script/import-account ./storage/export.zip owner@example.com +# +# A new account is created and owned by the given email address, then the +# export is loaded into it. The export file itself is left untouched. + +require "uri" + +zip_path, email_address = ARGV + +if zip_path.nil? || email_address.nil? + abort <<~USAGE + Usage: script/import-account + + Example: + script/import-account ./storage/export.zip owner@example.com + USAGE +end + +abort "❌ Export file not found: #{zip_path}" unless File.file?(zip_path) +abort "❌ That doesn't look like an email address: #{email_address}" unless email_address.match?(URI::MailTo::EMAIL_REGEXP) + +puts "Loading Fizzy..." +require_relative "../lib/fizzy" +Fizzy.configure_bundle +require_relative "../config/environment" + +identity = Identity.find_or_create_by!(email_address: email_address) +signup = Signup.new(identity: identity, full_name: "Import", skip_account_seeding: true) + +abort "❌ Couldn't create an account for the import: #{signup.errors.full_messages.to_sentence}" unless signup.complete + +account = signup.account + +Current.set(account: account, identity: identity) do + import = account.imports.create!(identity: identity, file: File.open(zip_path)) + + last_announced = nil + progress = ->(record_set:, **) do + if record_set.model.name != last_announced + last_announced = record_set.model.name + puts " #{record_set.model.name.demodulize.titleize.pluralize}..." + end + end + + begin + puts "Checking the export file (nothing is imported yet)..." + import.check callback: progress + + last_announced = nil + puts "Importing..." + import.process callback: progress + rescue Account::DataTransfer::RecordSet::ConflictError + abort "❌ Import failed: the export conflicts with data that already exists in this instance." + rescue Account::DataTransfer::RecordSet::IntegrityError, ZipFile::InvalidFileError + abort "❌ Import failed: the file doesn't look like a valid Fizzy export." + rescue => error + abort "❌ Import failed: #{error.message}" + end + + puts + puts "✅ Done! The account “#{account.name}” was imported." + + begin + puts " #{email_address} can now sign in at #{Rails.application.routes.url_helpers.root_url(script_name: account.slug)}" + rescue ArgumentError + puts " #{email_address} can now sign in to the account at #{account.slug}" + end +end diff --git a/script/import-sqlite-database.rb b/script/import-sqlite-database.rb index 4a76685264..545cd2d74a 100755 --- a/script/import-sqlite-database.rb +++ b/script/import-sqlite-database.rb @@ -49,7 +49,7 @@ def import_database ActiveStorage::Attachment.skip_callback(:commit, :after, :mirror_blob_later) ActiveStorage::Attachment.skip_callback(:commit, :after, :analyze_blob_later) ActiveStorage::Attachment.skip_callback(:commit, :after, :transform_variants_later) - ActiveStorage::Attachment.skip_callback(:commit, :after, :purge_dependent_blob_later) + ActiveStorage::Attachment.skip_callback(:commit, :after, :purge_dependent_blob) rescue => e puts "⚠️ Warning: Could not skip some callbacks: #{e.message}" end diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb index 4e7854ea97..73015e3d8f 100644 --- a/test/application_system_test_case.rb +++ b/test/application_system_test_case.rb @@ -34,4 +34,10 @@ def sign_in_as(user) visit session_transfer_url(user.identity.transfer_id, script_name: nil) assert_current_path root_path end + + def fill_in_lexxy(selector = "lexxy-editor", with:) + editor_element = find(selector) + editor_element.set with + page.execute_script("arguments[0].value = '#{with}'", editor_element) + end end diff --git a/test/channels/solid_cable_adapter_test.rb b/test/channels/solid_cable_adapter_test.rb new file mode 100644 index 0000000000..319fd5b576 --- /dev/null +++ b/test/channels/solid_cable_adapter_test.rb @@ -0,0 +1,33 @@ +require "test_helper" + +# config/cable.yml uses `adapter: test` in the test env, but beta/staging/production use +# `adapter: solid_cable`. So the normal channel/connection tests (which run through +# ActionCable::Connection::TestCase) never exercise the real solid_cable subscription +# adapter, and a green suite says nothing about whether it works against the installed +# Rails. +# +# This guards the adapter against ActionCable::SubscriptionAdapter::Base contract changes on +# Rails upgrades. rails/rails 96b3add356 ("Extract async executor from Action Cable +# event_loop") dropped @server from the adapter base in favor of @executor/@config; older +# solid_cable releases still called @server.mutex / @server.event_loop, so on Rails edge +# every WebSocket connect raised `undefined method 'mutex' for nil` — a break that only +# surfaced in beta because tests use the `test` adapter. +class SolidCableAdapterTest < ActiveSupport::TestCase + # Stand-in so we exercise the adapter's mutex/executor resolution (the code that broke) + # without starting the real listener's DB-polling thread — the test env's cable database + # has no solid_cable_messages table (it uses adapter: test). + class FakeListener + def add_subscriber(*); end + def shutdown; end + end + + test "subscription adapter resolves mutex/executor against the installed Action Cable" do + adapter = ActionCable::SubscriptionAdapter::SolidCable.new(ActionCable.server) + ActionCable::SubscriptionAdapter::SolidCable::Listener.stubs(:new).returns(FakeListener.new) + + assert_nothing_raised do + adapter.subscribe("fizzy:solid_cable_adapter_regression", ->(_message) { }) + end + adapter.shutdown + end +end diff --git a/test/controllers/accounts/exports_controller_test.rb b/test/controllers/accounts/exports_controller_test.rb index fd950f989e..1888583559 100644 --- a/test/controllers/accounts/exports_controller_test.rb +++ b/test/controllers/accounts/exports_controller_test.rb @@ -103,6 +103,25 @@ class Account::ExportsControllerTest < ActionDispatch::IntegrationTest assert body["download_url"].present? end + test "show as JSON with bearer token returns a download URL that can be fetched" do + export = Account::Export.create!(account: Current.account, user: users(:jason)) + export.build + sign_out + bearer_token = { "HTTP_AUTHORIZATION" => "Bearer #{identity_access_tokens(:jasons_api_token).token}" } + + get account_export_path(export), as: :json, env: bearer_token + assert_response :success + + body = @response.parsed_body + assert_equal export.id, body["id"] + assert_equal "completed", body["status"] + assert body["download_url"].present? + + get URI(body["download_url"]).request_uri, env: bearer_token + assert_response :redirect + assert_match %r{rails/active_storage}, response.location + end + test "show as JSON with pending export" do export = Account::Export.create!(account: Current.account, user: users(:jason)) diff --git a/test/controllers/active_storage/direct_uploads_controller_test.rb b/test/controllers/active_storage/direct_uploads_controller_test.rb index f52d343210..9ee0cb8b9c 100644 --- a/test/controllers/active_storage/direct_uploads_controller_test.rb +++ b/test/controllers/active_storage/direct_uploads_controller_test.rb @@ -34,6 +34,43 @@ class ActiveStorage::DirectUploadsControllerTest < ActionDispatch::IntegrationTe assert_includes response.parsed_body.keys, "direct_upload" end + test "create with session token" do + sign_in_as :david + + post rails_direct_uploads_path, + params: @blob_params, + as: :json + + assert_response :success + assert_includes response.parsed_body.keys, "direct_upload" + end + + test "create with session token skips forgery protection" do + sign_in_as :david + + with_forgery_protection do + post rails_direct_uploads_path, + params: @blob_params, + as: :json + + assert_response :success + assert_includes response.parsed_body.keys, "direct_upload" + end + end + + test "create with session token from a cross-site request is forbidden" do + sign_in_as :david + + with_forgery_protection do + post rails_direct_uploads_path, + params: @blob_params, + headers: { "Sec-Fetch-Site" => "cross-site" }, + as: :json + + assert_response :unprocessable_entity + end + end + test "create with read-only access token" do post rails_direct_uploads_path, params: @blob_params, @@ -83,4 +120,12 @@ class ActiveStorage::DirectUploadsControllerTest < ActionDispatch::IntegrationTe def bearer_token_header(token) { "Authorization" => "Bearer #{token}" } end + + def with_forgery_protection + original = ActionController::Base.allow_forgery_protection + ActionController::Base.allow_forgery_protection = true + yield + ensure + ActionController::Base.allow_forgery_protection = original + end end diff --git a/test/controllers/activities_controller_test.rb b/test/controllers/activities_controller_test.rb new file mode 100644 index 0000000000..82357e3d9f --- /dev/null +++ b/test/controllers/activities_controller_test.rb @@ -0,0 +1,272 @@ +require "test_helper" + +class ActivitiesControllerTest < ActionDispatch::IntegrationTest + setup do + sign_in_as :kevin + end + + test "index returns flat array of events with required envelope fields" do + get activities_path, as: :json + assert_response :success + + body = @response.parsed_body + assert_kind_of Array, body + assert body.any? + + event = body.first + assert_includes event.keys, "id" + assert_includes event.keys, "action" + assert_includes event.keys, "created_at" + assert_includes event.keys, "description" + assert_includes event.keys, "particulars" + assert_includes event.keys, "url" + assert_includes event.keys, "eventable_type" + assert_includes event.keys, "eventable" + assert_includes event.keys, "board" + assert_includes event.keys, "creator" + end + + test "index returns events in reverse-chronological order" do + get activities_path, as: :json + assert_response :success + + times = @response.parsed_body.map { |e| Time.parse(e["created_at"]) } + assert_equal times, times.sort.reverse + end + + test "index includes card eventable" do + event = events(:logo_published) + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.find { |e| e["id"] == event.id } + assert_not_nil item + assert_equal "Card", item["eventable_type"] + assert_equal cards(:logo).title, item["eventable"]["title"] + assert_equal "card_published", item["action"] + assert item["url"].end_with?("/cards/#{cards(:logo).number}") + end + + test "index includes comment eventable" do + event = events(:layout_commented) + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.find { |e| e["id"] == event.id } + assert_not_nil item + assert_equal "Comment", item["eventable_type"] + assert_equal card_url(event.eventable.card, anchor: ActionView::RecordIdentifier.dom_id(event.eventable)), item["url"] + assert item["eventable"]["body"].present? + end + + test "index includes board and creator at top level" do + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.first + assert item["board"]["id"].present? + assert item["board"]["name"].present? + assert item["creator"]["id"].present? + assert item["creator"]["name"].present? + end + + test "index normalizes particulars for card_assigned" do + event = events(:logo_assignment_jz) + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.find { |e| e["id"] == event.id } + assert_not_nil item + assert_equal "card_assigned", item["action"] + assert_equal [ users(:jz).id ], item["particulars"]["assignee_ids"] + end + + test "index normalizes particulars for card_unassigned" do + card = cards(:logo) + event = card.board.events.create!( + action: "card_unassigned", + creator: users(:david), + eventable: card, + account: accounts("37s"), + particulars: { assignee_ids: [ users(:jz).id ] } + ) + + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.find { |e| e["id"] == event.id } + assert_not_nil item + assert_equal [ users(:jz).id ], item["particulars"]["assignee_ids"] + end + + test "index returns empty particulars for actions with no payload" do + event = events(:logo_published) + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.find { |e| e["id"] == event.id } + assert_not_nil item + assert_equal({}, item["particulars"]) + end + + test "index normalizes particulars for card_board_changed" do + card = cards(:logo) + event = card.board.events.create!( + action: "card_board_changed", + creator: users(:david), + eventable: card, + account: accounts("37s"), + particulars: { particulars: { old_board: "Backlog", new_board: "Mobile" } } + ) + + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.find { |e| e["id"] == event.id } + assert_not_nil item + assert_equal "Backlog", item["particulars"]["old_board"] + assert_equal "Mobile", item["particulars"]["new_board"] + end + + test "index normalizes particulars for card_title_changed" do + card = cards(:logo) + event = card.board.events.create!( + action: "card_title_changed", + creator: users(:david), + eventable: card, + account: accounts("37s"), + particulars: { particulars: { old_title: "Old title", new_title: "New title" } } + ) + + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.find { |e| e["id"] == event.id } + assert_not_nil item + assert_equal "Old title", item["particulars"]["old_title"] + assert_equal "New title", item["particulars"]["new_title"] + end + + test "index normalizes particulars for card_triaged" do + card = cards(:logo) + event = card.board.events.create!( + action: "card_triaged", + creator: users(:david), + eventable: card, + account: accounts("37s"), + particulars: { particulars: { column: "In Progress" } } + ) + + get activities_path, as: :json + assert_response :success + + item = @response.parsed_body.find { |e| e["id"] == event.id } + assert_not_nil item + assert_equal "In Progress", item["particulars"]["column"] + end + + test "index filters by creator_ids" do + get activities_path(creator_ids: [ users(:kevin).id ]), as: :json + assert_response :success + + body = @response.parsed_body + assert body.any? + assert body.all? { |e| e["creator"]["id"] == users(:kevin).id } + end + + test "index filters by multiple creator_ids with OR semantics" do + get activities_path(creator_ids: [ users(:david).id, users(:kevin).id ]), as: :json + assert_response :success + + body = @response.parsed_body + creator_ids = body.map { |e| e["creator"]["id"] }.uniq.sort + assert_includes creator_ids, users(:david).id + assert_includes creator_ids, users(:kevin).id + end + + test "index filters by board_ids" do + get activities_path(board_ids: [ boards(:writebook).id ]), as: :json + assert_response :success + + body = @response.parsed_body + assert body.any? + assert body.all? { |e| e["board"]["id"] == boards(:writebook).id } + end + + test "index ANDs creator_ids and board_ids filters" do + get activities_path(creator_ids: [ users(:david).id ], board_ids: [ boards(:writebook).id ]), as: :json + assert_response :success + + body = @response.parsed_body + assert body.any? + assert body.all? { |e| e["creator"]["id"] == users(:david).id } + assert body.all? { |e| e["board"]["id"] == boards(:writebook).id } + end + + test "index ignores empty creator_ids and board_ids filters" do + get activities_path(creator_ids: [], board_ids: []), as: :json + assert_response :success + + assert_predicate @response.parsed_body, :any? + end + + test "index only returns events from accessible boards" do + get activities_path, as: :json + assert_response :success + + accessible_board_ids = users(:kevin).boards.pluck(:id) + @response.parsed_body.each do |item| + assert_includes accessible_board_ids, item["board"]["id"] + end + end + + test "index paginates and returns Link header when more results exist" do + board = boards(:writebook) + 30.times do |i| + board.events.create!( + action: "card_published", + creator: users(:kevin), + eventable: cards(:logo), + account: accounts("37s") + ) + end + + get activities_path, as: :json + assert_response :success + + link_header = @response.headers["Link"] + assert link_header.present?, "Expected a Link header for paginated results" + assert_match(/rel="next"/, link_header) + end + + test "index follows pagination to retrieve all events" do + board = boards(:writebook) + 30.times do + board.events.create!( + action: "card_published", + creator: users(:kevin), + eventable: cards(:logo), + account: accounts("37s") + ) + end + + all_ids = [] + next_path = activities_path(format: :json) + + while next_path + get next_path + assert_response :success + all_ids.concat(@response.parsed_body.map { |e| e["id"] }) + next_path = next_page_from_link_header(@response.headers["Link"]) + end + + total = Event.where(board: users(:kevin).boards).where(action: ActivitiesController::ACTIONS).count + assert_equal total, all_ids.uniq.count + end + + private + def next_page_from_link_header(link_header) + url = link_header&.match(/<([^>]+)>;\s*rel="next"/)&.captures&.first + URI.parse(url).request_uri if url + end +end diff --git a/test/controllers/api/flat_json_params_test.rb b/test/controllers/api/flat_json_params_test.rb index 7a9a5ea5d2..af092d6122 100644 --- a/test/controllers/api/flat_json_params_test.rb +++ b/test/controllers/api/flat_json_params_test.rb @@ -53,7 +53,7 @@ class FlatJsonParamsTest < ActionDispatch::IntegrationTest end test "create push subscription with flat JSON" do - stub_dns_resolution("142.250.185.206") + stub_web_push_dns_resolution post user_push_subscriptions_path(users(:kevin)), params: { endpoint: "https://fcm.googleapis.com/fcm/send/abc123", p256dh_key: "key1", auth_key: "key2" }, @@ -104,11 +104,13 @@ class FlatJsonParamsTest < ActionDispatch::IntegrationTest params: { name: "Flat board", auto_postpone_period_in_days: 7, public_description: "

Flat public desc

" }, as: :json - assert_response :no_content + assert_response :success board.reload assert_equal "Flat board", board.name assert_equal 7.days, board.entropy.auto_postpone_period assert_equal "Flat public desc", board.public_description.to_plain_text + assert_equal board.id, @response.parsed_body["id"] + assert_equal "Flat board", @response.parsed_body["name"] end test "create column with flat JSON" do @@ -127,8 +129,10 @@ class FlatJsonParamsTest < ActionDispatch::IntegrationTest put board_column_path(column.board, column), params: { name: "Flat Updated" }, as: :json - assert_response :no_content + assert_response :success assert_equal "Flat Updated", column.reload.name + assert_equal column.id, @response.parsed_body["id"] + assert_equal "Flat Updated", @response.parsed_body["name"] end test "create step with flat JSON" do @@ -184,8 +188,10 @@ class FlatJsonParamsTest < ActionDispatch::IntegrationTest test "update user with flat JSON" do put user_path(users(:david)), params: { name: "Flat Name" }, as: :json - assert_response :no_content + assert_response :success assert_equal "Flat Name", users(:david).reload.name + assert_equal users(:david).id, @response.parsed_body["id"] + assert_equal "Flat Name", @response.parsed_body["name"] end test "create webhook with flat JSON" do @@ -247,11 +253,4 @@ class FlatJsonParamsTest < ActionDispatch::IntegrationTest assert_response :no_content assert_equal "Flat Join", users(:david).reload.name end - - private - def stub_dns_resolution(*ips) - dns_mock = mock("dns") - dns_mock.stubs(:each_address).multiple_yields(*ips) - Resolv::DNS.stubs(:open).yields(dns_mock) - end end diff --git a/test/controllers/boards/accesses_controller_test.rb b/test/controllers/boards/accesses_controller_test.rb new file mode 100644 index 0000000000..6f883f19a2 --- /dev/null +++ b/test/controllers/boards/accesses_controller_test.rb @@ -0,0 +1,105 @@ +require "test_helper" + +class Boards::AccessesControllerTest < ActionDispatch::IntegrationTest + setup do + sign_in_as :kevin + end + + test "index returns active account users with access status" do + board = boards(:writebook) + + get board_accesses_path(board), as: :json + assert_response :success + + body = @response.parsed_body + assert_equal board.id, body["board_id"] + assert body["all_access"] + + user_ids = body["users"].map { |u| u["id"] } + accounts("37s").users.active.each do |user| + assert_includes user_ids, user.id + end + end + + test "index includes has_access and involvement for users with access" do + board = boards(:writebook) + board.access_for(users(:kevin)).update!(involvement: :watching) + + get board_accesses_path(board), as: :json + + kevin_entry = @response.parsed_body["users"].find { |u| u["id"] == users(:kevin).id } + assert kevin_entry["has_access"] + assert_equal "watching", kevin_entry["involvement"] + end + + test "index shows has_access false and nil involvement for users without access" do + board = boards(:private) + + get board_accesses_path(board), as: :json + assert_response :success + + david_entry = @response.parsed_body["users"].find { |u| u["id"] == users(:david).id } + assert_not david_entry["has_access"] + assert_nil david_entry["involvement"] + end + + test "index includes standard user fields" do + get board_accesses_path(boards(:writebook)), as: :json + + user_entry = @response.parsed_body["users"].first + assert user_entry.key?("id") + assert user_entry.key?("name") + assert user_entry.key?("role") + assert user_entry.key?("email_address") + assert user_entry.key?("avatar_url") + end + + test "index requires board access" do + logout_and_sign_in_as :david + board = boards(:private) + + get board_accesses_path(board), as: :json + assert_response :not_found + end + + test "index is accessible to non-admin board members" do + logout_and_sign_in_as :jz + board = boards(:writebook) + + get board_accesses_path(board), as: :json + assert_response :success + end + + test "index paginates account users" do + account = accounts("37s") + board = boards(:private) + + 200.times do |index| + identity = Identity.create!(email_address: "board-membership-#{index}@example.com") + account.users.create!(identity: identity, name: "Board Membership User #{index}", role: :member) + end + + expected_ids = account.users.active.alphabetically.pluck(:id) + actual_ids = [] + next_page = board_accesses_path(board, format: :json) + page_count = 0 + + while next_page + get next_page, as: :json + assert_response :success + + page_count += 1 + actual_ids.concat(@response.parsed_body["users"].map { |user| user["id"] }) + next_page = next_page_from_link_header(@response.headers["Link"]) + end + + assert_equal expected_ids, actual_ids + assert_operator page_count, :>, 1 + end + + private + def next_page_from_link_header(link_header) + url = link_header&.match(/<([^>]+)>;\s*rel="next"/)&.captures&.first + URI.parse(url).request_uri if url + end +end diff --git a/test/controllers/boards/columns/cards_controller_test.rb b/test/controllers/boards/columns/cards_controller_test.rb new file mode 100644 index 0000000000..bb65bdfb5d --- /dev/null +++ b/test/controllers/boards/columns/cards_controller_test.rb @@ -0,0 +1,29 @@ +require "test_helper" + +class Boards::Columns::CardsControllerTest < ActionDispatch::IntegrationTest + setup do + sign_in_as :kevin + end + + test "index as JSON" do + column = columns(:writebook_in_progress) + + get board_column_cards_path(column.board, column), as: :json + + assert_response :success + assert_kind_of Array, @response.parsed_body + assert_equal [ cards(:text).number ], @response.parsed_body.pluck("number") + assert_equal "1", response.headers["X-Total-Count"] + end + + test "cannot access cards on board without access as JSON" do + board = boards(:private) + column = board.columns.create!(name: "Secret") + + logout_and_sign_in_as :jason + + get board_column_cards_path(board, column), as: :json + + assert_response :not_found + end +end diff --git a/test/controllers/boards/columns_controller_test.rb b/test/controllers/boards/columns_controller_test.rb index 9fef675f52..45c31724c7 100644 --- a/test/controllers/boards/columns_controller_test.rb +++ b/test/controllers/boards/columns_controller_test.rb @@ -55,6 +55,7 @@ class Boards::ColumnsControllerTest < ActionDispatch::IntegrationTest assert_response :success assert_equal board.columns.count, @response.parsed_body.count + assert_equal board_column_cards_url(board, board.columns.sorted.first), @response.parsed_body.first["cards_url"] end test "show as JSON" do @@ -64,6 +65,7 @@ class Boards::ColumnsControllerTest < ActionDispatch::IntegrationTest assert_response :success assert_equal column.id, @response.parsed_body["id"] + assert_equal board_column_cards_url(column.board, column), @response.parsed_body["cards_url"] end test "create as JSON" do @@ -76,6 +78,7 @@ class Boards::ColumnsControllerTest < ActionDispatch::IntegrationTest assert_response :created assert_equal board_column_path(board, Column.last, format: :json), @response.headers["Location"] assert_equal "New Column", @response.parsed_body["name"] + assert_equal board_column_cards_url(board, Column.last), @response.parsed_body["cards_url"] end test "update as JSON" do @@ -83,8 +86,12 @@ class Boards::ColumnsControllerTest < ActionDispatch::IntegrationTest put board_column_path(column.board, column), params: { column: { name: "Updated Name" } }, as: :json - assert_response :no_content + assert_response :success assert_equal "Updated Name", column.reload.name + + json = @response.parsed_body + assert_equal column.id, json["id"] + assert_equal "Updated Name", json["name"] end test "destroy as JSON" do diff --git a/test/controllers/boards_controller_test.rb b/test/controllers/boards_controller_test.rb index 059c380266..896b504382 100644 --- a/test/controllers/boards_controller_test.rb +++ b/test/controllers/boards_controller_test.rb @@ -217,6 +217,19 @@ class BoardsControllerTest < ActionDispatch::IntegrationTest assert_equal users(:kevin).boards.count, @response.parsed_body.count end + test "index as JSON includes public_description fields for published boards" do + board = boards(:writebook) + board.publish + board.update!(public_description: "

Public board description.

") + + get boards_path, as: :json + assert_response :success + + published_board = @response.parsed_body.find { |b| b["id"] == board.id } + assert_equal board.public_description.to_plain_text, published_board["public_description"] + assert_equal board.public_description.to_s, published_board["public_description_html"] + end + test "index as JSON paginates and preserves recently-accessed order" do account = accounts("37s") kevin = users(:kevin) @@ -261,6 +274,43 @@ class BoardsControllerTest < ActionDispatch::IntegrationTest assert_equal boards(:writebook).auto_postpone_period_in_days, @response.parsed_body["auto_postpone_period_in_days"] end + test "show as JSON includes public_description fields when published" do + board = boards(:writebook) + board.publish + board.update!(public_description: "

This is a public note.

") + + get board_path(board), as: :json + assert_response :success + assert_equal board.public_description.to_plain_text, @response.parsed_body["public_description"] + assert_equal board.public_description.to_s, @response.parsed_body["public_description_html"] + end + + test "show as JSON excludes public_description fields when not published" do + board = boards(:writebook) + board.update!(public_description: "

This is a public note.

") + assert_not board.published? + + get board_path(board), as: :json + assert_response :success + assert_nil @response.parsed_body["public_description"] + assert_nil @response.parsed_body["public_description_html"] + end + + test "show as JSON includes granted user_ids when board is not all access" do + board = boards(:private) + board.accesses.revise granted: users(:david, :jz), revoked: [] + + get board_path(board), as: :json + assert_response :success + assert_equal board.users.ids.sort, @response.parsed_body["user_ids"].sort + end + + test "show as JSON excludes user_ids when board is all access" do + get board_path(boards(:writebook)), as: :json + assert_response :success + assert_nil @response.parsed_body["user_ids"] + end + test "show as JSON includes public_url when published" do board = boards(:writebook) board.publish @@ -294,8 +344,27 @@ class BoardsControllerTest < ActionDispatch::IntegrationTest put board_path(board), params: { board: { name: "Updated Name" } }, as: :json + assert_response :success + assert_equal "Updated Name", board.reload.name + + json = @response.parsed_body + assert_equal board.id, json["id"] + assert_equal "Updated Name", json["name"] + assert_equal board.creator.id, json["creator"]["id"] + end + + test "update as JSON returns no content when user removes themselves from board" do + board = boards(:writebook) + + put board_path(board), params: { + board: { name: "Updated Name", all_access: false }, + user_ids: users(:david, :jz).pluck(:id) + }, as: :json + assert_response :no_content assert_equal "Updated Name", board.reload.name + assert_not board.users.include?(users(:kevin)) + assert_empty response.body end test "destroy as JSON" do diff --git a/test/controllers/cards/boards_controller_test.rb b/test/controllers/cards/boards_controller_test.rb index ebadff9b98..6be06ce823 100644 --- a/test/controllers/cards/boards_controller_test.rb +++ b/test/controllers/cards/boards_controller_test.rb @@ -26,7 +26,13 @@ class Cards::BoardsControllerTest < ActionDispatch::IntegrationTest put card_board_path(card), params: { board_id: new_board.id }, as: :json - assert_response :no_content + assert_response :success assert_equal new_board, card.reload.board + + json = @response.parsed_body + assert_equal card.id, json["id"] + assert_equal card.number, json["number"] + assert_equal card.title, json["title"] + assert_equal new_board.id, json["board"]["id"] end end diff --git a/test/controllers/cards/comments_controller_test.rb b/test/controllers/cards/comments_controller_test.rb index be5831e39b..3e311ae203 100644 --- a/test/controllers/cards/comments_controller_test.rb +++ b/test/controllers/cards/comments_controller_test.rb @@ -102,6 +102,10 @@ class Cards::CommentsControllerTest < ActionDispatch::IntegrationTest assert_response :success assert_equal "Flat update", comment.reload.body.to_plain_text + + json = @response.parsed_body + assert_equal comment.id, json["id"] + assert_equal "Flat update", json["body"]["plain_text"] end test "update as JSON" do @@ -111,6 +115,27 @@ class Cards::CommentsControllerTest < ActionDispatch::IntegrationTest assert_response :success assert_equal "Updated comment", comment.reload.body.to_plain_text + + json = @response.parsed_body + assert_equal comment.id, json["id"] + assert_equal "Updated comment", json["body"]["plain_text"] + assert_equal comment.creator.id, json["creator"]["id"] + end + + test "edit a comment that contains a mention" do + card = cards(:logo) + mentioned_user = users(:jz) + mention_html = ActionText::Attachment.from_attachable(mentioned_user).to_html + comment = card.comments.create!(creator: users(:kevin), body: "#{mention_html} hello") + + get edit_card_comment_path(card, comment) + assert_response :success + assert_select "lexxy-editor" do |editors| + value = editors.first["value"] + attachment = Nokogiri::HTML.fragment(value).at_css("action-text-attachment") + assert_equal mentioned_user.attachable_sgid, attachment["sgid"] + assert_includes attachment["content"], mentioned_user.first_name + end end test "destroy as JSON" do diff --git a/test/controllers/cards_controller_test.rb b/test/controllers/cards_controller_test.rb index f582aa9c09..6c8f375e34 100644 --- a/test/controllers/cards_controller_test.rb +++ b/test/controllers/cards_controller_test.rb @@ -15,6 +15,27 @@ class CardsControllerTest < ActionDispatch::IntegrationTest assert_response :success end + test "index as JSON can filter by workflow column id" do + get cards_path(format: :json), params: { column_ids: [ columns(:writebook_in_progress).id ] } + assert_response :success + + assert_equal [ cards(:text).number ], @response.parsed_body.pluck("number") + end + + test "index as JSON can OR multiple workflow column ids" do + get cards_path(format: :json), params: { column_ids: [ columns(:writebook_triage).id, columns(:writebook_in_progress).id ] } + assert_response :success + + assert_equal [ cards(:logo).number, cards(:layout).number, cards(:text).number ].sort, @response.parsed_body.pluck("number").sort + end + + test "index as JSON can filter by maybe index" do + get cards_path(format: :json), params: { indexed_by: "maybe" } + assert_response :success + + assert_equal [ cards(:buy_domain).number ], @response.parsed_body.pluck("number") + end + test "create a new draft" do assert_difference -> { Card.count }, 1 do post board_cards_path(boards(:writebook)) diff --git a/test/controllers/my/timezones_controller_test.rb b/test/controllers/my/timezones_controller_test.rb index 98d45e3041..d39d7cbd46 100644 --- a/test/controllers/my/timezones_controller_test.rb +++ b/test/controllers/my/timezones_controller_test.rb @@ -12,4 +12,11 @@ class My::TimezonesControllerTest < ActionDispatch::IntegrationTest patch my_timezone_path, params: { timezone_name: "America/New_York" } assert_equal time_zone, users(:kevin).reload.timezone end + + test "update as JSON" do + assert_not_equal ActiveSupport::TimeZone["America/Chicago"], users(:kevin).timezone + patch my_timezone_path, params: { timezone_name: "America/Chicago" }, as: :json + assert_response :no_content + assert_equal ActiveSupport::TimeZone["America/Chicago"], users(:kevin).reload.timezone + end end diff --git a/test/controllers/notifications_controller_test.rb b/test/controllers/notifications_controller_test.rb index 29b454ebdf..cf0c9c5897 100644 --- a/test/controllers/notifications_controller_test.rb +++ b/test/controllers/notifications_controller_test.rb @@ -31,4 +31,14 @@ class NotificationsControllerTest < ActionDispatch::IntegrationTest assert_equal card.closed?, notification.dig("card", "closed") assert_equal card.postponed?, notification.dig("card", "postponed") end + + test "index as JSON includes an explicit null column for cards awaiting triage" do + get notifications_path, as: :json + + notification = @response.parsed_body.find { |n| n["id"] == notifications(:buy_domain_sent_back_to_triage_kevin).id } + + assert_nil notifications(:buy_domain_sent_back_to_triage_kevin).card.column + assert notification["card"].key?("column") + assert_nil notification.dig("card", "column") + end end diff --git a/test/controllers/prompts/tags_controller_test.rb b/test/controllers/prompts/tags_controller_test.rb deleted file mode 100644 index 9ddea6fae8..0000000000 --- a/test/controllers/prompts/tags_controller_test.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "test_helper" - -class Prompts::TagsControllerTest < ActionDispatch::IntegrationTest - setup do - sign_in_as :kevin - end - - test "index" do - get prompts_tags_path - assert_response :success - end -end diff --git a/test/controllers/pwa_controller_test.rb b/test/controllers/pwa_controller_test.rb new file mode 100644 index 0000000000..0b391b8ce4 --- /dev/null +++ b/test/controllers/pwa_controller_test.rb @@ -0,0 +1,31 @@ +require "test_helper" + +class PwaControllerTest < ActionDispatch::IntegrationTest + setup do + sign_in_as :david + end + + test "service worker fetches storage with CORS mode by default" do + untenanted { get "/service-worker.js" } + + assert_response :success + assert_match 'fetchOptions: { mode: "cors" }', response.body + end + + test "service worker omits CORS fetch mode when disabled" do + switch_env "SERVICE_WORKER_CORS_ENABLED", "false" do + untenanted { get "/service-worker.js" } + end + + assert_response :success + assert_no_match(/mode: "cors"/, response.body) + end + + private + def switch_env(key, value) + old, ENV[key] = ENV[key], value + yield + ensure + ENV[key] = old + end +end diff --git a/test/controllers/signup/completions_controller_test.rb b/test/controllers/signup/completions_controller_test.rb index 9fd3ba4405..89e2b267b6 100644 --- a/test/controllers/signup/completions_controller_test.rb +++ b/test/controllers/signup/completions_controller_test.rb @@ -17,6 +17,14 @@ class Signup::CompletionsControllerTest < ActionDispatch::IntegrationTest assert_response :success end + test "new when signups are disabled" do + SignupToggle.stubs(:allowed?).returns(false) + + untenanted { get new_signup_completion_path } + + assert_response :not_found + end + test "create" do untenanted do post signup_completion_path, params: { diff --git a/test/controllers/signups_controller_test.rb b/test/controllers/signups_controller_test.rb index d5cbef51fb..aef3470b6c 100644 --- a/test/controllers/signups_controller_test.rb +++ b/test/controllers/signups_controller_test.rb @@ -9,6 +9,14 @@ class SignupsControllerTest < ActionDispatch::IntegrationTest end end + test "new when signups are disabled" do + SignupToggle.stubs(:allowed?).returns(false) + + untenanted { get new_signup_path } + + assert_response :not_found + end + test "new for an authenticated user" do identity = identities(:kevin) sign_in_as identity diff --git a/test/controllers/users/data_exports_controller_test.rb b/test/controllers/users/data_exports_controller_test.rb index c482547053..4007c6eef8 100644 --- a/test/controllers/users/data_exports_controller_test.rb +++ b/test/controllers/users/data_exports_controller_test.rb @@ -67,6 +67,62 @@ class Users::DataExportsControllerTest < ActionDispatch::IntegrationTest assert_select "h2", "Download Expired" end + test "create as JSON" do + assert_difference -> { User::DataExport.count }, 1 do + assert_enqueued_with(job: DataExportJob) do + post user_data_exports_path(@user), as: :json + end + end + + assert_response :created + body = @response.parsed_body + assert body["id"].present? + assert_equal "pending", body["status"] + assert_nil body["download_url"] + end + + test "show as JSON with completed export" do + export = @user.data_exports.create!(account: Current.account) + export.build + + get user_data_export_path(@user, export), as: :json + assert_response :success + + body = @response.parsed_body + assert_equal export.id, body["id"] + assert_equal "completed", body["status"] + assert body["download_url"].present? + end + + test "show as JSON with pending export" do + export = @user.data_exports.create!(account: Current.account) + + get user_data_export_path(@user, export), as: :json + assert_response :success + + body = @response.parsed_body + assert_equal export.id, body["id"] + assert_equal "pending", body["status"] + assert_nil body["download_url"] + end + + test "show as JSON with failed export" do + export = @user.data_exports.create!(account: Current.account, status: :failed) + + get user_data_export_path(@user, export), as: :json + assert_response :success + + body = @response.parsed_body + assert_equal export.id, body["id"] + assert_equal "failed", body["status"] + assert_nil body["download_url"] + end + + test "show as JSON with missing export" do + get user_data_export_path(@user, "nonexistent"), as: :json + assert_response :not_found + end + test "create is forbidden for other users" do other_user = users(:kevin) @@ -75,6 +131,14 @@ class Users::DataExportsControllerTest < ActionDispatch::IntegrationTest assert_response :forbidden end + test "create as JSON is forbidden for other users" do + other_user = users(:kevin) + + post user_data_exports_path(other_user), as: :json + + assert_response :forbidden + end + test "show is forbidden for other users" do other_user = users(:kevin) export = other_user.data_exports.create!(account: Current.account) @@ -84,4 +148,26 @@ class Users::DataExportsControllerTest < ActionDispatch::IntegrationTest assert_response :forbidden end + + test "show as JSON is forbidden for other users" do + other_user = users(:kevin) + export = other_user.data_exports.create!(account: Current.account) + export.build + + get user_data_export_path(other_user, export), as: :json + + assert_response :forbidden + end + + test "create as JSON rejects request when current export limit is reached" do + Users::DataExportsController::CURRENT_EXPORT_LIMIT.times do + @user.data_exports.create!(account: Current.account) + end + + assert_no_difference -> { User::DataExport.count } do + post user_data_exports_path(@user), as: :json + end + + assert_response :too_many_requests + end end diff --git a/test/controllers/users/email_addresses/confirmations_controller_test.rb b/test/controllers/users/email_addresses/confirmations_controller_test.rb index 5cd2b4a7e7..9d1764a37f 100644 --- a/test/controllers/users/email_addresses/confirmations_controller_test.rb +++ b/test/controllers/users/email_addresses/confirmations_controller_test.rb @@ -27,4 +27,42 @@ class Users::EmailAddresses::ConfirmationsControllerTest < ActionDispatch::Integ assert_response :unprocessable_entity assert_match /Link expired/, response.body end + + test "create as JSON" do + post user_email_address_confirmation_path(user_id: @user.id, email_address_token: @token, script_name: @user.account.slug), as: :json + + assert_response :no_content + assert_equal @new_email, @user.reload.identity.email_address + end + + test "create as JSON with invalid token" do + post user_email_address_confirmation_path(user_id: @user.id, email_address_token: "invalid", script_name: @user.account.slug), as: :json + + assert_response :unprocessable_entity + assert_equal "Token is invalid or has expired", @response.parsed_body["error"] + assert_equal @old_email, @user.reload.identity.email_address + end + + test "create as JSON with expired token" do + expired_token = @user.send(:generate_email_address_change_token, to: @new_email, expires_in: 0.seconds) + + travel_to 1.minute.from_now do + post user_email_address_confirmation_path(user_id: @user.id, email_address_token: expired_token, script_name: @user.account.slug), as: :json + + assert_response :unprocessable_entity + assert_equal "Token is invalid or has expired", @response.parsed_body["error"] + assert_equal @old_email, @user.reload.identity.email_address + end + end + + test "create as JSON changes identity" do + assert_equal @old_email, @user.identity.email_address + + post user_email_address_confirmation_path(user_id: @user.id, email_address_token: @token, script_name: @user.account.slug), as: :json + + assert_response :no_content + @user.reload + assert_equal @new_email, @user.identity.email_address + assert_not_equal @old_email, @user.identity.email_address + end end diff --git a/test/controllers/users/email_addresses_controller_test.rb b/test/controllers/users/email_addresses_controller_test.rb index d9b973d882..064345c201 100644 --- a/test/controllers/users/email_addresses_controller_test.rb +++ b/test/controllers/users/email_addresses_controller_test.rb @@ -20,6 +20,22 @@ class Users::EmailAddressesControllerTest < ActionDispatch::IntegrationTest assert_response :success end + test "create with invalid email format" do + assert_no_emails do + post user_email_addresses_path(@user, script_name: @user.account.slug), params: { email_address: "notanemail" } + end + assert_redirected_to new_user_email_address_path(@user) + assert_equal "Please enter a valid email address", flash[:alert] + end + + test "create with same email as current" do + assert_no_emails do + post user_email_addresses_path(@user, script_name: @user.account.slug), params: { email_address: @user.identity.email_address } + end + assert_redirected_to new_user_email_address_path(@user) + assert_equal "That is already your email address", flash[:alert] + end + test "create with existing email in same account" do existing_user = users(:kevin) existing_email = existing_user.identity.email_address @@ -37,4 +53,61 @@ class Users::EmailAddressesControllerTest < ActionDispatch::IntegrationTest end assert_response :not_found end + + test "create as JSON" do + assert_emails 1 do + post user_email_addresses_path(@user, script_name: @user.account.slug), params: { email_address: "newemail@example.com" }, as: :json + end + assert_response :created + end + + test "create as JSON with existing email in same account" do + existing_email = users(:kevin).identity.email_address + + assert_no_emails do + post user_email_addresses_path(@user, script_name: @user.account.slug), params: { email_address: existing_email }, as: :json + end + assert_response :unprocessable_entity + assert_equal "You already have a user in this account with that email address", @response.parsed_body["error"] + end + + test "create as JSON with blank email" do + assert_no_emails do + post user_email_addresses_path(@user, script_name: @user.account.slug), params: { email_address: "" }, as: :json + end + assert_response :bad_request + end + + test "create as JSON with same email as current" do + assert_no_emails do + post user_email_addresses_path(@user, script_name: @user.account.slug), params: { email_address: @user.identity.email_address }, as: :json + end + assert_response :unprocessable_entity + assert_equal "That is already your email address", @response.parsed_body["error"] + end + + test "create as JSON with same email different case" do + assert_no_emails do + post user_email_addresses_path(@user, script_name: @user.account.slug), params: { email_address: @user.identity.email_address.upcase }, as: :json + end + assert_response :unprocessable_entity + assert_equal "That is already your email address", @response.parsed_body["error"] + end + + test "create as JSON with invalid email format" do + assert_no_emails do + post user_email_addresses_path(@user, script_name: @user.account.slug), params: { email_address: "notanemail" }, as: :json + end + assert_response :unprocessable_entity + assert_equal "Please enter a valid email address", @response.parsed_body["error"] + end + + test "create as JSON for other user" do + other_user = users(:kevin) + + assert_no_emails do + post user_email_addresses_path(other_user, script_name: @user.account.slug), params: { email_address: "newemail@example.com" }, as: :json + end + assert_response :not_found + end end diff --git a/test/controllers/users/push_subscriptions_controller_test.rb b/test/controllers/users/push_subscriptions_controller_test.rb index b9f43ff0ad..b18f4a7f8c 100644 --- a/test/controllers/users/push_subscriptions_controller_test.rb +++ b/test/controllers/users/push_subscriptions_controller_test.rb @@ -1,11 +1,9 @@ require "test_helper" class Users::PushSubscriptionsControllerTest < ActionDispatch::IntegrationTest - PUBLIC_TEST_IP = "142.250.185.206" - setup do sign_in_as :david - stub_dns_resolution(PUBLIC_TEST_IP) + stub_web_push_dns_resolution end test "create new push subscription" do @@ -92,11 +90,4 @@ class Users::PushSubscriptionsControllerTest < ActionDispatch::IntegrationTest assert_response :unprocessable_entity end - - private - def stub_dns_resolution(*ips) - dns_mock = mock("dns") - dns_mock.stubs(:each_address).multiple_yields(*ips) - Resolv::DNS.stubs(:open).yields(dns_mock) - end end diff --git a/test/controllers/users_controller_test.rb b/test/controllers/users_controller_test.rb index 7fd9fd28da..dcadefccec 100644 --- a/test/controllers/users_controller_test.rb +++ b/test/controllers/users_controller_test.rb @@ -120,8 +120,12 @@ class UsersControllerTest < ActionDispatch::IntegrationTest put user_path(users(:david)), params: { user: { name: "New David" } }, as: :json - assert_response :no_content + assert_response :success assert_equal "New David", users(:david).reload.name + + json = @response.parsed_body + assert_equal users(:david).id, json["id"] + assert_equal "New David", json["name"] end test "update as JSON with invalid avatar returns errors" do diff --git a/test/controllers/webhooks/deliveries_controller_test.rb b/test/controllers/webhooks/deliveries_controller_test.rb new file mode 100644 index 0000000000..49b167e6d7 --- /dev/null +++ b/test/controllers/webhooks/deliveries_controller_test.rb @@ -0,0 +1,90 @@ +require "test_helper" + +class Webhooks::DeliveriesControllerTest < ActionDispatch::IntegrationTest + setup do + sign_in_as :kevin + end + + test "index as JSON" do + webhook = webhooks(:active) + delivery = webhook_deliveries(:successfully_completed) + webhook_timestamp = delivery.event.created_at.utc.iso8601 + delivery.update!( + request: { + headers: { + "User-Agent" => "fizzy/1.0.0 Webhook", + "Content-Type" => "application/json", + "X-Webhook-Signature" => "super-secret-signature", + "X-Webhook-Timestamp" => webhook_timestamp + } + }, + response: { code: 200 } + ) + + get board_webhook_deliveries_path(webhook.board, webhook), as: :json + + assert_response :success + assert_kind_of Array, @response.parsed_body + assert_equal webhook.deliveries.count, @response.parsed_body.count + assert_equal webhook.deliveries.ordered.pluck(:id), @response.parsed_body.pluck("id") + + completed_delivery = @response.parsed_body.find { |record| record["id"] == delivery.id } + + assert_equal "completed", completed_delivery["state"] + assert_equal delivery.created_at.utc.iso8601(3), completed_delivery["created_at"] + assert_equal delivery.updated_at.utc.iso8601(3), completed_delivery["updated_at"] + assert_equal "fizzy/1.0.0 Webhook", completed_delivery.dig("request", "headers", "User-Agent") + assert_equal "application/json", completed_delivery.dig("request", "headers", "Content-Type") + assert_equal webhook_timestamp, completed_delivery.dig("request", "headers", "X-Webhook-Timestamp") + assert_not completed_delivery.dig("request", "headers").key?("X-Webhook-Signature") + assert_equal 200, completed_delivery.dig("response", "code") + assert_nil completed_delivery.dig("response", "error") + assert_equal delivery.event.id, completed_delivery.dig("event", "id") + assert_equal delivery.event.action, completed_delivery.dig("event", "action") + assert_equal delivery.event.created_at.utc.iso8601(3), completed_delivery.dig("event", "created_at") + assert_equal delivery.event.creator_id, completed_delivery.dig("event", "creator", "id") + assert_equal delivery.event.creator.name, completed_delivery.dig("event", "creator", "name") + assert_equal delivery.event.eventable_type, completed_delivery.dig("event", "eventable", "type") + assert_equal delivery.event.eventable_id, completed_delivery.dig("event", "eventable", "id") + assert_equal polymorphic_url(delivery.event.eventable), completed_delivery.dig("event", "eventable", "url") + + pending_delivery = @response.parsed_body.find { |record| record["id"] == webhook_deliveries(:pending).id } + assert_nil pending_delivery["request"] + assert_nil pending_delivery["response"] + end + + test "index defaults to JSON" do + webhook = webhooks(:active) + + get board_webhook_deliveries_path(webhook.board, webhook) + + assert_response :success + assert_equal "application/json; charset=utf-8", @response.headers["Content-Type"] + end + + test "index rejects HTML" do + webhook = webhooks(:active) + + get board_webhook_deliveries_path(webhook.board, webhook, format: :html) + + assert_response :not_acceptable + end + + test "non-admin cannot access deliveries as JSON" do + logout_and_sign_in_as :jz + webhook = webhooks(:active) + + get board_webhook_deliveries_path(webhook.board, webhook), as: :json + + assert_response :forbidden + end + + test "cannot access deliveries on board without access as JSON" do + logout_and_sign_in_as :jason + webhook = webhooks(:inactive) + + get board_webhook_deliveries_path(webhook.board, webhook), as: :json + + assert_response :not_found + end +end diff --git a/test/fixtures/events.yml b/test/fixtures/events.yml index ea4f2f465c..258619653c 100644 --- a/test/fixtures/events.yml +++ b/test/fixtures/events.yml @@ -37,6 +37,15 @@ logo_assignment_km: created_at: <%= 1.day.ago %> account: 37s_uuid +buy_domain_sent_back_to_triage: + id: <%= ActiveRecord::FixtureSet.identify("buy_domain_sent_back_to_triage", :uuid) %> + creator: david_uuid + board: writebook_uuid + eventable: buy_domain_uuid (Card) + action: card_sent_back_to_triage + created_at: <%= 1.day.ago %> + account: 37s_uuid + layout_published: id: <%= ActiveRecord::FixtureSet.identify("layout_published", :uuid) %> creator: david_uuid diff --git a/test/fixtures/notifications.yml b/test/fixtures/notifications.yml index 8fa4404d53..95cc84d37a 100644 --- a/test/fixtures/notifications.yml +++ b/test/fixtures/notifications.yml @@ -9,6 +9,17 @@ logo_assignment_kevin: creator: david_uuid account: 37s_uuid +buy_domain_sent_back_to_triage_kevin: + id: <%= ActiveRecord::FixtureSet.identify("buy_domain_sent_back_to_triage_kevin", :uuid) %> + user: kevin_uuid + source: buy_domain_sent_back_to_triage_uuid (Event) + card: buy_domain_uuid + unread_count: 1 + created_at: <%= 1.day.ago %> + updated_at: <%= 1.day.ago + 1.second %> + creator: david_uuid + account: 37s_uuid + layout_commented_kevin: id: <%= ActiveRecord::FixtureSet.identify("layout_commented_kevin", :uuid) %> user: kevin_uuid diff --git a/test/integration/active_storage_authorization_test.rb b/test/integration/active_storage_authorization_test.rb index 605bc109db..3fed18267e 100644 --- a/test/integration/active_storage_authorization_test.rb +++ b/test/integration/active_storage_authorization_test.rb @@ -17,6 +17,15 @@ class ActiveStorageAuthorizationTest < ActionDispatch::IntegrationTest assert_match %r{rails/active_storage}, response.location end + test "bearer token with board access can view blob" do + bearer_token = { "HTTP_AUTHORIZATION" => "Bearer #{identity_access_tokens(:davids_api_token).token}" } + + get rails_blob_path(@blob, disposition: :inline), env: bearer_token + + assert_response :redirect + assert_match %r{rails/active_storage}, response.location + end + test "authenticated user without board access cannot view blob" do sign_in_as :mike @@ -38,6 +47,15 @@ class ActiveStorageAuthorizationTest < ActionDispatch::IntegrationTest assert_match %r{rails/active_storage/}, response.location end + test "bearer token with board access can view representation" do + bearer_token = { "HTTP_AUTHORIZATION" => "Bearer #{identity_access_tokens(:davids_api_token).token}" } + + get rails_representation_path(@blob.representation(resize_to_limit: [ 100, 100 ])), env: bearer_token + + assert_response :redirect + assert_match %r{rails/active_storage/}, response.location + end + test "authenticated user without board access cannot view representation" do sign_in_as :mike @@ -194,6 +212,16 @@ class ActiveStorageAuthorizationTest < ActionDispatch::IntegrationTest assert_match %r{rails/active_storage}, response.location end + test "export owner can download their export with bearer token" do + blob = create_export_blob_for(users(:david)) + bearer_token = { "HTTP_AUTHORIZATION" => "Bearer #{identity_access_tokens(:davids_api_token).token}" } + + get rails_blob_path(blob, disposition: :attachment), env: bearer_token + + assert_response :redirect + assert_match %r{rails/active_storage}, response.location + end + test "non-owner cannot download another user's export" do sign_in_as :jz diff --git a/test/integration/notifications_test.rb b/test/integration/notifications_test.rb index f581fb5e94..623d1ba367 100644 --- a/test/integration/notifications_test.rb +++ b/test/integration/notifications_test.rb @@ -9,6 +9,7 @@ class NotificationDeliveryTest < ActiveSupport::TestCase @card.assignments.destroy_all @assignee.notifications.destroy_all + stub_dns_resolution("142.250.185.206") stub_web_push_pool @original_targets = Notification.push_targets.dup @@ -16,6 +17,8 @@ class NotificationDeliveryTest < ActiveSupport::TestCase Notification.register_push_target(:web) Notification.register_push_target(push_target_with_tracking) + stub_web_push_dns_resolution + # Give assignee a web push subscription @assignee.push_subscriptions.create!( endpoint: "https://fcm.googleapis.com/fcm/send/test123", diff --git a/test/jobs/search_reindex_job_test.rb b/test/jobs/search_reindex_job_test.rb new file mode 100644 index 0000000000..da238e3c50 --- /dev/null +++ b/test/jobs/search_reindex_job_test.rb @@ -0,0 +1,82 @@ +require "test_helper" + +class SearchReindexJobTest < ActiveJob::TestCase + test "reindexes cards and comments after their search records are nuked" do + card = cards(:logo) + comment = comments(:logo_1) + + card.reindex + comment.reindex + + card_shard = Search::Record.for(card.account_id) + comment_shard = Search::Record.for(comment.account_id) + + assert card_shard.exists?(searchable_type: "Card", searchable_id: card.id) + assert comment_shard.exists?(searchable_type: "Comment", searchable_id: comment.id) + + card_shard.delete_all + comment_shard.delete_all unless comment_shard == card_shard + + assert_not card_shard.exists?(searchable_type: "Card", searchable_id: card.id) + assert_not comment_shard.exists?(searchable_type: "Comment", searchable_id: comment.id) + + SearchReindexJob.perform_now + + assert card_shard.exists?(searchable_type: "Card", searchable_id: card.id) + assert comment_shard.exists?(searchable_type: "Comment", searchable_id: comment.id) + end + + test "skips records whose rich text exceeds rich_text_limit" do + Current.account = accounts(:"37s") + Current.session = Session.new(identity: identities(:david)) + + big_card = boards(:writebook).cards.create!( + creator: users(:david), + title: "too big to index", + status: :published, + description: "x" * 5_000 + ) + + nuke_search_records + + SearchReindexJob.perform_now(rich_text_limit: 1_000) + + shard = Search::Record.for(big_card.account_id) + assert_not shard.exists?(searchable_type: "Card", searchable_id: big_card.id) + end + + test "does not index drafted cards or their comments" do + Current.account = accounts(:"37s") + Current.session = Session.new(identity: identities(:david)) + + card = boards(:writebook).cards.create!( + creator: users(:david), + title: "will be drafted", + status: :published + ) + comment = card.comments.create!(creator: users(:david), body: "on a card that will be drafted") + card.update!(status: :drafted) + + nuke_search_records + + SearchReindexJob.perform_now + + shard = Search::Record.for(card.account_id) + assert_not shard.exists?(searchable_type: "Card", searchable_id: card.id) + assert_not shard.exists?(searchable_type: "Comment", searchable_id: comment.id) + end + + private + def sqlite? + ActiveRecord::Base.connection.adapter_name == "SQLite" + end + + def nuke_search_records + if sqlite? + ActiveRecord::Base.connection.execute("DELETE FROM search_records") + ActiveRecord::Base.connection.execute("DELETE FROM search_records_fts") + else + Search::Record::Trilogy::SHARD_CLASSES.each(&:delete_all) + end + end +end diff --git a/test/lib/web_push/persistent_request_test.rb b/test/lib/web_push/persistent_request_test.rb index 649e27b759..41d5572492 100644 --- a/test/lib/web_push/persistent_request_test.rb +++ b/test/lib/web_push/persistent_request_test.rb @@ -1,12 +1,11 @@ require "test_helper" class WebPush::PersistentRequestTest < ActiveSupport::TestCase - PUBLIC_TEST_IP = "142.250.185.206" ENDPOINT = "https://fcm.googleapis.com/fcm/send/test123" test "pins connection to endpoint_ip" do request = stub_request(:post, ENDPOINT) - .with(ipaddr: PUBLIC_TEST_IP) + .with(ipaddr: DnsTestHelper::WEB_PUSH_PUBLIC_TEST_IP) .to_return(status: 201) notification = WebPush::Notification.new( @@ -15,7 +14,7 @@ class WebPush::PersistentRequestTest < ActiveSupport::TestCase url: "/test", badge: 0, endpoint: ENDPOINT, - endpoint_ip: PUBLIC_TEST_IP, + endpoint_ip: DnsTestHelper::WEB_PUSH_PUBLIC_TEST_IP, p256dh_key: "BNcRdreALRFXTkOOUHK1EtK2wtaz5Ry4YfYCA_0QTpQtUbVlUls0VJXg7A8u-Ts1XbjhazAkj7I99e8QcYP7DkM", auth_key: "tBHItJI5svbpez7KI4CCXg" ) diff --git a/test/mailers/notification/bundle_mailer_test.rb b/test/mailers/notification/bundle_mailer_test.rb index 8aca366c9a..d37ecaeb78 100644 --- a/test/mailers/notification/bundle_mailer_test.rb +++ b/test/mailers/notification/bundle_mailer_test.rb @@ -106,6 +106,19 @@ class Notification::BundleMailerTest < ActionMailer::TestCase "Should not generate a real email when all notifications are stale" end + test "deliver_later works with account context" do + # Give user a second account so the mailer includes the account name in the subject + second_account = Account.create!(name: "Second account") + second_account.users.create!(identity: @user.identity, role: :member, name: @user.name) + + create_notification(@user) + + Notification::BundleMailer.notification(@bundle).deliver_later + perform_enqueued_jobs + + assert_emails 1 + end + private def create_notification(user, source: events(:logo_published)) Notification.create!(user: user, creator: user, source: source, created_at: 30.minutes.ago) diff --git a/test/models/account/data_transfer/action_text/rich_text_record_set_test.rb b/test/models/account/data_transfer/action_text/rich_text_record_set_test.rb index 2fe2c4b935..3bc4ee0016 100644 --- a/test/models/account/data_transfer/action_text/rich_text_record_set_test.rb +++ b/test/models/account/data_transfer/action_text/rich_text_record_set_test.rb @@ -44,11 +44,11 @@ class Account::DataTransfer::ActionText::RichTextRecordSetTest < ActiveSupport:: end test "transform_body_for_import skips GIDs belonging to another account" do - victim_tag = tags(:web) + victim_user = users(:david) attacker_account = accounts(:initech) - assert_not_equal attacker_account.id, victim_tag.account_id + assert_not_equal attacker_account.id, victim_user.account_id - cross_tenant_gid = victim_tag.to_global_id.to_s + cross_tenant_gid = victim_user.to_global_id.to_s html = %() record_set = Account::DataTransfer::ActionText::RichTextRecordSet.new(attacker_account) @@ -59,11 +59,11 @@ class Account::DataTransfer::ActionText::RichTextRecordSetTest < ActiveSupport:: end test "transform_body_for_import converts GIDs belonging to the same account" do - own_tag = tags(:web) + own_user = users(:david) own_account = accounts(:"37s") - assert_equal own_account.id, own_tag.account_id + assert_equal own_account.id, own_user.account_id - same_account_gid = own_tag.to_global_id.to_s + same_account_gid = own_user.to_global_id.to_s html = %() record_set = Account::DataTransfer::ActionText::RichTextRecordSet.new(own_account) @@ -74,7 +74,7 @@ class Account::DataTransfer::ActionText::RichTextRecordSetTest < ActiveSupport:: end test "transform_body_for_import handles non-existent record GIDs gracefully" do - nonexistent_gid = "gid://fizzy/Tag/00000000000000000000000000" + nonexistent_gid = "gid://fizzy/User/00000000000000000000000000" html = %() record_set = Account::DataTransfer::ActionText::RichTextRecordSet.new(accounts(:"37s")) diff --git a/test/models/account/import_test.rb b/test/models/account/import_test.rb index de384b385f..c1e9c2f7cb 100644 --- a/test/models/account/import_test.rb +++ b/test/models/account/import_test.rb @@ -226,6 +226,7 @@ def account_digest(account) name: account.name, board_count: Board.where(account: account).count, column_count: Column.where(account: account).count, + column_colors: Column.where(account: account).order(:id).pluck(:color), card_count: Card.where(account: account).count, comment_count: Comment.where(account: account).count, tag_count: Tag.where(account: account).count diff --git a/test/models/account/incineratable_test.rb b/test/models/account/incineratable_test.rb index 021f751ba6..cb6e6560ba 100644 --- a/test/models/account/incineratable_test.rb +++ b/test/models/account/incineratable_test.rb @@ -23,4 +23,198 @@ class Account::IncineratableTest < ActiveSupport::TestCase @account.cancellation.update!(created_at: 29.days.ago) assert Account.due_for_incineration.empty? end + + test "incinerate destroys all associated records" do + account = accounts(:initech) + board = boards(:miltons_wish_list) + card = cards(:radio) + + Current.account = account + Current.session = Session.new(identity: identities(:mike)) + + user = users(:mike) + user.create_settings!(bundle_email_frequency: :never) + + # Direct on Account + tag = Tag.create!(title: "urgent") + column = Column.create!(board: board, name: "Test", position: 0) + export = Account::Export.create!(account: account, user: user) + search_query = Search::Query.create!(user: user, terms: "test search") + storage_entry = Storage::Entry.create!(account: account, delta: 100, operation: "attach") + + # Via Board + publication = Board::Publication.create!(board: board) + webhook = Webhook.create!(board: board, name: "Test", url: "https://example.com/webhook") + event = Event.create!(board: board, creator: user, eventable: card, action: "card_published") + + # Via Webhook + delivery = Webhook::Delivery.create!(webhook: webhook, event: event) + # DelinquencyTracker is auto-created with Webhook + + # Via Card + comment = card.comments.create!(body: "Test comment") + step = Step.create!(card: card, content: "Test step") + assignment = Assignment.create!(card: card, assignee: user, assigner: user) + tagging = Tagging.create!(card: card, tag: tag) + watch = Watch.create!(card: card, user: user) + pin = Pin.create!(card: card, user: user) + reaction = Reaction.create!(reactable: card, content: "thumbs_up") + mention = Mention.create!(source: card, mentioner: user, mentionee: user) + closure = Closure.create!(card: cards(:paycheck), user: user) + goldness = Card::Goldness.create!(card: card) + not_now = Card::NotNow.create!(card: cards(:unfinished_thoughts), user: user) + activity_spike = Card::ActivitySpike.create!(card: card) + + # Via User + notification = Notification.create!(user: user, source: event, creator: user) + notification_bundle = Notification::Bundle.create!(user: user, starts_at: 1.hour.ago, ends_at: 1.hour.from_now) + filter = Filter.create!(creator: user, fields: { indexed_by: :all, sorted_by: :newest }.to_json, params_digest: SecureRandom.hex) + + # ActiveStorage (attach image to card) + card.image.attach(io: StringIO.new("fake image"), filename: "test.png", content_type: "image/png") + + account_id = account.id + user_ids = User.where(account_id: account_id).pluck(:id) + + # Confirm records exist before destroy + assert User.where(account_id: account_id).exists? + assert Board.where(account_id: account_id).exists? + assert Card.where(account_id: account_id).exists? + assert Tag.where(account_id: account_id).exists? + assert Column.where(account_id: account_id).exists? + assert Webhook.where(account_id: account_id).exists? + assert Access.where(account_id: account_id).exists? + assert Entropy.where(account_id: account_id).exists? + assert Account::JoinCode.where(account_id: account_id).exists? + assert Account::Export.where(account_id: account_id).exists? + assert Search::Query.where(account_id: account_id).exists? + assert Storage::Entry.where(account_id: account_id).exists? + assert Board::Publication.where(account_id: account_id).exists? + assert Event.where(account_id: account_id).exists? + assert Webhook::Delivery.where(account_id: account_id).exists? + assert Webhook::DelinquencyTracker.where(account_id: account_id).exists? + assert Comment.where(account_id: account_id).exists? + assert Step.where(account_id: account_id).exists? + assert Assignment.where(account_id: account_id).exists? + assert Tagging.where(account_id: account_id).exists? + assert Watch.where(account_id: account_id).exists? + assert Pin.where(account_id: account_id).exists? + assert Reaction.where(account_id: account_id).exists? + assert Mention.where(account_id: account_id).exists? + assert Closure.where(account_id: account_id).exists? + assert Card::Goldness.where(account_id: account_id).exists? + assert Card::NotNow.where(account_id: account_id).exists? + assert Card::ActivitySpike.where(account_id: account_id).exists? + assert Notification.where(account_id: account_id).exists? + assert Notification::Bundle.where(account_id: account_id).exists? + assert Filter.where(account_id: account_id).exists? + assert User::Settings.where(user_id: user.id).exists? + assert ActiveStorage::Attachment.where(account_id: account_id).exists? + assert ActiveStorage::Blob.where(account_id: account_id).exists? + assert ActionText::RichText.where(account_id: account_id).exists? + + # Flush jobs enqueued during setup (Turbo broadcasts, etc.) while records still exist + perform_enqueued_jobs + + account.incinerate + perform_enqueued_jobs + + # Confirm account is gone + assert_not Account.exists?(account_id) + + # Direct associations + assert_empty User.where(account_id: account_id) + assert_empty Board.where(account_id: account_id) + assert_empty Card.where(account_id: account_id) + assert_empty Webhook.where(account_id: account_id) + assert_empty Tag.where(account_id: account_id) + assert_empty Column.where(account_id: account_id) + assert_empty Entropy.where(account_id: account_id) + assert_empty Account::JoinCode.where(account_id: account_id) + assert_empty Account::Export.where(account_id: account_id) + assert_empty Account::Import.where(account_id: account_id) + assert_empty Search::Query.where(account_id: account_id) + + # Via Board + assert_empty Board::Publication.where(account_id: account_id) + assert_empty Access.where(account_id: account_id) + assert_empty Event.where(account_id: account_id) + + # Via Webhook + assert_empty Webhook::Delivery.where(account_id: account_id) + assert_empty Webhook::DelinquencyTracker.where(account_id: account_id) + + # Via Card + assert_empty Comment.where(account_id: account_id) + assert_empty Step.where(account_id: account_id) + assert_empty Assignment.where(account_id: account_id) + assert_empty Tagging.where(account_id: account_id) + assert_empty Watch.where(account_id: account_id) + assert_empty Pin.where(account_id: account_id) + assert_empty Reaction.where(account_id: account_id) + assert_empty Mention.where(account_id: account_id) + assert_empty Closure.where(account_id: account_id) + assert_empty Card::Goldness.where(account_id: account_id) + assert_empty Card::NotNow.where(account_id: account_id) + assert_empty Card::ActivitySpike.where(account_id: account_id) + + # Via User + assert_empty Notification.where(account_id: account_id) + assert_empty Notification::Bundle.where(account_id: account_id) + assert_empty Filter.where(account_id: account_id) + assert_empty User::Settings.where(user_id: user_ids) + + # Storage + assert_empty Storage::Entry.where(account_id: account_id) + assert_empty Storage::Total.where(owner_type: "Account", owner_id: account_id) + + # ActiveStorage / ActionText + assert_empty ActiveStorage::Attachment.where(account_id: account_id) + assert_empty ActiveStorage::Blob.where(account_id: account_id) + assert_empty ActionText::RichText.where(account_id: account_id) + + # Search records (sharded) + assert_empty Search::Record.for(account_id).where(account_id: account_id) + end + + test "incinerating an account clears its own search records but preserves others on the same shard" do + doomed = accounts(:initech) + shard = Search::Record.for(doomed.id) + + doomed_card = cards(:radio) + doomed_record = shard.create!( + account_id: doomed_card.account_id, + searchable_type: "Card", + searchable_id: doomed_card.id, + card_id: doomed_card.id, + board_id: doomed_card.board_id, + title: "doomed", + content: "should be destroyed", + created_at: Time.current + ) + + # Simulate a shard collision: plant a record belonging to a different + # account directly on doomed's shard, as would happen in production when + # two accounts' UUIDs hash to the same shard. + foreign_card = cards(:logo) + foreign_record = shard.create!( + account_id: foreign_card.account_id, + searchable_type: "Card", + searchable_id: foreign_card.id, + card_id: foreign_card.id, + board_id: foreign_card.board_id, + title: "foreign", + content: "should survive", + created_at: Time.current + ) + + Current.account = doomed + Current.session = Session.new(identity: identities(:mike)) + doomed.incinerate + + assert_not shard.exists?(id: doomed_record.id), + "the incinerated account's search record should be destroyed" + assert shard.exists?(id: foreign_record.id), + "another account's search record on the same shard should survive" + end end diff --git a/test/models/card/entropic_test.rb b/test/models/card/entropic_test.rb index fe5dfd8068..848cfa7bc1 100644 --- a/test/models/card/entropic_test.rb +++ b/test/models/card/entropic_test.rb @@ -69,11 +69,14 @@ class Card::EntropicTest < ActiveSupport::TestCase assert_not_includes Card.postponing_soon, cards(:shipping) end - test "due_to_be_postponed scope works properly cross-account" do + test "auto postpone all due works properly cross-account" do cards(:logo).update!(last_active_at: entropies(:writebook_board).auto_postpone_period.seconds.ago - 2.days) cards(:radio).update!(last_active_at: entropies(:miltons_wish_list_board).auto_postpone_period.seconds.ago - 2.days) - assert_equal(cards(:logo, :radio).to_set, Card.due_to_be_postponed.to_set) + Card.auto_postpone_all_due + + assert cards(:logo).reload.postponed? + assert cards(:radio).reload.postponed? end test "postponing_soon scope works properly cross-account" do diff --git a/test/models/card/stallable_test.rb b/test/models/card/stallable_test.rb index 0f5b3dbf4f..275abcc60c 100644 --- a/test/models/card/stallable_test.rb +++ b/test/models/card/stallable_test.rb @@ -58,7 +58,7 @@ class Card::StallableTest < ActiveSupport::TestCase assert_includes Card.stalled, card travel_to Time.now + card.board.entropy.auto_postpone_period + 1.day - assert_includes Card.due_to_be_postponed, card + assert_operator card.entropy.auto_clean_at, :<=, Time.now Card.auto_postpone_all_due diff --git a/test/models/column/colored_test.rb b/test/models/column/colored_test.rb index 9d2d469e4d..241ddb6607 100644 --- a/test/models/column/colored_test.rb +++ b/test/models/column/colored_test.rb @@ -7,6 +7,14 @@ class Column::ColoredTest < ActiveSupport::TestCase assert_equal Column::Colored::DEFAULT_COLOR, column.color end + test "reads color from legacy export format" do + column = columns(:writebook_triage) + # Broken exports serialized Color structs as JSON + column.update_column(:color, { "name" => "Lime", "value" => "var(--color-card-4)" }.to_json) + + assert_equal Color.for_value("var(--color-card-4)"), column.reload.color + end + test "update the column color" do columns(:writebook_triage).update!(color: "var(--color-card-3)") diff --git a/test/models/event_test.rb b/test/models/event_test.rb new file mode 100644 index 0000000000..3c50bd2a12 --- /dev/null +++ b/test/models/event_test.rb @@ -0,0 +1,53 @@ +require "test_helper" + +class EventTest < ActiveSupport::TestCase + test "blank creator and board filters return the current relation unchanged" do + relation = Event.where(action: "card_published") + + assert_equal relation.to_sql, relation.for_creators(nil).to_sql + assert_equal relation.to_sql, relation.for_creators([]).to_sql + assert_equal relation.to_sql, relation.for_boards(nil).to_sql + assert_equal relation.to_sql, relation.for_boards([]).to_sql + end + + test "blank creator and board filters remain chainable" do + relation = Event.where(action: "card_published") + + assert_nothing_raised do + relation.for_creators([]).for_boards([]).load + end + end + + test "api_particulars returns empty strings for missing nested board change values" do + event = boards(:writebook).events.create!( + action: "card_board_changed", + creator: users(:david), + eventable: cards(:logo), + account: accounts("37s"), + particulars: {} + ) + + assert_equal({ "old_board" => "", "new_board" => "" }, event.api_particulars) + end + + test "api_particulars returns empty strings for missing nested title and column values" do + title_event = boards(:writebook).events.create!( + action: "card_title_changed", + creator: users(:david), + eventable: cards(:logo), + account: accounts("37s"), + particulars: {} + ) + + triage_event = boards(:writebook).events.create!( + action: "card_triaged", + creator: users(:david), + eventable: cards(:logo), + account: accounts("37s"), + particulars: {} + ) + + assert_equal({ "old_title" => "", "new_title" => "" }, title_event.api_particulars) + assert_equal({ "column" => "" }, triage_event.api_particulars) + end +end diff --git a/test/models/filter_test.rb b/test/models/filter_test.rb index bb41f3e418..53d9f6a353 100644 --- a/test/models/filter_test.rb +++ b/test/models/filter_test.rb @@ -23,6 +23,9 @@ class FilterTest < ActiveSupport::TestCase filter = users(:david).filters.new indexed_by: "closed" assert_equal [ cards(:shipping) ], filter.cards + filter = users(:david).filters.new indexed_by: "maybe", board_ids: [ boards(:writebook).id ] + assert_equal [ cards(:buy_domain) ], filter.cards + cards(:shipping).postpone filter = users(:david).filters.new indexed_by: "not_now" assert_includes filter.cards, cards(:shipping) @@ -45,6 +48,15 @@ class FilterTest < ActiveSupport::TestCase assert_empty users(:david).filters.new(board_ids: [ boards(:writebook).id ]).boards end + test "board-scoped cards never leak cards from an inaccessible board in the same account" do + inaccessible_card = boards(:private).cards.create!(status: "published", creator: users(:kevin)) + + filter = users(:david).filters.new(board_ids: [ boards(:private).id, boards(:writebook).id ]) + + assert_not_includes filter.cards, inaccessible_card + filter.cards.each { |card| assert_includes users(:david).boards, card.board } + end + test "remembering equivalent filters" do assert_difference "Filter.count", +1 do filter = users(:david).filters.remember(sorted_by: "latest", assignment_status: "unassigned", tag_ids: [ tags(:mobile).id ]) @@ -166,6 +178,17 @@ class FilterTest < ActiveSupport::TestCase assert_not users(:david).filters.new(board_ids: [ boards(:writebook).id ]).used?(ignore_boards: true) end + test "column ids filter cards by workflow columns" do + assert_equal [ cards(:text) ], users(:david).filters.new(column_ids: [ columns(:writebook_in_progress).id ]).cards.to_a + assert_equal [ cards(:logo), cards(:layout) ].sort_by(&:id), users(:david).filters.new(column_ids: [ columns(:writebook_triage).id ]).cards.to_a.sort_by(&:id) + end + + test "column ids are ORed together" do + filter = users(:david).filters.new(column_ids: [ columns(:writebook_triage).id, columns(:writebook_in_progress).id ]) + + assert_equal [ cards(:logo), cards(:layout), cards(:text) ].sort_by(&:id), filter.cards.to_a.sort_by(&:id) + end + test "board titles are scoped to creator's account" do # Give mike (initech) access to the board in his account boards(:miltons_wish_list).accesses.grant_to(users(:mike)) diff --git a/test/models/notification/push_target/web_test.rb b/test/models/notification/push_target/web_test.rb index 37f23b557d..dae683eb95 100644 --- a/test/models/notification/push_target/web_test.rb +++ b/test/models/notification/push_target/web_test.rb @@ -5,6 +5,8 @@ class Notification::PushTarget::WebTest < ActiveSupport::TestCase @user = users(:david) @notification = notifications(:logo_mentioned_david) + stub_web_push_dns_resolution + @user.push_subscriptions.create!( endpoint: "https://fcm.googleapis.com/fcm/send/test123", p256dh_key: "test_key", diff --git a/test/models/notification_test.rb b/test/models/notification_test.rb index 8d9809ba1a..02dcbc7dbb 100644 --- a/test/models/notification_test.rb +++ b/test/models/notification_test.rb @@ -50,6 +50,23 @@ class NotificationTest < ActiveSupport::TestCase assert_turbo_stream_broadcasts [ kevin, :notifications ] end + test "broadcast job renders account-scoped URLs" do + kevin = users(:kevin) + account = kevin.account + notifications(:layout_commented_kevin).destroy + + # Enqueue the broadcast job but don't run it yet + notification = Notification.create!(user: kevin, source: events(:layout_commented), creator: users(:david)) + + broadcasts = capture_turbo_stream_broadcasts([ kevin, :notifications ]) do + perform_enqueued_jobs + end + + assert broadcasts.any?, "Expected at least one broadcast" + html = broadcasts.last.to_s + assert_includes html, "href=\"#{account.slug}/", "Broadcast should include account slug in URLs" + end + test "broadcasting on update when read removes" do notification = notifications(:layout_commented_kevin) diff --git a/test/models/push/subscription_test.rb b/test/models/push/subscription_test.rb index 89887599fd..b654e44988 100644 --- a/test/models/push/subscription_test.rb +++ b/test/models/push/subscription_test.rb @@ -1,10 +1,8 @@ require "test_helper" class Push::SubscriptionTest < ActiveSupport::TestCase - PUBLIC_TEST_IP = "142.250.185.206" # google.com IP - setup do - stub_dns_resolution(PUBLIC_TEST_IP) + stub_web_push_dns_resolution end test "valid subscription with permitted endpoint" do @@ -92,7 +90,7 @@ class Push::SubscriptionTest < ActiveSupport::TestCase auth_key: "test_auth" ) - assert_equal PUBLIC_TEST_IP, subscription.resolved_endpoint_ip + assert_equal DnsTestHelper::WEB_PUSH_PUBLIC_TEST_IP, subscription.resolved_endpoint_ip end test "accepts all permitted push service domains" do @@ -115,11 +113,4 @@ class Push::SubscriptionTest < ActiveSupport::TestCase assert subscription.valid?, "Expected #{endpoint} to be valid, got errors: #{subscription.errors.full_messages}" end end - - private - def stub_dns_resolution(*ips) - dns_mock = mock("dns") - dns_mock.stubs(:each_address).multiple_yields(*ips) - Resolv::DNS.stubs(:open).yields(dns_mock) - end end diff --git a/test/models/ssrf_protection_test.rb b/test/models/ssrf_protection_test.rb index 550909f89a..7504de26a4 100644 --- a/test/models/ssrf_protection_test.rb +++ b/test/models/ssrf_protection_test.rb @@ -83,10 +83,58 @@ class SsrfProtectionTest < ActiveSupport::TestCase assert_nil SsrfProtection.resolve_public_ip("compat-public.example.com") end - private - def stub_dns_resolution(*ips) - dns_mock = mock("dns") - dns_mock.stubs(:each_address).multiple_yields(*ips) - Resolv::DNS.stubs(:open).yields(dns_mock) - end + test "blocks NAT64 addresses embedding a private IPv4" do + stub_dns_resolution("64:ff9b::a9fe:a9fe") # NAT64 -> 169.254.169.254 (AWS metadata) + assert_nil SsrfProtection.resolve_public_ip("nat64-metadata.example.com") + end + + test "blocks NAT64 addresses embedding a carrier-grade NAT IPv4" do + stub_dns_resolution("64:ff9b::6440:1") # NAT64 -> 100.64.0.1 + assert_nil SsrfProtection.resolve_public_ip("nat64-cgnat.example.com") + end + + test "allows NAT64 addresses embedding a public IPv4" do + # DNS64 legitimately synthesizes these for public sites on IPv6-only hosts. + stub_dns_resolution("64:ff9b::808:808") # NAT64 -> 8.8.8.8 + assert_not_nil SsrfProtection.resolve_public_ip("nat64-public.example.com") + end + + test "blocks local-use NAT64 addresses embedding a private IPv4 (RFC8215)" do + stub_dns_resolution("64:ff9b:1::a00:1") # local-use NAT64 -> 10.0.0.1 + assert_nil SsrfProtection.resolve_public_ip("nat64-local.example.com") + end + + test "allows local-use NAT64 addresses embedding a public IPv4 (RFC8215)" do + stub_dns_resolution("64:ff9b:1::808:808") # local-use NAT64 -> 8.8.8.8 + assert_not_nil SsrfProtection.resolve_public_ip("nat64-local-public.example.com") + end + + test "blocks 6to4 and Teredo transition addresses" do + stub_dns_resolution("2002:a9fe:a9fe::") # 6to4 embedding 169.254.169.254 + assert_nil SsrfProtection.resolve_public_ip("sixtofour.example.com") + + stub_dns_resolution("2001::1") # Teredo + assert_nil SsrfProtection.resolve_public_ip("teredo.example.com") + end + + test "blocks IPv6 benchmarking addresses (RFC5180)" do + stub_dns_resolution("2001:2::1") + assert_nil SsrfProtection.resolve_public_ip("v6-benchmark.example.com") + end + + test "blocks IPv6 loopback, ULA, and multicast" do + stub_dns_resolution("::1") + assert_nil SsrfProtection.resolve_public_ip("v6-loopback.example.com") + + stub_dns_resolution("fd00:ec2::254") # AWS IMDSv6 (ULA) + assert_nil SsrfProtection.resolve_public_ip("v6-imds.example.com") + + stub_dns_resolution("ff02::1") + assert_nil SsrfProtection.resolve_public_ip("v6-multicast.example.com") + end + + test "allows public IPv6 addresses" do + stub_dns_resolution("2606:4700:4700::1111") + assert_not_nil SsrfProtection.resolve_public_ip("v6-public.example.com") + end end diff --git a/test/models/storage/no_reuse_test.rb b/test/models/storage/no_reuse_test.rb index e876fe50ca..1142e2a2eb 100644 --- a/test/models/storage/no_reuse_test.rb +++ b/test/models/storage/no_reuse_test.rb @@ -57,6 +57,32 @@ class Storage::NoReuseTest < ActiveSupport::TestCase ).count end + test "purge touches the record to invalidate cache" do + card = @board.cards.create!(title: "Card", creator: users(:david)) + card.image.attach(io: file_fixture("moon.jpg").open, filename: "moon.jpg", content_type: "image/jpeg") + + original_updated_at = card.reload.updated_at + + travel 1.second do + card.image.purge + end + + assert card.reload.updated_at > original_updated_at + end + + test "purge_later touches the record to invalidate cache" do + card = @board.cards.create!(title: "Card", creator: users(:david)) + card.image.attach(io: file_fixture("moon.jpg").open, filename: "moon.jpg", content_type: "image/jpeg") + + original_updated_at = card.reload.updated_at + + travel 1.second do + card.image.purge_later + end + + assert card.reload.updated_at > original_updated_at + end + test "purge_later does not purge blob when still attached elsewhere" do file = file_fixture("moon.jpg") blob = ActiveStorage::Blob.create_and_upload! \ diff --git a/test/models/webhook/delivery_test.rb b/test/models/webhook/delivery_test.rb index 8d40c44178..4fc6b2870f 100644 --- a/test/models/webhook/delivery_test.rb +++ b/test/models/webhook/delivery_test.rb @@ -45,6 +45,45 @@ class Webhook::DeliveryTest < ActiveSupport::TestCase assert_not delivery.succeeded?, "the response can't have an error" end + test "sanitized_request strips signature header" do + delivery = webhook_deliveries(:successfully_completed) + delivery.update!(request: { + headers: { + "User-Agent" => "fizzy/1.0.0 Webhook", + "Content-Type" => "application/json", + "X-Webhook-Signature" => "super-secret-signature", + "X-Webhook-Timestamp" => "2025-12-05T19:36:35.401Z" + } + }) + + result = delivery.sanitized_request + assert_equal %w[ User-Agent Content-Type X-Webhook-Timestamp ], result[:headers].keys + assert_not result[:headers].key?("X-Webhook-Signature") + end + + test "sanitized_request returns nil when request is blank" do + delivery = webhook_deliveries(:pending) + delivery.update_columns(request: nil) + + assert_nil delivery.sanitized_request + end + + test "response_summary returns code and error" do + delivery = webhook_deliveries(:successfully_completed) + delivery.update!(response: { code: 200, error: nil }) + + result = delivery.response_summary + assert_equal 200, result[:code] + assert_nil result[:error] + end + + test "response_summary returns nil when response is blank" do + delivery = webhook_deliveries(:pending) + delivery.update_columns(response: nil) + + assert_nil delivery.response_summary + end + test "deliver_later" do delivery = webhook_deliveries(:pending) @@ -434,11 +473,4 @@ class Webhook::DeliveryTest < ActiveSupport::TestCase assert_equal 200, delivery.response[:code] assert delivery.succeeded? end - - private - def stub_dns_resolution(*ips) - dns_mock = mock("dns") - dns_mock.stubs(:each_address).multiple_yields(*ips) - Resolv::DNS.stubs(:open).yields(dns_mock) - end end diff --git a/test/system/card_refresh_test.rb b/test/system/card_refresh_test.rb new file mode 100644 index 0000000000..ac7eb51ff2 --- /dev/null +++ b/test/system/card_refresh_test.rb @@ -0,0 +1,84 @@ +require "application_system_test_case" + +class CardRefreshTest < ApplicationSystemTestCase + include ActionView::RecordIdentifier + + setup do + sign_in_as(users(:david)) + Current.user = users(:kevin) + @card = cards(:layout) + end + + test "a broadcast refresh shows card changes made elsewhere" do + visit card_url(@card) + assert_selector "h1", text: @card.title + + update_card_elsewhere + + assert_selector "h1", text: "Retitled elsewhere", wait: 5 + assert_text "Description updated elsewhere" + end + + test "a broadcast refresh preserves an edit in progress" do + visit card_url(@card) + click_on @card.title + + within_edit_frame do + fill_in_lexxy with: "Draft description in progress" + end + + update_card_elsewhere + + # The title change's system comment appearing proves the refresh reached the page. + assert_text "changed the title", wait: 5 + within_edit_frame do + assert_selector "lexxy-editor", text: "Draft description in progress" + end + assert_no_text "Description updated elsewhere" + end + + test "canceling an edit reveals card changes made elsewhere during the edit" do + visit card_url(@card) + click_on @card.title + within_edit_frame { assert_selector "form" } + + update_card_elsewhere + assert_text "changed the title", wait: 5 + + send_keys :escape + + assert_selector "h1", text: "Retitled elsewhere" + assert_text "Description updated elsewhere" + end + + test "a broadcast refresh shows card changes after an edit is canceled" do + visit card_url(@card) + click_on @card.title + within_edit_frame { assert_selector "form" } + + send_keys :escape + assert_selector "a.card__title-link", text: @card.title + + update_card_elsewhere + + assert_selector "h1", text: "Retitled elsewhere", wait: 5 + assert_text "Description updated elsewhere" + end + + private + def update_card_elsewhere + wait_for_cable_subscriptions + @card.update!(title: "Retitled elsewhere", description: "Description updated elsewhere") + perform_enqueued_jobs only: Turbo::Streams::BroadcastStreamJob + end + + # A broadcast sent before the page's subscriptions are confirmed is lost. + def wait_for_cable_subscriptions + assert_selector "turbo-cable-stream-source[connected]", visible: :all + assert_no_selector "turbo-cable-stream-source:not([connected])", visible: :all + end + + def within_edit_frame(&block) + within "##{dom_id(@card, :edit)}", &block + end +end diff --git a/test/system/smoke_test.rb b/test/system/smoke_test.rb index 467483fc11..a545cf4867 100644 --- a/test/system/smoke_test.rb +++ b/test/system/smoke_test.rb @@ -93,11 +93,4 @@ class SmokeTest < ApplicationSystemTestCase column_el.find(".cards__expander-count", text: cards_count + 1) assert_equal("Triage", card.reload.column.name) end - - private - def fill_in_lexxy(selector = "lexxy-editor", with:) - editor_element = find(selector) - editor_element.set with - page.execute_script("arguments[0].value = '#{with}'", editor_element) - end end diff --git a/test/test_helper.rb b/test/test_helper.rb index b1f8137610..b4289ec7b1 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -8,6 +8,11 @@ require "mocha/minitest" require "turbo/broadcastable/test_helper" +unless [ "0", "false" ].include?(ENV["CI_PROGRESS_BAR"]) + require "minitest/reporters" + Minitest::Reporters.use! Minitest::Reporters::ProgressReporter.new(detailed_skip: false) +end + WebMock.allow_net_connect! VCR.configure do |config| @@ -45,9 +50,19 @@ class TestCase fixtures :all include ActiveJob::TestHelper - include ActionTextTestHelper, CachingTestHelper, CardTestHelper, ChangeTestHelper, SessionTestHelper + include ActionTextTestHelper, CachingTestHelper, CardTestHelper, ChangeTestHelper, DnsTestHelper, SessionTestHelper include Turbo::Broadcastable::TestHelper + # Jobs must carry their own account context via AccountTenanted, + # not rely on Current.account leaking from the test setup. + def perform_enqueued_jobs(...) + saved_account = Current.account + Current.account = nil + super + ensure + Current.account = saved_account + end + setup do Current.account = accounts("37s") end diff --git a/test/test_helpers/dns_test_helper.rb b/test/test_helpers/dns_test_helper.rb new file mode 100644 index 0000000000..34f4c54389 --- /dev/null +++ b/test/test_helpers/dns_test_helper.rb @@ -0,0 +1,15 @@ +module DnsTestHelper + WEB_PUSH_PUBLIC_TEST_IP = "142.250.185.206" # stable public IP for web push DNS stubs in tests + + private + + def stub_dns_resolution(*ips) + dns_mock = mock("dns") + dns_mock.stubs(:each_address).multiple_yields(*ips) + Resolv::DNS.stubs(:open).yields(dns_mock) + end + + def stub_web_push_dns_resolution + stub_dns_resolution(WEB_PUSH_PUBLIC_TEST_IP) + end +end