mirror of
https://github.com/PerpetualSoftware/pad.git
synced 2026-09-20 17:43:26 +00:00
504d348917c2fb8ed2c139bbbc352e07fccae19a
57 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
6461aafd16 |
feat(store): attachments table + Attachment model (TASK-869) (#286)
Adds the schema groundwork for inline images and file uploads — see DOC-865 (Attachments — architecture & migration design). - migrations/047_attachments.sql — SQLite migration. Table + 4 indexes (workspace, item, hash, parent). Partial indexes on workspace/item/parent match the items table convention. The hash index is full (not partial) so dedupe can resurrect a soft-deleted blob if the same bytes are re-uploaded without writing a duplicate. - pgmigrations/026_attachments.sql — Postgres mirror with BIGINT for size_bytes; same partial-index pattern. - internal/models/attachment.go — Go model with all columns. Uses pointer types for nullable columns (item_id, width, height, parent_id, variant, deleted_at) so JSON omitempty works correctly. No call sites yet — purely schema groundwork. Verified the migration runs cleanly on a fresh install and on the live dev DB. Parent: PLAN-866. |
||
|
|
7cda0d7896 |
feat: rebrand to Perpetual Software + new tagline (IDEA-832) (#273)
Migrates from xarmian/pad to PerpetualSoftware/pad across the entire
repo and updates the product subtitle to "Collaborate with your AI
agents".
Go module rename
- go.mod: github.com/xarmian/pad → github.com/PerpetualSoftware/pad
- All Go imports updated across cmd/pad, internal/{cli,server,store,
models,collections,items,events,metrics,webhooks} (~130 files)
- Test fixtures with the literal repo slug ("xarmian/pad" in JSON
shapes, SSH/HTTPS git URL strings, workspace_context fixtures)
also updated, including the secondary repo entry
(xarmian/pad-web → PerpetualSoftware/pad-web — pad-web was also
moved to the org per branch context)
Docs / config
- README badges, install instructions, brew tap, Docker image, source
build path, sponsor link (sponsor link kept as personal @xarmian)
- Subtitle: "Project management for developers and AI agents." →
"Collaborate with your AI agents." (README, manifests, web layout
meta, .goreleaser homebrew description)
- CONTRIBUTING.md, SECURITY.md, skills/INSTALL.md
- .goreleaser.yaml: homebrew_casks owner, GHCR image, release github
owner, cosign cert-identity regex, comments
- .github/workflows/release.yml: tap/release comments
- deploy/k8s/deployment.yaml: container image
- docs/deployment.md: clone URL
- web/static/{site.webmanifest,manifest.json}: description
- web/src/routes/+layout.svelte: meta description + og:description
Brew tap path is PerpetualSoftware/tap/pad (CamelCase, matches
GitHub user case). GHCR image is ghcr.io/perpetualsoftware/pad
(lowercased per GHCR's URL normalization). CODEOWNERS @xarmian and
FUNDING.yml github: xarmian intentionally retained — those are the
personal maintainer / sponsor account, separate from the org repo.
Verification: go build ./..., go test ./... (all pkgs pass), web
build, and make install all clean (TASK-844, TASK-845).
|
||
|
|
afe721d202 |
feat(cli): add Cloud mode to pad init, drop Docker option (TASK-837, TASK-838) (#272)
Merging despite Go (PostgreSQL) red — those failures (TestListItems_FTS_HyphenatedSearchTerm/task-five + TestAdminBillingStats_SidecarSidecarError_DegradesToLocalOnly TempDir cleanup race) are pre-existing on main and tracked in BUG-842. Codex reviewed in 3 rounds (round 1 clean → round 2 found a real semantic bug → fix → round 3 clean). Tests, vet, and lint all green; remaining check failures are documented pre-existing. |
||
|
|
dd381e1066 |
chore: delete 5 unwired document handlers (TASK-769) (#252)
* chore: delete 5 unwired document handlers (TASK-769)
internal/server/handlers_documents.go had 5 dead HTTP handlers that
were drafted as Documents-v1 extensions but never wired into the
router (server.go:509 already labels Documents itself as "v1, will be
replaced by items in Phase 2"):
- handleQuickSave (POST /documents/quick-save) — title-based upsert
- handleBulkRead (POST /documents/bulk-read) — multi-doc fetch by IDs
- handleGetBacklinks (GET /documents/{id}/backlinks)
- handleGetLinks (GET /documents/{id}/links)
- handleGetContext (GET /documents/context?type=)
Investigation confirmed zero consumers:
- Not registered in setupRouter (`grep -n "QuickSave\|BulkRead\|Backlinks\|GetLinks\|GetContext" server.go` → empty).
- Not used by the SvelteKit frontend (`web/src/`).
- Not used by the CLI (`internal/cli/`).
- Pre-launch repo, no fork or downstream that could be relying on them.
Delete scope is intentionally limited to the HTTP handlers. The
underlying `Store.QuickSave / BulkRead / GetBacklinks / GetLinks /
GetContext` methods stay — they're tested at the store level
(internal/store/store_test.go) and preserve optionality if Phase 2
work needs to revive any of these features. `models.QuickSave` stays
for the same reason.
After this lands, IDEA-732's lint catalog is fully cleared on main
(staticcheck SA* + U1000 returns zero). TASK-771 (flip CI
only-new-issues=false) becomes safe.
Verified:
- `go build ./...` clean
- `go vet ./...` clean
- `go test ./...` all pass
- `staticcheck -checks "SA*,U1000" ./...` clean
- All `import "strings"` etc. still used elsewhere in file
Parent: PLAN-644.
* chore: also delete now-test-only document store helpers (TASK-769)
Codex round 1 on PR #252 flagged that the document-store helpers
retained for "Phase 2 optionality" are now exclusively kept alive by
their own store tests — Store.QuickSave, BulkRead, GetBacklinks,
GetLinks, GetContext are not called by any production code path after
the handler deletions in the previous commit. Same for the
models.QuickSave struct.
Pre-launch with no external consumers, optionality preservation has a
real cost (dead code on main, ongoing test maintenance). When Phase 2
needs any of these capabilities it is cheaper to re-derive them
against the Items model than to drag dead Documents-v1 plumbing
forward. So delete them now.
Removed:
- internal/store/documents.go: QuickSave (38 lines), BulkRead (28),
GetBacklinks (15), GetLinks (28), GetContext (41).
- internal/models/document.go: QuickSave struct.
- internal/store/store_test.go: TestQuickSave (38 lines), TestBulkRead
(16), TestDocumentLinking (29), TestContext (23).
Kept:
- TestDocumentLinkRename — exercises UpdateDocument's internal
link-rewriting path, not any of the deleted helpers.
- GetDocumentByTitle — still used by TestDocumentLinkRename.
- The full CRUD/restore handlers and their store methods — these are
still wired into setupRouter and have their own coverage.
Verified:
- `go build ./...` clean
- `go vet ./...` clean
- `go test ./...` all pass (TestDocumentLinkRename and the wider doc
CRUD/version/activity tests still cover the surviving paths).
- `staticcheck -checks "SA*,U1000" ./...` clean
- No new unused imports introduced (links package is still used by
documents.go for ReplaceTitle in UpdateDocument).
Parent: PLAN-644.
* chore: drop GetDocumentByTitle and refactor TestDocumentLinkRename (TASK-769)
Codex round 2 caught the chain — after deleting QuickSave/BulkRead/
GetBacklinks/GetLinks/GetContext, Store.GetDocumentByTitle was kept
alive by exactly one test (TestDocumentLinkRename), which was
re-fetching by title only because the test ignored the *Document
already returned by createTestDoc.
Use the createTestDoc return value instead, then drop GetDocumentByTitle
from the store. Same idea, cleaner test, one fewer test-only API on
the store. The rename behaviour (the actual thing under test) is
unchanged.
Verified:
- `go build ./...` clean
- `go test ./internal/store` and `./internal/server` pass
- `staticcheck -checks "SA*,U1000" ./...` still clean
Parent: PLAN-644.
* chore: drop now-orphaned links.Extract (TASK-769)
Codex round 3 caught the next link in the chain: after Store.GetLinks
was deleted, links.Extract had no remaining callers — links.ReplaceTitle
is the only Extract-package function still used (by UpdateDocument's
rename rewrite). The linkPattern regex was only used by Extract.
Drop linkPattern, the regexp import, and Extract itself. Leaves
ReplaceTitle and its private string helpers (replaceAll, indexOf)
intact.
The cleanup chain ends here: ReplaceTitle is still wired into a live
production path (Documents-v1 rename), and the supporting helpers
have no other roles to inherit.
Verified:
- `go build ./...` clean
- `go test ./internal/store` and `./internal/server` pass
- `staticcheck -checks "SA*,U1000" ./...` clean
Parent: PLAN-644.
|
||
|
|
157ca4e88f |
chore: bump Go toolchain to 1.26 (TASK-763) (#247)
* chore: bump Go toolchain to 1.26 (TASK-763) Bump Go from 1.25 to 1.26 across all toolchain pins: - go.mod — go 1.25.0 → go 1.26.0 - Dockerfile — golang:1.25-alpine → golang:1.26-alpine - .github/workflows/ci.yml — three setup-go steps (Go, Go-Postgres, E2E jobs) - .github/workflows/release.yml — release pipeline No `toolchain` directive: the repo is pre-launch with no external contributors yet, so we set the floor where we want it (hard requirement). Verified locally before commit: - golangci-lint v2.11.4 builds and runs under Go 1.26.2 (pinned in CI) - golang:1.26-alpine and 1.26.2-alpine images present on Docker Hub - go build ./... clean - go vet ./... clean - go test ./... all pass Parent: PLAN-644 (OSS Repo Hygiene and Launch Polish). * chore: gofmt -w under Go 1.26 (TASK-763) Apply Go 1.26's gofmt to the codebase. ~41 files reformatted, all struct-tag whitespace realignment — no semantic changes. Verified: - gofmt -l ./cmd ./internal returns empty after - go build ./... still clean - go test ./... still passes (run before commit) Bundling the gofmt diff with the toolchain bump in the same PR because the formatting drift is a direct consequence of moving from 1.25 to 1.26; splitting them creates a mandatory two-PR ordering for no value. Parent: PLAN-644. * docs: bump documented Go floor to 1.26 (TASK-763) Match go.mod's hard 1.26.0 requirement in the source-build instructions. Caught by Codex review round 1 on PR #247. - README.md:158 — "Go 1.25+" → "Go 1.26+" - CONTRIBUTING.md:9 — "Go 1.25+" → "Go 1.26+" |
||
|
|
119e2d8aa2 |
feat(billing): payment-failed email endpoint + template (TASK-712 1 of 2) (#232)
* feat(billing): payment-failed email endpoint + template (TASK-712 1 of 2) Pairs with pad-cloud's invoice.payment_failed webhook handler (shipping next) to give paying users a chance to update their card before dunning exhausts and the subscription cancels. pad owns the Maileroo integration and the user→email mapping; the sidecar forwards the invoice metadata here. Changes: - email.Sender.SendPaymentFailed — new template (HTML + plain). Subject "Your Pad payment couldn't be processed"; body names the amount + next retry date when provided, falls back to generic copy when Stripe omits them, and CTAs to the billing portal so the user can update their card. Transactional (no unsubscribe link) — users who want the emails to stop either fix their card or cancel the subscription. - POST /api/v1/admin/payment-failed — new cloud-secret-gated endpoint (handlers_cloud.go). Accepts stripe_customer_id + optional pre- formatted amount_display + next_retry_display. Looks up the user, sends the email, logs a payment_failed_email_sent audit entry. Returns 200 + email_sent=false with a reason string for every non-error skip (unknown customer, no email on file, Maileroo not configured) so the sidecar never rolls back the Stripe webhook over an email failure. Returns 200 + email_sent=false + reason=send_failed when Maileroo itself errors — still no rollback. - Registered the path in cloudAdminPaths, the server router, and the CloudAdmin rate limiter so the sidecar's calls share the same rate bucket as /plan + /stripe-customer-id. - ActionPaymentFailedEmailSent audit constant for the new entry. - Three focused tests: cus_ prefix validation, unknown-customer 200, and email-not-configured 200. Added an entry to the cloud-mode gate table-driven test to confirm /admin/payment-failed also 404s when cloud mode is off. Parent: PLAN-645 (Pad Cloud Beta Readiness). TASK-712 bullet 3, pad side. pad-cloud's handlePaymentFailed wiring ships in a sibling PR. * fix(billing): audit every outcome; target user ID; add send-path tests (Codex round 1) Addresses PR #232 round 1 findings: MEDIUM — payment-failed handler only wrote an audit row on the actual send attempt, so no_customer / no_email_address / email_not_configured skip paths left no durable trail. Consolidated the audit + response into a single auditAndRespond closure called from every outcome branch, so operators can always reconstruct whether (and why) a customer was notified during dunning reconciliation. MEDIUM — audit UserID was set to actorID, which is empty for sidecar calls. /audit-log?user=<target-user-id> would never surface these events. Now set UserID to targetUser.ID whenever we have one; the no_customer branch still writes a row but with empty UserID (filtered only by action + stripe_customer_id metadata). Moved actor identity into an actor_is_admin metadata field instead. LOW — test coverage was thin: no assertion on the most important contract ("return 200 with reason=send_failed and still record the attempt"), no test of the happy send path, no audit-log assertions. Added email.Sender.SetEndpoint (exported, test-only — comment says so) so tests can point the Sender at a mock Maileroo server, plus three new tests: - TestPaymentFailed_HappyPath_SendsAndAudits - TestPaymentFailed_MailerooError_Returns200_SendFailed_AndAudits - TestPaymentFailed_UnknownCustomer_AuditsWithoutUserID The first two verify audit metadata per outcome; the third proves unknown-customer cases still leave a findable audit row. Thread-safety fix as a side-effect: Send/SendAs were reading s.endpoint outside the sender's RWMutex — fine before the mutable SetEndpoint existed, now a data race. Pulled the endpoint read into the same RLock scope as fromAddr/fromName. * fix: capture admin actor ID + audit-log formatter for payment_failed (Codex round 2) Addresses PR #232 round 2 findings: MEDIUM — auditAndRespond recorded actor_is_admin=true/false but not which admin. For manual operator-triggered calls, that meant the audit trail could not answer "who sent the dunning email?" when multiple admins touched the endpoint. Added admin_actor_id to the metadata whenever the authenticated caller has role=admin. Sidecar calls with no authenticated user still have no admin_actor_id, which correctly distinguishes them from manual admin operations. LOW — web/src/routes/console/admin/audit-log/+page.svelte falls back to "first 3 metadata keys" when no formatter exists for an action, which could hide the important reason/sent fields. Added a dedicated case for payment_failed_email_sent that renders either "sent (cus_...)" or "skipped: <reason> (cus_...)" depending on the outcome, matching the terse display style of the other switch cases. * fix(audit-log): distinguish send_failed from skip; surface admin actor (Codex round 3) Addresses PR #232 round 3 LOWs: - The formatter lumped every sent=false outcome under 'skipped', which conflates a genuine Maileroo delivery failure with a pre-send skip. Now: sent → 'sent (...)'; send_failed → 'send failed (...)'; other reasons → 'skipped (<reason>) (...)'. - admin_actor_id was recorded in metadata but invisible in the UI: the User column shows the target user via a.user_id. Appended 'by admin:<id>' to the formatted string whenever admin_actor_id is present, so manual operator calls are attributable at a glance. Sidecar calls have no admin_actor_id and render without the suffix. * fix(audit-log): register payment_failed_email_sent in action filter dropdown (Codex round 4) The backend emits payment_failed_email_sent and the custom formatter knows how to render it, but the audit-log page's ACTION_TYPES / ACTION_LABELS registry omitted the action, so admins couldn't filter for these events from the dropdown — undercutting the dunning reconciliation workflow this PR is adding. Added 'payment_failed_email_sent' to the ACTION_TYPES list and 'Payment Failed Email' to ACTION_LABELS. |
||
|
|
775dd89fdc |
feat(cloud): add /admin/stripe-event-unmark endpoint (TASK-736 / 1 of 2) (#228)
* feat(cloud): add /admin/stripe-event-unmark endpoint (TASK-736 / 1 of 2) Parent: PLAN-645. Pair with pad-cloud follow-up. * fix(cloud): add processed_at race protection + audit log per Codex review (round 1) |
||
|
|
46fa72ca0f |
feat(server): log session IP changes, add optional PAD_IP_CHANGE_ENFORCE=strict (TASK-666) (#191)
* feat(server): log session IP changes, add optional PAD_IP_CHANGE_ENFORCE=strict (TASK-666)
Sessions stored a client IP at creation but never rechecked it. A stolen
cookie could be used from anywhere with no signal to the owner. This
change adds mid-lifetime IP-change detection without breaking legitimate
mobility (mobile roaming, VPN toggles, carrier NAT) by default.
- New audit action ActionSessionIPChanged captures {old_ip, new_ip} in
the audit metadata. Visible via the existing /api/v1/admin/audit-log.
- handleSessionIPChange wired into both SessionAuth (cookies) and
TokenAuth (padsess_ bearer). After UA check passes, compares stored
session IP to clientIP(r). On mismatch:
- log one audit row
- update the stored session IP so we don't spam the log
- strict mode: DeleteSession + 401 "session_ip_changed"
- default mode: let the request through
- Store.UpdateSessionIP lets middleware refresh the recorded IP without
tearing down the session.
- PAD_IP_CHANGE_ENFORCE=strict env var + ip_change_enforce TOML key +
Server.SetIPChangeEnforce setter (case-insensitive, trims whitespace).
- Table-driven tests cover log-only, strict rejection with session
destruction, and setter parsing edge cases.
Parent: PLAN-643 (OSS Security Hardening).
* fix(server): dedupe session-IP-change audit via CAS, handle browser vs API paths per Codex review
Addresses two P2 comments on PR #191:
1. Race: parallel requests after an IP change could each emit
ActionSessionIPChanged before any of them updated the stored IP,
producing duplicate audit rows for a single transition.
- Replace UpdateSessionIP with UpdateSessionIPIfEquals (compare-and-set
on ip_address). Only the request that actually rotates the stored
value logs; concurrent siblings lose the CAS and skip logging.
- New test TestSessionIPChange_CASDedupesRace fires 20 concurrent
requests from the new IP and asserts exactly 1 audit row.
2. Strict-mode 401 on non-API paths:
- In current routing the SPA is mounted on the root router outside
the auth Group, so SessionAuth only fires for /api/* in practice.
The original concern about JSON 401s on browser navigation doesn't
surface today, but defense-in-depth keeps the code forward-safe:
restructure handleSessionIPChange to return a four-state outcome
(Continue / AllowedLogged / Revoked / Terminated) and only write
the JSON 401 on /api/* paths. Revoked + non-API falls through
unauthenticated so a future SPA-in-group configuration would still
render a login screen instead of raw JSON.
- Clear the session cookie (MaxAge=-1) in strict rejection so the
browser stops sending the now-revoked token on the next request.
TestSessionIPChange_StrictClearsCookies verifies the Set-Cookie.
Parent: PLAN-643 (OSS Security Hardening), TASK-666.
* fix(server): strict mode destroys session atomically, never rotate stored IP when destroying (TASK-666)
Addresses Codex P1 on PR #191: previously we rotated the session's stored
ip_address via UpdateSessionIPIfEquals BEFORE attempting DeleteSession.
If the DELETE failed (transient DB error) the row remained alive —
rebound to the attacker's new IP — so follow-up requests saw stored IP
== client IP and passed handleSessionIPChange's "match, no-op" branch.
That silently defeated strict enforcement.
- New Store.DeleteSessionIfExists returns (bool, error) to serve as the
CAS primitive for strict mode: only the caller whose DELETE affected a
row emits the audit entry, and a DB error fails closed (500 — "Unable
to validate session") rather than letting the request through.
- handleSessionIPChange splits into two paths:
* log-only mode: UpdateSessionIPIfEquals for CAS dedup (unchanged)
* strict mode: DeleteSessionIfExists is the CAS; stored IP is NEVER
rotated so any failure leaves the session bound to the OLD IP and
subsequent requests from the new IP still mismatch + still reject.
- TestSessionIPChange_StrictDestroysSessionAtomically regression test
verifies a second request from the new IP with the same token still
fails after the first strict-mode rejection.
Parent: PLAN-643 (OSS Security Hardening).
* fix(server): exempt public API paths from strict IP-change termination (TASK-666)
Addresses Codex P2 on PR #191: SessionAuth runs for every /api/* path,
including public endpoints like /api/v1/auth/login, /api/v1/auth/register,
/api/v1/health, /api/v1/s/* (share links), and /api/v1/plan-limits. In
strict mode, a stale session cookie on those requests was rejected with
a 401 session_ip_changed BEFORE the public handler could run — the user
literally couldn't log back in because their own stale cookie blocked
the login call.
- Extract isPublicAPIPath as a shared helper between RequireAuth and
handleSessionIPChange so they can't drift out of sync.
- handleSessionIPChange strict-mode flow now: destroy session + clear
cookies + audit log (unchanged), then for public API paths return
Revoked so the handler still runs. For authenticated-only API paths
still return Terminated (401). For non-API paths return Revoked for
the SPA fallback.
- Updated TokenAuth Revoked handler to match: pass through unauth on
public paths, 401 on authenticated-only.
- TestSessionIPChange_StrictAllowsPublicAPIPaths regression test:
a stale session cookie on /api/v1/auth/login must NOT produce
session_ip_changed; /api/v1/plan-limits must still return 200.
Parent: PLAN-643 (OSS Security Hardening).
* fix(server): short-circuit SessionAuth on token auth + fix IPv6 clientIP parsing (TASK-666)
Addresses two more Codex comments on PR #191:
P1 — SessionAuth 401'd API-token-authenticated requests:
TokenAuth sets currentUser for user-owned tokens AND tokenWorkspaceID
for legacy workspace-scoped tokens. SessionAuth short-circuited only on
currentUser, so a workspace-scoped-token request that happened to carry
a stale session cookie with a mismatched IP would be rejected by the
IP-change strict path before RequireAuth could honor the token. Extend
the short-circuit to also check tokenWorkspaceID; either signal is
enough to say "token auth already succeeded, skip cookie validation".
P2 — clientIP mangled IPv6 addresses:
clientIP used strings.LastIndex(":") on RemoteAddr. For bare IPv6
addresses like "2001:db8::1" (which TrustedProxyRealIP writes verbatim
from X-Forwarded-For, no brackets/port), that strips the final hextet
to "2001:db8:" — unusable for comparison in the new IP-change audit
path and incorrect for rate-limit keys too. Switch to net.SplitHostPort
which handles both "host:port" and "[ipv6]:port", falling back to the
raw RemoteAddr when no port is present (the trusted-proxy rewrite
case).
Tests:
- TestClientIP_IPv6NotMangled covers IPv4 w/wo port, bracketed IPv6,
bare IPv6 (no port, no brackets), and loopback forms.
- TestSessionAuth_ShortCircuitsOnAPITokenAuth exercises the worst case:
strict mode + valid API token + stale session cookie + new client IP.
Request must succeed (token wins) and NO new session_ip_changed audit
row must appear.
Parent: PLAN-643 (OSS Security Hardening).
* fix(server): canonicalize IPs before session-IP-change comparison (TASK-666)
Addresses Codex P2 on PR #191: raw-string comparison of session.IPAddress
vs clientIP(r) would fire session_ip_changed spuriously when the same
IPv6 address arrived in different valid textual representations (the
trusted-proxy path writes X-Forwarded-For verbatim, and different hops
normalize differently — "2001:0db8::1" vs "2001:db8::1" etc.).
- canonicalIP helper: net.ParseIP + stringify to collapse equivalent
IPv6 forms (compressed vs expanded, case, leading zeros) and IPv4-in-
IPv6 into a single canonical string. Non-parseable inputs pass through
unchanged so debug/malformed values behave predictably.
- handleSessionIPChange compares and logs the canonical forms. The CAS
still passes session.IPAddress (the raw stored value) to the DB — the
compare-and-set is about row identity — but the new IP written in is
the canonical form so future comparisons are stable.
- TestCanonicalIP covers empty, IPv4, shorthand "::1", expanded 8-group
equivalent, mixed-case 2001:DB8::1, fully expanded 2001:0db8:…:0001,
and non-IP fallback.
Parent: PLAN-643 (OSS Security Hardening).
|
||
|
|
33b3f21a2c |
feat(auth): expire workspace invitations after 14 days (TASK-649) (#176)
* feat(auth): expire workspace invitations after 14 days (TASK-649)
A workspace invite code lives forever until accepted. A leaked code —
email forwarding, stale screenshot, git history — lets any attacker who
registers the invitee's email claim the workspace seat months or years
later.
Introduce a 14-day default expiry:
- New migration (SQLite 044 + Postgres 024) adds expires_at TEXT to
workspace_invitations with an index, backfilling existing rows to
created_at + 14 days so old codes also age out.
- Store CreateInvitation sets expires_at = now + InvitationTTL;
GetInvitation/GetInvitationByCode/ListWorkspaceInvitations read and
populate ExpiresAt. Legacy rows with NULL expires_at are treated as
non-expiring (backward compat for codes created before the migration).
- Model gains ExpiresAt *time.Time and an IsExpired() helper, nil-safe.
- handleAcceptInvitation returns 410 Gone "expired" for expired codes.
- handleRegister (invitation path) returns 410 Gone with the same
message so the signup flow surfaces expiry distinctly from "invalid
code".
Tests: models.TestWorkspaceInvitation_IsExpired covers nil/past/future
plus a nil-receiver safety check.
Parent: PLAN-643 (OSS Security Hardening).
* fix(store): backfill invitation expires_at in RFC3339 per Codex P1
Codex caught that the first cut of migration 044 (SQLite) and 024 (Postgres)
emitted space-separated timestamp strings, which parseTime silently rejects —
legacy invitations would all show up as zero-time ExpiresAt and be treated
as already-expired right after upgrade.
- SQLite: switch to strftime('%Y-%m-%dT%H:%M:%SZ', created_at, '+14 days').
- Postgres: use to_char(..., 'YYYY-MM-DD"T"HH24:MI:SS"Z"').
Add regression tests:
- TestCreateInvitation_SetsExpiresAt — fresh invitations get expiry ~14d out.
- TestMigration044_BackfillProducesRFC3339 — inserts a legacy row with NULL
expires_at, applies the same backfill expression as the migration, and
verifies the round-tripped ExpiresAt is non-zero, parses correctly, and
is ~InvitationTTL after created_at.
* fix(store): drop AT TIME ZONE cast in PG backfill per Codex P2
Codex flagged that '(timestamp + INTERVAL) AT TIME ZONE UTC' yields a
timestamptz, and to_char(timestamptz, ...) renders using the session's
TimeZone — on a non-UTC Postgres instance, legacy invitations get
offset-shifted values mislabeled with a 'Z' suffix.
created_at is already stored as UTC text, so casting it to a naive
timestamp and doing the interval math without further conversion is
both correct and tz-independent. to_char on a plain timestamp uses the
stored value as-is and the hardcoded 'Z' suffix labels it accurately.
|
||
|
|
9e7daa779f |
feat: tie done-detection to the board group-by field (TASK-604) (#140)
* feat: tie done-detection to the board group-by field
Closes TASK-604. Make "is this item done?" follow the collection's
settings.board_group_by rather than the hardcoded `status` key. If a
collection's board is grouped by `resolution`, then resolution's
terminal options drive dashboard counts, progress bars, changelog,
and starred-items filtering. Collections without an explicit
board_group_by (every collection today) continue to behave exactly
as before because the fallback resolves to `"status"`.
Why this shape
- No ambiguity: one field per collection wins. No reconciling
"status says in-progress, resolution says fixed."
- One JSON path to swap: every $.status query becomes
$.<done_field>. No dynamic OR across schema-discovered fields.
- Matches the mental model: the field you organize the board by is
the field that represents the item's current state. The old
mismatch (board grouped by X, "done" count from status) is a
latent bug this resolves.
- Non-breaking: board_group_by defaults to nil → DoneFieldKey
returns "status" → behavior identical to pre-TASK-604.
Model layer (internal/models/terminal.go)
- DoneFieldKey(schema, settings) resolves the done-field key with a
fallback chain: valid select on schema → that field, else "status".
- TerminalValuesForDoneField(schema, settings) returns (fieldKey,
values) honoring the done field, falling back to
DefaultTerminalStatuses when the resolved field has no
terminal_options.
- TerminalPlaceholdersForDoneField(schema, settings) is the SQL
convenience returning (fieldKey, placeholders, args).
- IsTerminalItem(fields, schema, settings) is the canonical
Go-side membership check.
- Legacy API (TerminalStatusesFromSchema, IsTerminalStatus,
TerminalStatusPlaceholders) kept as back-compat wrappers that
delegate with empty settings — resolve to "status" for callers
that don't have settings in scope yet.
SQL callers migrated to the new helpers
- internal/store/collections.go ListCollections active-count query
- internal/store/items.go GetItemProgress + GetAllItemProgress:
- New collectionDoneFilter type + childrenDoneFiltersFor{Parent,
Collection} + doneFiltersForWorkspace helpers load each
candidate collection's (schema, settings) and resolve per-
collection done keys + terminals.
- buildChildrenDoneExpr(filters, alias) compiles filters into a
single SQL boolean expression using per-collection OR clauses:
((alias.collection_id=? AND LOWER(...)
IN (?,?)) OR (alias.collection_id=? AND LOWER(...)
IN (?,?)) ...)
- Each child item is evaluated against its own collection's
done rules, so mixed-collection child progress is correct
without a global union hack.
- internal/store/agent_roles.go GetRoleBreakdown + Go-side filter
- internal/store/item_stars.go starred-items filtering now uses a
collectionDoneContext map (schema + settings) and IsTerminalItem.
Go-side callers migrated
- internal/server/handlers_dashboard.go: buildSchemaMap →
buildDoneContextMap (carries settings), isItemTerminal →
isItemDone (evaluates against the done field). 7 call sites
updated.
- internal/server/handlers_items.go: plan-progress recompute and
per-item /progress endpoint now use the done-context approach.
Left status-specific (per task scope)
- Link-payload $.status extracts in items.go getItemLink /
GetItemLinks / GetParentForItem — these populate
link.SourceStatus / link.TargetStatus, which are status-specific
by design.
- cmd/pad reconcile paths — no schema in scope, default-list
fallback is the right call.
- search.go facet "status breakdown" — a different UX concept
(bucket search results by status values) than done-detection.
Web UI reactivity
- FieldEditor: new activeDoneField prop. Each modal derives it from
boardGroupBy with the same fallback rule as the Go DoneFieldKey.
- Fields tab: the "Done?" column header on each select field renders
an "Active" green pill when that field is the board group-by, or a
muted "Saved" pill + inline hint otherwise ("Switch the board
group-by to <key> to make them drive done-detection"). Reactive to
boardGroupBy changes in the Display tab.
- DisplaySettingsEditor: "Board group by" label gets a helper line
explaining the new responsibility.
Tests
- internal/models/terminal_test.go: 13 unit tests covering fallback
resolution, placeholder args, membership (case-insensitive), and
back-compat shim semantics.
- internal/store/done_field_test.go: 3 integration tests:
1. Bugs collection grouped by resolution → items with terminal
resolution values count as done; items with status=fixed but
resolution=open do NOT count as done (proves status is no
longer consulted when it isn't the done field).
2. Collection without board_group_by still uses status terminals.
3. Mixed-collection children: each child evaluated against its
own done rules.
All pass alongside the full existing suite.
* fix: restrict done field to select (reject multi_select)
Two linked Codex P1 findings on PR #140, both rooted in the same
gap: multi_select fields store their values as JSON arrays, but both
the Go-side membership check (IsTerminalItem) and the SQL done
expression (buildChildrenDoneExpr) assume a scalar string. Naively
accepting multi_select as a done field would silently miss items
whose terminal value is one of several in the array — dashboards
and progress would report wrong counts.
Rather than implement array-containment semantics across both
paths (which would require deciding "any terminal value → done" vs
"all terminal values → done", SQL-dialect-aware JSON-contains, and
new tests for both shapes), close the gap with a constraint: only
select fields qualify as a done field. If array semantics become
a requirement later, that's a focused follow-up that can update
both paths together with a clear definition.
Changes
- DoneFieldKey and TerminalValuesForDoneField: loop bodies now
match only `select`, not `select || multi_select`. A
board_group_by pointing at a multi_select field falls back to
'status' — matching the rule for non-existent or non-select
fields.
- IsTerminalItem: docstring made the scalar contract explicit;
non-string values (which would be the multi_select array shape)
already returned false, which is now the deliberate behavior.
- buildChildrenDoneExpr: added a doc note that the scalar
JSON_EXTRACT path is correct because the upstream resolution
only hands us select fields.
- Web UI: EditCollectionModal + CreateCollectionModal derive
activeDoneField matching the backend rule (select only), and
FieldEditor.isActiveDoneField gates on field.type === 'select'.
A multi_select field never lights up the green "Active" pill now,
even if a user somehow pointed board_group_by at one.
Tests
- Replaced TestDoneFieldKey_AcceptsMultiSelect with
TestDoneFieldKey_RejectsMultiSelect. Asserts that a multi_select
board_group_by falls back to 'status' instead of being honored.
- Existing 12 unit tests + 3 integration tests all still pass.
* fix: include soft-deleted collections in done-filter loaders
Two related Codex P2s on PR #140. The done-filter loaders were
limiting their SELECT to collections with deleted_at IS NULL, but
the outer callers (GetItemProgress, GetAllItemProgress,
GetRoleBreakdown) count items regardless of their collection's
deleted_at. Net effect: after a collection was soft-deleted, its
items lost their per-collection clause in buildChildrenDoneExpr and
were always evaluated as non-terminal — undercounting done in plan
progress and inflating active counts in the role breakdown.
Fix
Drop the `c.deleted_at IS NULL` guard from all three filter
loaders:
- childrenDoneFiltersForParent
- childrenDoneFiltersForCollection
- doneFiltersForWorkspace
Soft-deleted collections still have valid schema + settings rows in
the DB, so the done rules remain applicable until a hard delete
cascades. This also matches what the outer queries count: if they
include items from a soft-deleted collection, the filter loaders
must too.
Regression test
TestGetItemProgress_HonorsSoftDeletedChildCollections:
1. Create a parent + two children in a child collection where one
child is done and one is open — assert done=1.
2. DeleteCollection on the child collection (soft-delete).
3. Re-run GetItemProgress — assert done is still 1, not 0.
Fails before the filter-loader fix, passes after.
* fix: avoid N+1 in plans progress + preserve done fallback on bad schemas
Two Codex P2s on PR #140.
P2: Avoid N+1 list-collection queries in plans progress
handlePlansProgress's restricted path was calling s.store.
ListCollections solely to build a ctxMap, but ListCollections runs a
separate active-item COUNT query per collection (collections.go),
burning O(number of collections) round-trips on every call. In
larger workspaces this materially inflates latency and can cause
timeouts. Add a lightweight Store.ListCollectionsMinimal that
returns only the ID / Schema / Settings needed for done-context
construction and skips the count queries entirely. Handler switches
to it.
P2: Preserve done fallback for unparseable collection schemas
scanCollectionDoneFilters was `continue`-ing past collections whose
schema failed to parse. Because buildChildrenDoneExpr composes a
per-collection OR clause and only applies the default-list fallback
when NO filters are constructed overall, a single malformed
collection could leave its items without a matching clause —
silently marking them as perpetually active in progress / role /
starred queries. Emit a fallback filter (status + DefaultTerminal-
Statuses) for that collection instead of skipping it, matching
pre-TASK-604 behavior for its items while still honoring the
configured rules for every other collection.
* fix: sanitize done-field keys + cover granted-item collections
Two more Codex findings on PR #140.
P1: Sanitize done-field keys before embedding SQL JSON paths
buildChildrenDoneExpr passes the resolved done-field key straight
into JSONExtractText, whose dialect implementations interpolate it
as a string literal inside `json_extract(..., '$.<key>')` /
`-->>'<key>'`. Schema / settings rows are persisted without backend-
side key validation, so a crafted board_group_by (e.g. a key with
quotes, semicolons, or SQL metacharacters) could break the
resulting query or inject. Since TASK-604 made done-field
resolution dynamic, this needs a chokepoint.
Fix: DoneFieldKey now refuses to resolve to any candidate that
doesn't match ^[a-zA-Z][a-zA-Z0-9_]*$ and falls back to the literal
"status" (which is always safe). The pattern matches the convention
already in use for search-field filtering in internal/server/
handlers_search.go.
Added TestDoneFieldKey_RejectsUnsafeKeys covering injection-shaped
strings, dots, dashes, leading digits, empty strings, and spaces.
P2: Include granted-item collections in dashboard done context
The dashboard was filtering `collections` by visibility BEFORE
building ctxMap, but allItems can still include items from
collections outside the visibility set via item-level grants
(dashItemIDs). Those items missed their own done-rules and
fell back to the status-default, misclassifying them for guests
with item-level grants in collections that use a non-status done
field.
Fix: build ctxMap from ListCollectionsMinimal(workspaceID) first —
always covering every collection in the workspace — then apply
visibility filtering to `collections` for the summary section only.
isItemDone now sees the real done rules for every item the
dashboard iterates, regardless of how visibility surfaced it.
* fix(web): mirror backend safe-key check in activeDoneField derivation
Codex P2 on PR #140. The previous commit added a safe-key regex on
the backend (DoneFieldKey rejects keys outside ^[a-zA-Z][a-zA-Z0-9_]*$
and falls back to "status"), but the Web activeDoneField derivation
in both modals only checked type === 'select'. For legacy / API-
created schemas carrying keys like `resolution-v2` or `foo.bar`, the
Fields tab would display an "Active" green pill on that field even
though the server silently ignores it and falls back to status. Users
could configure terminal options on the wrong field and never see
them take effect.
Fix: export isSafeDoneFieldKey from field-editor-types.ts (a tiny
helper wrapping the same regex the backend uses) and gate both
modals' activeDoneField derivations on it. Unsafe keys fall back to
'status' in the UI, matching the backend's behavior exactly —
Active/Saved pills are now truthful.
|
||
|
|
e328844a1b |
fix: resolve five open bugs (BUG-585, BUG-586, BUG-588, BUG-589, BUG-590)
BUG-585 — Code-block copy no longer includes ``` fences
Editor.svelte: ProseMirror plugin overrides copy/cut when the selection
is inside a code_block node and writes raw textBetween to the clipboard.
NodeView for non-mermaid code blocks now shows a hover "Copy" button that
uses the existing copyToClipboard() util (with execCommand fallback).
BUG-586 — Wiki-link picker matches on item ref
Editor.svelte: getFilteredLinks() now also matches formatItemRef(item),
so typing [[DOC-535]] finds items by their issue ID. Picker dropdown
shows the ref as a badge; {#each} key switched to doc.id so duplicate
titles across collections don't collide.
BUG-588 — Can unlink OAuth provider when password is configured
Adds a password_set column to track whether a user has a usable
password vs. the random placeholder hash given to OAuth users.
CreateUser sets it true, UpdateUser sets it true when a password is
provided, and ValidatePassword auto-upgrades it on any successful
email/password login (which transparently upgrades pre-existing users
who linked OAuth after signing up with a real password — the OAuth
placeholder hash cannot match user-supplied plaintext, so this is safe).
handleOAuthUnlink now permits removing the last provider when
user.HasPassword() is true.
BUG-589 — Pre-auth pages render standalone
+layout.svelte: isAuthPage now also matches /forgot-password and
/reset-password/* so those pages don't inherit the authenticated
sidebar/topbar layout.
BUG-590 — Search no longer crashes with null results
store.Search() returned a nil Results slice on no-match queries, which
Go marshals as JSON null; CommandPalette then crashed on results.length.
Backend now normalizes nil to []SearchResult{} before returning.
CommandPalette also coalesces resp.results ?? [] on the initial search
and loadMore paths as belt-and-suspenders hardening.
|
||
|
|
b3af1acd07 |
feat: add last active tracking for users (#105)
* feat: add last active tracking for users Track when users were last active via a throttled update (once per 5 minutes) in the auth middleware. Adds last_active_at column, displays relative time in admin user list with full timestamp on hover. * fix: bound last-active goroutine with 3s context timeout Use a short-lived context for the background TouchUserActivity write so it gets cancelled under DB pressure, preventing goroutine/connection buildup from unbounded background work. |
||
|
|
d968b551b7 |
feat: add account disable/deactivation (#104)
* feat: add account disable/deactivation for admin users Allow admins to soft-disable user accounts without deleting data. Disabled users get a 403 on all authenticated requests, their sessions are invalidated on disable, and they show as visually dimmed with a red "disabled" badge in the admin console. Includes migration for disabled_at column, auth middleware check, disable/enable endpoints with audit logging, and frontend toggle with confirmation dialog. * refactor: auto-discover migrations from embedded filesystem Replace hardcoded migration lists with fs.ReadDir on the embedded FS directories. New migrations are now picked up automatically by filename sort order — no need to manually register them in store.go. * fix: block disabled users at login and capture IDs before async calls Reject disabled accounts in the login handler before session creation, not just in RequireAuth middleware (which exempts auth routes). Also capture selectedId into a local const in all async admin panel functions to prevent stale updates if the selection changes during a request. * fix: enforce disabled check in OAuth and password reset flows, always invalidate sessions Block disabled users in all session-minting paths (OAuth login, password reset) not just password login. Also remove early return for already-disabled users in the disable endpoint so session invalidation always runs, handling retry after partial failure. |
||
|
|
79d7d26a00 |
feat: add admin password reset for other users (#103)
* feat: add admin password reset for other users
New POST /api/v1/admin/users/{id}/reset-password endpoint. When email is
configured, sends a password reset link. Otherwise generates a temporary
password and invalidates existing sessions. Includes audit logging via
new password_reset_by_admin action and frontend UI with confirmation.
* fix: treat session revocation and email send as hard failures
Make session invalidation failure abort the reset instead of silently
continuing, and send the reset email synchronously so delivery failures
are surfaced to the admin caller.
|
||
|
|
f276745478 |
fix: sidebar collection counts ignore terminal status settings (#100)
When all items in a collection had terminal statuses (e.g. all bugs "fixed"), the sidebar showed the total item count instead of 0. Root cause: ActiveItemCount used `json:"omitempty"`, so a zero value was omitted from the API response. The sidebar fallback logic then displayed item_count (total) instead. Additionally, ListCollections used a hardcoded global terminal status list instead of respecting each collection's configured terminal_options. - Remove omitempty from ItemCount/ActiveItemCount so 0 serializes - Compute active counts per-collection using schema terminal_options - Show count of 0 in sidebar when collection has items but all are done |
||
|
|
ac24fb742c |
fix: breadcrumbs show parent item path for child items (#94)
When viewing a child item (e.g. TASK-101 under PLAN-10), the breadcrumb now shows "Home / Plans / PLAN-10 / TASK-101" instead of the flat "Home / Tasks / TASK-101". - Add parent_slug and parent_collection_slug fields to Go Item model - Populate them in both single-item and bulk enrichment paths - Add corresponding TypeScript types - Update breadcrumb nav to show parent collection and parent item when the item has a parent, falling back to the item's own collection Fixes BUG-516. |
||
|
|
92580905bb |
feat: cloud hardening and security follow-ups (PLAN-503)
Address 11 issues identified during the PLAN-427 security review: Critical/High: - Stripe customer-to-user mapping with indexed lookup (TASK-505) - OAuth provider linking with explicit consent model (TASK-504) - CSRF tokens on admin console mutations (TASK-506) - Rate limiting on cloud admin and OAuth endpoints (TASK-507) Medium: - __Host- cookie prefix for subdomain protection (TASK-510) - Billing portal verifies customer ownership server-side (TASK-515) - Transactional account deletion with rollback (TASK-509) - Streaming data export with 60s timeout (TASK-508) - Migration registration for new columns (TASK-514) Low: - Billing page fetches actual plan limits from API (TASK-511) - Admin user search/filter pushed into SQL with pagination (TASK-512) |
||
|
|
d0518216c5 |
feat: add cloud infrastructure for hosted Pad (PLAN-427)
Add the foundation for running Pad as a hosted service at app.getpad.dev. Same binary in cloud mode with a thin sidecar for OAuth and Stripe. Cloud mode (PAD_CLOUD=true): - PAD_CLOUD flag with cloud secret for sidecar communication - Account-level billing: plan field on users, CheckLimit enforcement - Free/Pro tiers with configurable limits stored in platform_settings - Three-tier limit resolution: user overrides → DB defaults → hardcoded fallback - Plan enforcement on workspace, item, member, webhook, and token creation Authentication & security: - OAuth login endpoint (POST /api/v1/auth/oauth-login) with cloud secret gate - Verified email requirement for OAuth, 2FA bypass protection - Cloud secret rotation support (comma-separated keys) - TOTP secret encryption at rest (AES-256-GCM via PAD_ENCRYPTION_KEY) - Rate limiting on OAuth login endpoint - Bootstrap disabled in cloud mode - Password max length enforcement (128 chars) - Config file written with 0600 permissions Admin & billing: - Admin user management API (list, detail, update plan/overrides) - Configurable plan limits API (GET/PATCH /api/v1/admin/limits) - Platform stats endpoint - Admin plan endpoint for sidecar to set user plans - GDPR: account deletion and data export endpoints Console UI (cloud mode only): - /console — workspace list with owned/shared sections - /console/new — create workspace wizard with slug preview - /console/settings — profile, password, API tokens - /console/billing — plan status, upgrade/manage links - /console/admin — user management, plan overrides, limits editor - OAuth buttons (GitHub/Google) on login page in cloud mode Auto-create default workspace on signup in cloud mode. Migration 035: plan, plan_expires_at, stripe_customer_id, plan_overrides on users. |
||
|
|
94d35509a4 |
feat: share links with hardened security, anonymous access, and analytics (#88)
* feat: share links with hashed tokens and /s/{token} route
Add share_links and share_link_views tables with CRUD API and
anonymous resolution route (TASK-421).
Data model:
- share_links: token_hash (SHA-256), target_type/id, permission,
password_hash, expires_at, max_views, require_auth, view tracking
- share_link_views: per-view records with fingerprint/user tracking
Token security:
- 192-bit entropy (crypto/rand), URL-safe base64 encoding
- SHA-256 hashed at rest, raw token returned only once on creation
- Generic 404 for invalid tokens (no info leakage)
- /api/v1/s/ exempt from auth middleware for anonymous access
API endpoints:
- POST /items/{slug}/share-links — create item share link
- POST /collections/{coll}/share-links — create collection share link
- GET /items/{slug}/share-links — list share links for item
- GET /collections/{coll}/share-links — list for collection
- DELETE /share-links/{id} — revoke share link
- GET /s/{token} — resolve share link, return shared content
D8: Anonymous users are ALWAYS read-only. View count and unique
viewers tracked on each resolution.
* feat: anonymous share page + share link management UI
Add minimal-chrome share link viewer page and share link CRUD in
the share dialog (TASK-422 + TASK-425).
Share page (/s/{token}):
- New SvelteKit route at /s/[token] for anonymous viewing
- Renders item (title, fields, markdown content) or collection
(name, item list) with no app chrome (no sidebar/topbar)
- Handles require_auth links with "Sign in to view" prompt
- Root layout bypasses auth checks for /s/ routes
- "Powered by Pad" footer
Share dialog updates:
- "Share links" section below existing grants
- Create/list/revoke share links for items and collections
- Copy-to-clipboard for share URLs
- Newly created links highlighted with "only shown once" notice
- View count and auth-required badges
API client:
- ShareLink type added
- shareLinks.* methods for CRUD
- share.get(token) for anonymous resolution
* feat: share link constraints + view analytics
Add password protection, expiry, max views, and view history
endpoints for share links (TASK-423 + TASK-424).
Constraints (TASK-423):
- CreateShareLink accepts ShareLinkOptions: password, expires_at,
max_views, require_auth, restrict_to_email
- Password hashed with bcrypt, verified on /s/{token} resolution
- Password-protected links return {require_password: true} prompt
- Expiry and max_views already validated by ValidateShareLink
Analytics (TASK-424):
- GET /share-links/{id}/views returns view history with fingerprint,
user ID, and timestamp
- Response includes total_views, unique_viewers, last_viewed_at
- View history stored per-view in share_link_views table
* fix: harden share links — XSS, access control, data leakage, and UX gaps
- Sanitize rendered markdown with DOMPurify before {@html} injection (XSS)
- Force require_auth=true when restrict_to_email is set (access bypass)
- Reject malformed non-empty JSON bodies with 400 instead of failing open
- Return public DTOs on share endpoints to prevent leaking internal IDs,
creator info, assignees, schemas, and other sensitive fields
- Enforce max_views atomically via conditional UPDATE to prevent races
- Fix collection share rendering: read items from top-level response key
and map ref/status fields correctly
- Add password prompt UI and X-Share-Password header support so
password-protected links can actually be unlocked by the frontend
* fix: follow-up hardening for share links
- Sanitize catch fallback in rendered markdown (XSS edge case if marked throws)
- Remove query-string password fallback; accept only X-Share-Password header
to avoid leaking passwords in logs, browser history, and referrers
- Return 500 on ListItems DB failure instead of swallowing as empty collection
- Normalize restrict_to_email with ToLower/TrimSpace on create and compare
- Fix malformed JSON check for chunked bodies (ContentLength == -1)
by checking for io.EOF instead of ContentLength > 0
- Remove internal share_link.id from public DTO responses
- Use clientIP(r) helper for consistent fingerprinting instead of raw
X-Forwarded-For which is spoofable and includes port in RemoteAddr
- Distinguish DB errors from not-found in share link delete handler
* fix: final hardening pass for share links
- Move auth/email gate before password check to prevent unauthenticated
callers from probing passwords and burning bcrypt CPU
- Wrap view recording (counter increment, unique-viewer accounting, view
insert) in a single transaction so a failed insert rolls back the
consumed view count instead of silently losing it
- Add X-Share-Password to CORS AllowedHeaders so cross-origin
deployments can send the custom header without preflight rejection
- Validate expires_at (RFC3339) and max_views (> 0) on share link
creation; return 400 for invalid constraints instead of creating
immediately-unusable links
- Cap view-history endpoint limit to 1000 to prevent unbounded queries
|
||
|
|
c6d19837c8 |
feat: collection & item grants, guest access, share dialog (PLAN-407 Phase 3) (#87)
* feat: collection and item grants tables + permission resolution
Add grant tables, CRUD operations, and permission resolution for
guest access and member overrides (TASK-417).
Data model:
- collection_grants table (id, collection_id, workspace_id, user_id,
permission, granted_by) with CASCADE on collection/user delete
- item_grants table (same structure, references items)
- Indexes for user/collection/item lookups
Store methods:
- Create/Get/List/Delete for both collection and item grants
- ListUserGrants: all grants for a user across a workspace
- RevokeAllUserGrants: bulk delete for member removal
- ResolveUserPermission: full 5-step resolution per DOC-406
(owner → item grant → collection grant → membership → deny)
API endpoints:
- GET/POST/DELETE /collections/{coll}/grants — collection grant CRUD
- GET/POST/DELETE /items/{slug}/grants — item grant CRUD
- GET /users/{userID}/grants — all grants for a user in workspace
All grant endpoints are owner-only for creation/deletion.
* feat: grant revocation + member removal with grant choice
Update member removal to support D4: owner chooses whether to revoke
all grants when removing a member (TASK-489).
- DELETE /members/{userID}?revoke_grants=true → remove membership AND
all collection/item grants (full removal)
- DELETE /members/{userID} (or revoke_grants=false) → remove membership
but keep grants (user becomes a guest with existing access)
- Audit log records whether grants were revoked
- CASCADE DELETE on collection/item deletion already handles cleanup
(via ON DELETE CASCADE in the grants migration)
* feat: share dialog UI for items and collections + grant types
Add a share dialog component for managing grants on items and
collections, plus TypeScript types and API client methods (TASK-419).
Frontend:
- ShareDialog.svelte: reusable modal for listing/creating/revoking
grants, with email input, permission select, and revoke buttons
- Item detail page: "Share" button in meta-actions (owner-only)
- Collection page: "Share" button in header actions (owner-only)
TypeScript:
- CollectionGrant and ItemGrant types added
- API client: grants.listCollectionGrants, createCollectionGrant,
deleteCollectionGrant, listItemGrants, createItemGrant,
deleteItemGrant, listUserGrants
Guest home screen (TASK-418) deferred — requires layout-level guest
detection which will be implemented when guest routing is built.
* feat: guest access — grants-based workspace access for non-members
Allow authenticated users with grants (but no workspace membership)
to access workspaces as guests (TASK-418).
Backend:
- UserHasGrantsInWorkspace: checks if user has any collection/item
grants in a workspace
- GuestVisibleCollectionIDs: returns collections visible to a guest
via collection grants + collections containing granted items
- RequireWorkspaceAccess: after member-nil check, falls through to
grant check; sets role to "guest" if grants exist
- VisibleCollectionIDs: non-members now checked for guest grants
instead of returning empty
- GetUserWorkspaces: includes guest workspaces (is_guest flag)
- GetWorkspacesBySlugForUser: JOINs on grants tables so workspaces
resolve for guests
- roleLevel: "guest" = 0 (below viewer, blocks role-gated actions)
Frontend:
- Workspace.is_guest field in TypeScript type
- Sidebar: hides Dashboard, Roles, Activity, Settings, and "New
collection" button for guests; shows "Shared with you" header
* feat: wiki-link rendering with locked icon for hidden items
Update wiki-link rendering to show a 🔒 locked icon when the linked
item is in a collection the user can't see (TASK-420).
- renderMarkdown accepts optional visibleCollectionSlugs parameter
- Items in hidden collections render as "🔒 Title" with tooltip
- Unresolved links still render as broken (no change)
- Username param added to renderMarkdown for correct URL construction
- TimelineCommentCard and CommentThread accept username prop
* fix: harden grant security — 9 findings from Codex review
- Item grants no longer leak collection-wide read access; guests with
item-level grants see only their granted items, not the full collection
(GuestVisibleResources two-level filter + ItemIDs in ListItems SQL).
- Edit grants are now enforced: mutating handlers (create/update/delete
items, comments, reactions, links, versions) resolve grant-based
permissions for guests via requireEditPermission + ResolveUserPermission.
- Grant list endpoints restricted to owners (collection/item grants) or
owner-or-self (user grants) to prevent metadata/email enumeration.
- Guests blocked from listing workspace members; invitation details
restricted to owners only.
- Grant deletion scoped to workspace_id to prevent cross-workspace
deletion by guessing grant IDs.
- Member removal now revokes grants by default (opt-out with
?revoke_grants=false) and propagates revocation errors instead of
silently discarding them.
- Guest workspace listing properly propagates DB errors instead of
swallowing them.
- PostgreSQL subquery alias added to UserHasGrantsInWorkspace to fix
silent guest-access failures on Postgres deployments.
* fix: harden item-level grant isolation — 7 findings from Codex re-review
- /changes endpoint now filters by item-level grants so guests with one
item grant no longer receive updates for every item in that collection.
- Search results filtered by item-level grants (new ItemIDs field in
SearchParams) so guests can't discover other items via search.
- Relationship/summary endpoints (item links, children, progress,
activity, dashboard) all apply item-level visibility checks via
isItemVisibleToGuest(), preventing metadata leakage through related
item titles, statuses, and counts.
- Grants now work as member overrides: a viewer with an edit grant can
edit the granted item (requireEditPermission falls back to
ResolveUserPermission for members below editor role).
- handleMoveItem now requires edit permission on the target collection,
not just visibility, preventing guests from moving items into
view-only collections.
- Member removal + grant revocation is now atomic via
RemoveWorkspaceMemberAndRevokeGrants() which wraps both operations
in a single database transaction.
- Guest-access DB errors in middleware now return 500 with slog.Error
instead of being silently collapsed into a 403 forbidden response.
* fix: close remaining grant isolation gaps — 10 findings from Codex round 3
- Workspace token endpoints (create/list/delete) now require owner role,
preventing guests from enumerating or revoking API tokens.
- Legacy document endpoints (list, get, context, bulk-read, backlinks,
links) now require at least viewer role, blocking guests entirely
since documents are outside the grants model.
- Global search no longer relies on workspaceRole() (which is unset
outside RequireWorkspaceAccess); detects guests via IsWorkspaceMember
and applies item-level filtering. Multi-workspace search now uses
GuestVisibleResources for guest workspaces.
- SSE event filtering now checks item IDs for guests with item-level
grants, not just collection slugs, preventing live event leaks.
- Role board passes ItemIDs through RoleBoardParams so guests only
see items they have grants on, not the entire collection.
- VisibleCollectionIDs for members with "specific" collection access
now merges direct grants (collection + item grants), so grant
overrides work for restricted members.
- Plans-progress endpoint filters plan items and children by item-level
grants for guests, preventing one plan grant from exposing all plans.
- Webhook listing now requires owner role since URLs may contain secrets.
- Agent role item counts use item-level filtering for guests.
- Link deletion checks item-level visibility on both endpoints, not
just collection-level.
* fix: close member grant escalation and remaining edge cases — round 4
- Item grants for restricted members no longer escalate to collection-
wide visibility. VisibleCollectionIDs now merges only direct collection
grants (not item-derived collections) into member access. Item-level
filtering (guestResourceFilter, isItemVisibleToGuest, requireItemVisible)
now applies to both guests AND restricted members with item grants,
closing the gap where a member with specific collection access plus
one item grant could see/edit all items in that collection.
- Guests blocked from workspace-level activity feed (/activity) which
exposed audit events (member invites, role changes) with operational
metadata. Requires at least viewer role.
- Global search no longer returns zero results for item-only guests.
Store.Search early-return now checks both CollectionIDs and ItemIDs
are empty before short-circuiting, so item-level grants work in
global (multi-workspace) search.
- UserHasGrantsInWorkspace now excludes item grants on soft-deleted
items, preventing phantom guest access to a workspace shell with
no visible content when the only granted item is archived.
* fix: prevent grant filter from overriding member access, close SSE/dashboard/collection leaks — round 5
- guestResourceFilter now returns nil/nil for members with "all"
collection access, preventing item grants from accidentally replacing
their full visibility. Only guests and members with "specific"
collection access get item-level filtering applied. This fixes a
regression where a normal member receiving one item grant would lose
access to all other items.
- requireItemVisible uses guestResourceFilter (with the same scoping)
instead of raw GuestVisibleResources, so the member-access check is
consistent throughout all code paths.
- SSE event filtering now denies collection-less events (workspace
updates, legacy document events) for guests, preventing metadata
leakage through realtime event payloads.
- Dashboard recent activity filters out workspace-level entries (no
DocumentID) for guests, preventing audit metadata leakage.
- All grant visibility queries (UserHasGrantsInWorkspace,
GuestVisibleCollectionIDs, GuestVisibleResources) now join the
collections table and require deleted_at IS NULL, so grants on
soft-deleted collections no longer provide phantom access.
* fix: make item grants additive for restricted members, close write/search/SSE gaps — round 6
- guestResourceFilter now merges member_collection_access + system
collections + collection grants into fullCollIDs for restricted members,
making item grants additive to existing access. Previously, item grants
replaced the member's normal collections, causing members with one item
grant to lose all their other collection visibility.
- Added ListSystemCollectionIDs store method for system collection lookup.
- Search (both global and workspace-scoped) now applies item-level
filtering for restricted members with item grants, not just guests.
Previously VisibleCollectionIDs included item-granted collections as
full-access, leaking all items in those collections via search.
- SSE event filtering now builds item-level filters for restricted
members with item grants (previously only for non-members/guests),
and merges member collections into the full-access set.
- Role board reorder now uses requireItemVisible + requireEditPermission
per item instead of collection-only visibility check, preventing
restricted editors from reordering items in item-granted collections.
- View create/update/delete now check requireEditPermission on the
collection (via requireViewEditable), not just collection visibility.
- GetUserWorkspaces guest query now joins collections/items tables to
exclude grants on soft-deleted resources, matching the behavior of
UserHasGrantsInWorkspace.
* fix: block guests from legacy doc versions/activity, fix ListItems early return, SSE fail-closed — round 7
- Legacy document version handlers (handleListVersions, handleGetVersion)
and document activity handler (handleListDocumentActivity) now require
at least viewer role, blocking guests from reading version history and
activity for unrelated legacy documents.
- ListItems early return now checks both CollectionIDs and ItemIDs are
empty before short-circuiting, matching the fix already applied to
Search. This fixes item-only guests seeing zero results from /items,
dashboard, role board, and agent-role counts.
- SSE item-grant filtering now fails closed on GuestVisibleResources
errors: installs empty item/collection filter sets instead of falling
through with nil (which would pass all events through).
- Role board reorder removed top-level requireMinRole("editor") so the
per-item grant-aware requireEditPermission checks can run for guests
and viewers with edit grants, consistent with other mutating handlers.
|
||
|
|
0fb8042ad2 |
feat: permission-filtered aggregates for all data endpoints
Wire collection visibility filtering into all data endpoints so members with "specific" access only see items in their visible collections (TASK-414). Core: - ItemListParams.CollectionIDs: SQL-level IN() filter on item queries - SearchParams.CollectionIDs: same for FTS search queries - visibleCollectionIDs() server helper computes once per request - isCollectionVisible() for single-item gating checks Filtered endpoints: - ListItems / ListCollectionItems: SQL-level collection ID filter - ListCollections: post-filter by visible set - Search: collection ID filter on both ref-lookup and FTS branches - Dashboard: all ListItems calls scoped, activity post-filtered - Activity feed: post-filtered by collection slug visibility - Collection items: gate check before listing Admins and "all access" members see everything (nil = no filter). The filtering is a no-op until a member's collection_access is set to "specific" via the management UI (TASK-416). |
||
|
|
d74431fbb3 |
feat: collection-level visibility + system collections
Add per-member collection visibility controls and mark conventions/
playbooks as system collections (TASK-413 + TASK-415).
Data model:
- workspace_members: new collection_access column ('all' or 'specific')
- New member_collection_access table (workspace_id, user_id, collection_id)
- collections: new is_system column, set for conventions and playbooks
Store methods:
- VisibleCollectionIDs(workspaceID, userID) — returns nil for "all"
access, or specific IDs (including system collections) for "specific"
- SetMemberCollectionAccess/GetMemberCollectionAccess for CRUD
- All collection queries include is_system in SELECT/scan
- Export/import handles is_system field
Default collection definitions:
- conventionsCollection and playbooksCollection set IsSystem=true
- New workspaces get system flag on seed
D7: default collection_access is "all" — absence of restrictions
means full access. System collections always visible to members.
|
||
|
|
38e6b4e5b1 |
feat: rewrite web UI routing to /{username}/{workspace}/... pattern
Restructure all workspace-scoped web URLs to include the owner's username as a prefix (TASK-411). Route structure: - Moved web/src/routes/[workspace]/ → [username]/[workspace]/ - All workspace pages extract both username and workspace from URL - Auth routes (/login, /register, /join, etc.) unchanged Backend: - Workspace model adds OwnerUsername field (populated by JOIN) - All workspace queries JOIN users table for owner_username - TypeScript Workspace type updated with owner_username Frontend (24 files updated): - All route pages: added username derived, updated URL constructions - Sidebar, TopBar, WorkspaceSwitcher: use owner_username for links - ItemCard, TableView, ChildItems, NestedChildren: username in links - CommandPalette, OnboardingChecklist, CreateWorkspaceModal: updated - Root page redirect includes owner_username - Wiki-link markdown utility accepts username parameter What did NOT change: - API client (client.ts) — still uses workspace slug for API calls - Go API routes — unchanged - CLI — unchanged |
||
|
|
520a7ca27b |
feat: add owner_id to workspaces with backfill
Add owner_id column to workspaces table and backfill existing workspaces from membership data (TASK-410 + TASK-480). - SQLite migration 030 and Postgres migration 010 add owner_id column with indexes on (owner_id) and (owner_id, slug) - Workspace, WorkspaceCreate models updated with OwnerID field - All workspace SELECT queries include owner_id - CreateWorkspace INSERT includes owner_id - handleCreateWorkspace sets owner_id from authenticated user - backfillWorkspaceOwners extended: sets owner_id using D3 logic (earliest owner member → earliest member → first admin) - TypeScript Workspace type updated Global UNIQUE(slug) constraint preserved for now; will be replaced with UNIQUE(owner_id, slug) in TASK-412 when auth-scoped resolution needs it. |
||
|
|
f80876a52e |
feat: add username column to users table
Add username field to the user data model as the foundation for the multi-user permissions system (PLAN-407, TASK-408). - SQLite migration 029 and Postgres migration 009 add username column with partial unique index (WHERE username != '') - User, UserCreate, UserUpdate Go structs updated - Store: CreateUser, UpdateUser, scanUser, userColumns updated - New GetUserByUsername store method (case-insensitive lookup) - All auth handler JSON payloads include username field - WorkspaceMember struct and ListWorkspaceMembers query include username - TypeScript User type and API client inline types updated Column is empty string by default; TASK-482 will backfill existing users and TASK-409 will add validation/registration flow support. |
||
|
|
1d26c2b542 |
feat: add workspace top bar with drag-to-reorder (#80)
* feat: add workspace top bar with drag-to-reorder Replace the sidebar WorkspaceSwitcher dropdown with a dedicated top bar that provides fast workspace switching and a user menu. Desktop: - Horizontal bar above sidebar + content with workspace icons (colored first-letter circles) and names as real <a> links - Drag-and-drop reorder via svelte-dnd-action - User avatar on right with dropdown (settings, theme toggle, sign out) - "+" button to create new workspaces Mobile: - Full-width fixed bar at top when sidebar opens (above sidebar/backdrop) - Tap workspace to navigate and close sidebar - Reorder button opens full-screen vertical list with drag handles - Sidebar starts below the top bar with adjusted positioning Backend: - Migration 028: add sort_order to workspace_members (per-user ordering) - GET /workspaces now returns workspaces in user's sort order - PUT /workspaces/reorder endpoint for persisting order Sidebar simplified: - Removed WorkspaceSwitcher component, user section, theme toggle - Theme initialization moved to root layout - Cleaner footer with search, settings, and notification bell Implements IDEA-129, relates to IDEA-126. * fix: address codex review findings (P1+P2) - Remove unsupported `direction` option from svelte-dnd-action dndzone - Add Postgres migration 008 for workspace_members.sort_order - Handle sql.ErrNoRows gracefully in reorder endpoint for admins who aren't members of all workspaces - Restore mobile sign-out: add user name + logout button to sidebar footer on mobile (was only in desktop TopBar user menu) |
||
|
|
0e32645bb5 |
feat: add TOTP two-factor authentication
Backend support for optional TOTP-based 2FA on user accounts:
- POST /auth/2fa/setup — generate TOTP secret, return QR code URI
- POST /auth/2fa/verify — verify code and enable 2FA with recovery codes
- POST /auth/2fa/disable — disable 2FA (requires password confirmation)
- POST /auth/2fa/login-verify — complete login with TOTP or recovery code
- Login returns {requires_2fa: true, user_id} when 2FA is enabled,
requiring a second step via /auth/2fa/login-verify
- 8 recovery codes generated on setup for account recovery
- User model extended with totp_secret, totp_enabled, recovery_codes
- Refactored user queries with shared scanUser/userColumns for DRYness
Implements TASK-169 under PLAN-15 (Pad Cloud: Hardening).
|
||
|
|
ba8e20c697 |
feat: add API token rotation, expiry defaults, and scope enforcement
- New tokens get a default 90-day expiry (configurable via platform
settings: token_default_expiry_days, token_max_lifetime_days)
- POST /api/v1/auth/tokens/{id}/rotate generates a new secret while
preserving token metadata; old secret is immediately invalidated
- X-Token-Expires-Soon and X-Token-Expires-At headers warn when a
token is within 7 days of expiry
- Token scopes are now enforced: "read" restricts to GET/HEAD/OPTIONS,
"write" and "*" allow all methods
- Existing tokens without expiry continue to work (backward compatible)
Implements TASK-170 under PLAN-15 (Pad Cloud: Hardening).
|
||
|
|
bde15d45ca |
Rename Phases to Plans, clean up deprecated aliases (#71)
* Rename "Phases" to "Plans" and clean up deprecated phase aliases
Renames the default "Phases" collection to "Plans" across the full stack:
- DB migration renames existing collections in-place (name, slug, prefix PLAN, icon 🗺️)
- Removes all deprecated Phase* backward-compat aliases from models and store
- Removes --phase CLI flag (use --parent instead)
- Updates convention triggers: on-phase-start/complete → on-plan-start/complete
- Updates dashboard API: active_phases → active_plans, /phases-progress → /plans-progress
- Updates all frontend components, types, and documentation
Closes IDEA-124
* Fix CSRF cookie not being cleared on logout
The SessionAuth middleware was re-issuing a CSRF cookie before the
logout handler could clear it, resulting in two Set-Cookie headers.
Skip CSRF re-issue for /api/v1/auth/ paths since auth endpoints
manage their own CSRF cookies (login sets, logout clears).
* Fix migration issues found in Codex review
- P1: Move doc_type UPDATE from migration 024 into 025, which recreates
the table with the new CHECK constraint first (SQLite enforces CHECK
on UPDATE, so the old constraint would reject 'plan')
- P1: Add PostgreSQL migration 005 for the collection rename (phases →
plans) — previously only existed on the SQLite path
- P2: Recreate FTS triggers, indexes, and rebuild FTS after the table
swap in migration 025 (DROP TABLE drops associated objects in SQLite)
* Fix parent filter field name and sync .agents skill copy
Codex review round 2 findings:
- P1: Parent filter compared against `parent_id` (wrong) instead of
`parent_link_id` — plan filtering in collection view was broken
- P1: .agents/skills/pad/SKILL.md still had old --phase flags and
"Phases" references — synced from the updated .claude copy
- P2: Accept legacy 'phase' filter key for backward compat with
existing saved views that serialized the old key name
* Fix PG migration JSONB casting and add slug collision guards
Codex PR review bot findings:
- P1: PostgreSQL REPLACE/LIKE don't work on JSONB columns — cast
schema::text and fields::text before string ops, then back to ::jsonb
- P1: If a workspace already has a custom 'plans' collection, the
rename hits UNIQUE(workspace_id, slug) — added NOT EXISTS guard
to both SQLite and PostgreSQL migrations
|
||
|
|
063ff92d00 |
feat: generalized parent/child items with progress tracking (#70)
* feat: generalize parent/child items — any item can have children with progress tracking
Replaces the phases-only task widget with a generalized parent/child system.
Any item (Phase, Idea, Doc, Task, etc.) can now be a parent of child items,
getting automatic progress bars, burndown charts, status grouping, drag-drop
reordering, and recursive expand/collapse up to 3 levels deep.
DB: migrate link_type 'phase' → 'parent' (migration 023)
Store: generalized methods (GetChildItems, GetItemProgress, SetParentLink
with cycle detection), drop collection filters, per-child terminal status
API: new /items/{slug}/children and /items/{slug}/progress endpoints
Frontend: ChildItems, ChildChart, NestedChildren components replace PhaseTasks
CLI: --parent flag (--phase kept as hidden alias), list/show/changelog updated
Docs: CLAUDE.md, SKILL.md, pad-web updated for parent/child model
Full backward compatibility: old 'phase' link_type, --phase flags, phase_id/
phase_ref JSON fields all still work as deprecated aliases.
Closes PHASE-16 (9 tasks).
* fix: update collection list page to use item_id from phasesProgress response
The TS client return type changed from phase_id to item_id but the
collection list page still referenced p.phase_id, causing svelte-check
type errors in CI.
* fix: address Codex review findings — PG migration, terminal statuses, metrics, CSRF resilience
- Add PostgreSQL migration 003 to rename 'phase' links to 'parent'
- Use schema-defined terminal statuses in GetAllItemProgress instead of hardcoded defaults
- Pass computed terminal statuses from page to ChildItems component
- Only special-case 'parent' field key when not defined in collection schema
- Move MetricsMiddleware before Recoverer so panics are counted
- Always mount ChildItems for SSE subscriptions even with 0 children
- Exclude soft-deleted children from has_children enrichment query
- Re-issue CSRF cookie when session is valid but cookie is missing
- Show actual API error messages in create-item toasts
|
||
|
|
872f08aa84 |
feat: add compliance audit trail with IP/UA tracking
Extend the activities table to capture IP address and user agent for all state-changing operations. Add audit events for auth (login, logout, register, bootstrap, password changes), workspace management (member invite/remove, role changes), token lifecycle, and admin settings. - SQLite migration recreates activities table with nullable workspace_id, new ip_address/user_agent columns, and relaxed CHECK constraints - PostgreSQL migration adds columns and drops constraints - New ListAuditLog store method with action/actor/workspace/date filters - GET /api/v1/audit-log endpoint (admin-only) - CLI: pad workspace audit-log [--days N] [--actor X] [--action X] |
||
|
|
367116b3a0 |
Unify relation fields and item links into single dependency system (#66)
* feat: unify relation fields and item links into single dependency system
Phase membership (Task→Phase) was previously stored as a UUID in the
item's fields JSON, separate from the item_links table used for
blocks/related/implements relationships. This unifies both into the
item_links table so all item relationships use one system.
Backend:
- Add 'phase' link type to item_links constants
- Migration 021: migrate existing phase field values to item_links,
strip phase from fields JSON, remove phase field from tasks schema
- Rewrite GetPhaseProgress, GetAllPhasesProgress, GetTasksForPhase
to JOIN on item_links instead of json_extract(fields, '$.phase')
- Add SetPhaseLink, ClearPhaseLink, GetPhaseForItem, GetTaskPhaseMap
store helpers with single-phase constraint enforcement
- Create/update handlers intercept 'phase' in fields and route through
links system; enrich item responses with phase_id/ref/title
- Dashboard orphan detection uses batch GetTaskPhaseMap lookup
- Add PhaseID filter to ItemListParams for link-based list filtering
Frontend:
- Remove relation field type from FieldEditor (no longer needed)
- Add link CRUD UI to item detail page: "Add relationship" inline form
with link type picker + item search, delete buttons on existing links
- Phase links appear in Relationships section as "In phase"/"Phase"
- ItemCard reads phase from item.phase_title instead of fields.phase
- FilterBar phase filter uses item.phase_id for client-side filtering
- Add api.links.delete to frontend API client
- Fix duplicate {#each} key on dashboard attention list
Implements IDEA-106.
* fix: remove relationLabels prop from BoardView, ListView, TableView
ItemCard no longer accepts relationLabels (phase info now comes from
item.phase_title), so remove the prop from all parent view components
that were passing it through. Also remove unused .cell-relation CSS.
* fix: address PR review — atomic SetPhaseLink, migration safety, error handling
1. Migration 021: remove deleted_at filters so archived tasks and tasks
pointing to archived phases also get their phase links migrated.
2. SetPhaseLink: wrap delete+insert in a transaction so a failed insert
doesn't leave the item with no phase link (previously non-atomic).
3. Create/update handlers: return proper HTTP errors when phase link
operations fail instead of logging warnings and returning 200 OK.
|
||
|
|
e21da3c6a4 |
fix: schema-driven terminal statuses replace hardcoded lists (BUG-17) (#65)
Add `terminal_options` to collection field schemas so each collection declares which statuses are terminal/finalized. Replaces 10+ inconsistent hardcoded status lists across backend, CLI, and frontend. - Add TerminalOptions to FieldDef and centralized helpers in models/terminal.go - Populate terminal_options on all default and template collections - Replace hardcoded isDoneStatus/isTerminalItemStatus with schema-aware lookups - Fix phase progress to count all terminal statuses (not just "done") - Add terminal status toggle UI in collection field editor (Settings → Fields) - Redesign collection field editor for cleaner layout and alignment - Move Platform settings tab before Danger Zone tab |
||
|
|
8b1b46ef22 |
feat: persistent card ordering within role board lanes
Add role_sort_order column to items for independent ordering in the role board, separate from the collection sort_order. Backend: - Migration 020: role_sort_order INTEGER column on items - Item model, all SELECT/INSERT/Scan queries updated - PUT /roles/board/reorder endpoint for batch sort updates - Board API sorts items by role_sort_order within each lane Frontend: - Within-lane drag reorder persists via reorder API - Cross-lane moves also persist new sort order - Both operations are optimistic (no page refresh) |
||
|
|
edd259b1b0 |
feat: role board — cross-collection view, dashboard breakdown, agent bindings (#60)
* feat: role board — cross-collection view, dashboard breakdown, agent bindings (#PHASE-11)
Add a standalone role board page showing all work organized by agent
role across every collection. This is the "human orchestrator" view —
see at a glance what's queued for each capability and who's working it.
Agent bindings:
- Add `tools` text field to agent_roles table (migration 019)
- CLI: `pad role create "Implementer" --tools "Claude Code + Sonnet"`
- Lightweight notes about preferred tools — no per-user binding table
Dashboard role breakdown:
- `pad project dashboard` now includes `by_role` section
- Shows item count, assigned users, and tools per role
- CLI renders role summary table with icons
Role board API:
- `GET /workspaces/{ws}/roles/board` — items from all collections grouped by role
- Filters terminal-status items (done, cancelled, etc.)
- Supports `?assigned_user_id=X` for "my work" filtering
- Returns role info, items, and assigned user list per lane
Web UI:
- New page at /{workspace}/roles with horizontal lane layout
- Collection badges on cards (items span collections)
- "My Work" toggle to filter by current user
- Empty states for no roles and empty lanes
- Sidebar nav: 🎭 Roles link added
- Responsive: stacks vertically on mobile
Skill:
- References role board in greeting and "who's working on what" patterns
* feat: add assignment picker to item detail page
Replace read-only assignment display with interactive dropdowns for
assigning users and roles directly from the item detail page.
- User dropdown populated from workspace members
- Role dropdown populated from agent roles
- Either can be set or cleared independently
- Saves immediately on change via PATCH API
- Added assigned_user_id/agent_role_id/clear_* to ItemUpdate type
* feat: add role management UI to roles page
Add a "Manage" toggle in the role board header that reveals an inline
panel for creating, editing, and deleting roles directly from the UI.
- Role cards show icon, name, description, tools, and item count
- Edit inline: name, icon, description, tools
- Create new roles with a dashed card form
- Delete with confirmation dialog
- Board auto-refreshes after changes
* refactor: replace inline role management with dialog modal
The inline horizontal card grid was cramped and hard to use. Replace
with a proper <dialog> modal that opens from the ⚙ Manage button.
- Vertical list of role rows with icon, name, description, tools, item count
- Inline edit mode per row with labeled fields
- Create new role form at the bottom with clear field labels
- Click backdrop or ✕ to close, board refreshes on close
- Native dialog handles backdrop, escape key, and focus trapping
* fix: role board mobile layout matches collection kanban, unassigned first
- Unassigned lane now appears first (before role lanes)
- Mobile: horizontal swipe with scroll-snap at 75vw columns, matching
the collection BoardView pattern (no vertical stacking)
* feat: add drag-and-drop between role board lanes
Items can now be dragged between role lanes to reassign their role.
Uses svelte-dnd-action matching the collection BoardView pattern.
- Drag items between role lanes to change role assignment
- Drag to Unassigned lane to clear role
- Drop target highlight on hover
- Touch support with 500ms delay (same as collection board)
- Haptic feedback on mobile drag start
- Board refreshes after drop to sync server state
* fix: auto-assign user on drag to role lane, show unassigned in My Work
- When dragging an unassigned item into a role lane, automatically
assign the current user alongside the role
- "My Work" filter now shows items assigned to you OR items with no
user assignment, so unassigned work remains visible and claimable
* fix: three-state filter on role board — All, My Work, Unassigned
Replace the My Work toggle with a segmented button group offering
three filter modes:
- All: show everything (default)
- My Work: items explicitly assigned to the current user
- Unassigned: items with no user assignment
* fix: replace filter buttons with Highlight Mine toggle
Remove the three-state filter (All/My Work/Unassigned) and replace
with a single "Highlight Mine" toggle that dims cards not assigned
to the current user. All items remain visible and draggable — your
items just visually pop while others fade to 35% opacity (hovering
restores to 70%).
* fix: resolve undefined loadBoard and myWorkOnly in role board page
Replace 6 references to nonexistent `loadBoard()` with `loadData()`
(the actual data-loading function), and replace `myWorkOnly` with
`highlightMine` (the actual state variable). Fixes svelte-check errors
that caused CI Web Build to fail.
* fix: role breakdown pointer aliasing and terminal status filtering
P1: Copy role.ID to a local variable before taking its address in
GetRoleBreakdown, avoiding potential pointer aliasing from the range
variable (safe in Go 1.22+ but clearer with an explicit copy).
P2: Add terminal status exclusion to the GetRoleBreakdown SQL query
so dashboard counts match the board view. Previously, done/completed/
cancelled items were included in role counts, inflating active load.
Addresses Codex review comments on PR #60.
|
||
|
|
be576d9e24 |
feat: agent roles — role-based (user, role) assignment for items (#58)
* feat: agent roles — role-based (user, role) assignment for items (#PHASE-9) Introduce agent roles as a first-class concept for human-agent work assignment. Roles describe capability specializations (Planner, Implementer, Reviewer, etc.) and items can be assigned to a (user, role) pair, enabling natural handoff workflows between different AI tools. Migration: - New `agent_roles` table (workspace-scoped, slug-unique) - `assigned_user_id` + `agent_role_id` columns on `items` with FKs - Removed legacy `assignee` text field from Tasks schema Backend: - AgentRole model + full CRUD store/API - All item queries updated with LEFT JOINs to resolve assignment - Item list filtering by assigned_user_id and agent_role_id - Role transitions tracked in activity feed metadata CLI: - `pad role list/create/delete` commands - `--role` and `--assign` flags on item create/update/list - Assignment displayed in `pad item show` output Web: - TypeScript types + API client for agent roles - Role badge on item cards in list/board views - Assignment display on item detail page * fix: enforce workspace-scoped assignments and fail fast on unresolved --assign filter Addresses code review feedback from PR #58: P1: Add validateAssignmentScope() to the store layer, called by both CreateItem and UpdateItem. Verifies that assigned_user_id belongs to the workspace (via IsWorkspaceMember) and agent_role_id exists in the workspace (via GetAgentRole) before writing. Prevents cross-workspace assignment leaks. P2: The CLI `pad item list --assign <name>` now errors instead of silently returning unfiltered results when the member lookup fails or no workspace member matches the provided name. |
||
|
|
481527de02 |
fix: server-side timeline pagination and reaction toggle (#57)
* fix: server-side timeline pagination and reaction toggle (#55, #56) Issue #55: Replace in-memory pagination with cursor-based approach. The /timeline endpoint now accepts `before` (RFC3339 timestamp) and `limit` params, fetching a small window from each source (comments, activities, versions) instead of loading everything into memory. Frontend gets a "Load more" button that passes the oldest entry's timestamp as the cursor. Issue #56: Plumb current user ID to reaction toggle. ItemTimeline fetches the auth session on mount to get the user ID, passes it to TimelineCommentCard. toggleReaction now checks if the user already reacted (by matching reaction.user_id) and calls onRemoveReaction to un-react. Own reaction chips are visually highlighted. * fix: address review findings for PR #57 (iteration 1) - Use <= with ID tie-breaker in cursor queries to prevent skipping entries at timestamp boundaries; use consistent RFC3339 format - Treat orphaned replies (parent on different page) as top-level entries instead of silently dropping them - Deduplicate by ID on "Load more" to handle boundary overlap - SSE reload now prepends new entries and updates existing ones instead of clobbering all paginated state - Parse before cursor with RFC3339Nano fallback for sub-second precision - Fix dangling doc comment on ListItemVersions Co-Authored-By: Claude <noreply@anthropic.com> * refactor: add global auth store, remove per-component session fetch Create authStore (web/src/lib/stores/auth.svelte.ts) following the same pattern as workspaceStore. The root layout populates it on mount. ItemTimeline now reads currentUserId via $derived(authStore.userId) instead of making a separate api.auth.session() call on every mount. * fix: address review findings for PR #57 (iteration 2) - Add beforeID tie-breaker to all cursor queries to prevent infinite Load More loop when entries share the same timestamp - Over-fetch per source (limit*3) to avoid skipping filtered entries - SSE refresh now detects deleted entries and removes them from the first-page window instead of keeping stale data - Auth store re-throws on fetch errors so layout can distinguish "not authenticated" from "server unreachable" - Sidebar reads from authStore instead of making redundant session fetch Co-Authored-By: Claude <noreply@anthropic.com> * fix: address review findings for PR #57 (iteration 3) - Add ID tie-breaker to buildTimeline sort to match SQL cursor ordering (prevents same-second entries from being skipped on Load More) - Refresh authStore after login so Sidebar and reaction toggle have correct user identity without requiring a page reload - SSE merge now tracks first-page IDs explicitly to detect deletions without incorrectly removing entries from older pages that share boundary timestamps Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
998716ae49 |
feat: unified item timeline with comment-on-update, threading, and reactions (#54)
* feat: unified item timeline with comment-on-update, threading, and reactions (IDEA-115) Replace the separate Comments section and Version History modal on the item detail page with a single chronological timeline that interleaves comments, activities, and content versions. Key changes: - Add --comment flag to `pad item update` so agents/users can explain status changes inline (creates a comment linked to the activity) - Add threaded replies (parent_id on comments) with inline reply UI - Add emoji reactions on comments (new comment_reactions table) - New /timeline API endpoint merges comments, activities, and versions server-side with dedup and collapsing of rapid edits - New Svelte timeline components: ItemTimeline, TimelineCommentCard, TimelineActivityCard, TimelineVersionCard, ReactionPicker - Remove Implementation Notes and Decision Log inputs from web UI - Update skill docs to encourage --comment on status changes * fix: address review findings for PR #54 (iteration 1) - Use ListItemVersions instead of ListVersions in timeline endpoint so item content history renders correctly - Add workspace validation to reply and reaction handlers to prevent cross-workspace comment mutation - Raise activity cap from 500 to 10000 to avoid silently truncating long timelines - Fix toggleReaction to always POST (idempotent) instead of incorrectly matching other users' reactions for DELETE - Await onReply promise before clearing draft to prevent duplicate submissions and lost drafts on failure - Register reaction_added/reaction_removed in SSE ITEM_EVENTS so reactions from other sessions appear in real-time Co-Authored-By: Claude <noreply@anthropic.com> * fix: address review findings for PR #54 (iteration 2) - Fix nil pointer dereference in timeline handler when item not found - Store empty string instead of NULL for reaction user_id so UNIQUE constraint works correctly in SQLite - Add workspace validation to handleDeleteComment (cross-workspace deletion was possible) - Fix SKILL.md duplicate numbering (4. appeared twice) - Remove || true debug artifacts from reaction conditionals - Replace SvelteMap with plain Map in non-reactive groupReactions - Use != null checks for timeline API params to handle offset=0 - Log warning on comment creation failure during item update Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
35f3dd1da4 |
feat(conventions): add structured metadata for TASK-133 (#51)
* feat(conventions): add structured metadata for TASK-133 * fix(web): add workspace update type for CI |
||
|
|
23a7fc2be1 | feat(workspaces): add CLI and API context support for TASK-130 (#46) | ||
|
|
c1a9cd1533 | feat(workspaces): add typed context schema for TASK-129 (#47) | ||
|
|
c61f4cdaaa | feat(items): add structured notes for TASK-125 (#43) | ||
|
|
bd9f281c81 | feat(items): add first-class code metadata for TASK-123 (#41) | ||
|
|
0596ed07f4 | feat(lineage): surface derived closure for TASK-122 (#40) | ||
|
|
c9ba893650 | feat(links): add lineage relationships for TASK-121 (#39) | ||
|
|
4003772538 |
feat: show user names in activity feeds and real-time events (#17)
Activity entries now display the authenticated user's name instead of
generic "user"/"You" labels. The user_id (already present in the
activities table from migration 012) is persisted when logging activity
and joined against the users table when querying, so actor_name flows
through the API without extra lookups. Falls back to the actor field
value when no user is associated (e.g. pre-auth activities or deleted
users).
Backend:
- Activity model gains UserID and ActorName fields
- Store queries LEFT JOIN users to populate actor_name
- logActivityWithMeta now records currentUserID on every activity
- Dashboard API includes actor_name in recent_activity
- SSE Event struct carries ActorName for real-time toasts
- Item-level activity endpoint added (GET /items/{slug}/activity)
Frontend:
- Activity page shows user name badge (green) instead of "web"
- Dashboard recent activity shows user name inline
- ActivityFeed component displays user name instead of "You"
- SSE toast notifications show user name instead of "CLI"
|
||
|
|
a219f81633 |
fix: CLI and skill file now use issue IDs (TASK-5) instead of slugs (#15)
Agents were using verbose slugs because: 1. The skill file (SKILL.md) taught them to use `<slug>` in every example 2. CLI output showed slugs in parentheses rather than issue IDs 3. CLI usage strings said `<slug>` not `<ref>` 4. JSON output lacked a `ref` field, so agents parsing JSON only saw slugs Changes: - Add computed `ref` field to Item model (e.g. "TASK-5") in JSON output - CLI create/update/delete/edit output now prominently shows issue IDs - All CLI usage strings changed from `<slug>` to `<ref>` - Issue IDs displayed in bold cyan (not dim) in list/show/grouped views - Skill file rewritten to use issue IDs in all examples and instructions - Dashboard API includes `item_ref`/`ref` in attention, suggestions, phases - Search results now include item_number and collection_prefix for refs - CLAUDE.md updated to document issue ID usage |
||
|
|
46447e5504 |
feat: user management & authentication (Phase 6) (#14)
* feat: add user management database migration and models
Add migration 012_users.sql with users, sessions, and workspace_members
tables. Add user_id columns to api_tokens, items, comments, activities,
item_links, and item_versions for proper user attribution. Create Go
model structs (User, Session, WorkspaceMember) in models/user.go.
* feat: add store layer for users, sessions, and workspace members
Implement CRUD operations for user management:
- users.go: create, get, update, list, validate password (bcrypt)
- sessions.go: create, validate, delete, cleanup expired (SHA-256 hashed tokens)
- workspace_members.go: add/remove members, role management, access checks
Adds golang.org/x/crypto/bcrypt dependency. Includes 16 new tests
covering all store methods, password validation, session lifecycle,
and workspace membership operations.
* feat: rewrite auth system from single-password to user-based
Replace single-password auth with email/password user authentication:
- New endpoints: POST /auth/register, GET /auth/me
- Rewritten: POST /auth/login (email+password), GET /auth/session
(needs_setup detection), POST /auth/logout (DB session destroy)
- Delete in-memory SessionManager, use DB-backed sessions via store
- New middleware: SessionAuth (cookie→user), RequireAuth (with
fresh-install passthrough when no users exist)
- Remove Password field from config, PAD_PASSWORD env var, SetPassword()
All 23 existing server tests pass (fresh DBs have no users → passthrough).
* feat: add workspace access control middleware
Add RequireWorkspaceAccess middleware that checks workspace_members for
authenticated users, with fallback for legacy API tokens and fresh
installs (no users → implicit owner). Includes role hierarchy helpers
(workspaceRole, requireRole) for downstream permission checks.
Wire middleware into the /{slug} workspace route group.
* feat: add CLI auth commands and credential storage
Add pad login, pad logout, pad whoami commands with credential
storage in ~/.pad/credentials.json (0600 permissions). Update CLI
HTTP client to auto-attach auth tokens and X-Pad-Agent header on
all requests. Add auth API methods (Login, Register, Logout,
CheckSession, GetCurrentUser). Extend .pad.toml with optional
agent_name field. Add golang.org/x/term for masked password input.
* feat: derive actor/source from auth context in all handlers
Replace hardcoded "user"/"web" actor/source strings with auth-aware
helpers. actorFromRequest() derives actor ("user"/"agent" via
X-Pad-Agent header) and source ("web"/"cli" from auth method).
agentMeta() merges agent name into activity metadata. Update all
item, document, comment, and move handlers to use request-based
logActivity/logActivityWithMeta. Remove hardcoded CreatedBy/Source
from all CLI commands — server now determines these from auth context.
* feat: frontend auth — login, registration, auth guard, user menu
Rewrite login page with email/password fields, add registration page
for first-time setup, update auth guard to handle needs_setup redirect.
Add user menu to sidebar with logout. Update API client with new auth
methods (register, login with email, session with needs_setup flag).
* feat: migrate API tokens from workspace-scoped to user-owned
API tokens now have a user_id owner and optional workspace_id scope.
CreateAPIToken takes userID as first parameter. ValidateToken resolves
the token's user into the request context. TokenAuth middleware now
sets ctxCurrentUser when a user-owned API token is used. Add user-
scoped endpoints: GET/POST/DELETE /auth/tokens. Keep workspace-scoped
token endpoints for backwards compatibility.
* feat: workspace membership, invitations, and role enforcement
Add workspace_invitations table (migration 013) with join codes.
Implement invitation store methods (create, get by code, accept,
list). Add member management handlers: list members + invitations,
invite (auto-adds existing users or creates invitation), remove
member, change role, accept invitation by code. Add API routes
under /workspaces/{slug}/members/* and /invitations/{code}/accept.
Add CLI commands: pad members, pad invite, pad join.
* feat: auth tests and documentation updates
Add comprehensive auth endpoint tests: registration flow (first user
becomes admin), login/logout, validation errors, duplicate email,
auth enforcement (401 after users exist, exempt paths), /me endpoint.
Update CLAUDE.md and README.md to document user-based auth system,
replacing old PAD_PASSWORD references with pad login/members/invite
workflow and role-based access control.
* feat: add members management UI to workspace settings page
Add Members section to settings with: member list (avatar, name,
email, role), role change dropdown (owner only), remove button
(owner only), pending invitations display with join codes, and
invite form with email + role picker. Add members API methods to
the TypeScript client (list, invite, remove, updateRole).
* fix: backfill workspace owners for pre-migration workspaces
Add backfillWorkspaceOwners() that runs on server start. For any
workspace with no members, adds the first admin user as owner.
This handles the migration case where workspaces existed before the
user system — without it, the members list shows empty.
* feat: shareable invite links with /join/[code] page
Replace raw join codes with full shareable URLs. Server generates
join_url using its configured base URL (e.g. https://pad.example.com/
join/a3f8b2c1). New /join/[code] page handles the full flow: checks
auth → shows login/register if needed → accepts invitation → redirects
to workspace. Settings page shows "Copy invite link" button that copies
URL to clipboard. CLI outputs shareable link instead of raw code.
* fix: auto-add workspace creator as owner, integrate auth into pad init
handleCreateWorkspace now adds the authenticated user as owner of the
new workspace immediately — no more relying on the startup backfill.
pad init now checks auth status before making API calls. If no users
exist, prompts to register. If not logged in, prompts to login. After
auth, proceeds with workspace creation normally.
* fix: add join_url to invite response type in API client
* fix: address codex review — invite registration, logout token revocation, workspace scoping
- Allow registration with valid invitation_code (fixes invite flow for new users)
- Revoke Bearer session tokens on logout, not just cookies
- Filter workspace listing to user's memberships (admins see all)
|
||
|
|
52c8348361 |
fix: enrich activity log entries with item titles and collection info (#1)
The activity list endpoint returned raw entries without item context, causing the activity page to show bare "Created"/"Updated" verbs. The dashboard already enriched entries via GetItem() lookups — now the activity handler does the same, and the frontend reads top-level fields with metadata fallback. |
||
|
|
cf83a60fc2 |
feat: Add API tokens system for programmatic access
Add a complete API tokens system enabling CI/CD integrations, custom
scripts, and third-party tools to authenticate with the Pad API.
- Migration 011: api_tokens table with hash-based token storage
- Model: APIToken, APITokenCreate, APITokenWithSecret types
- Store: CRUD operations with crypto/rand generation and SHA-256 hashing
- Middleware: Bearer token auth that sets workspace context
- Handlers: POST/GET/DELETE /workspaces/{ws}/tokens endpoints
- CORS: Allow Authorization header for token-based requests
|