* feat: Re-authorize collaboration connections when access changes
Collaboration connections are authorized once, when the websocket is first
established, so a connection outlives changes to the access it was granted.
Add a processor that publishes access changes to the collaboration servers
over Redis. Each server closes the connections it holds within the scope of
the change and clients reconnect, at which point they are authorized as
normal. Authorization stays in one place, the published scope only has to
cover the connections that may be affected.
The API update subscriber now shares a single Redis connection rather than
opening its own.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* refactor: Log an access change once rather than per connection
Every closed connection is already logged by LoggerExtension, so record the
reason and the number of connections affected once instead. The count also
makes a scope that matches nothing visible.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The parentDocumentId clear in documentPermanentDeleter inherited the Document
default scope, so draft, template, and trial children were never detached and
the foreign key cascade removed them along with the parent.
* fix: Match the base domain on a label boundary
Domain parsing looked for the base domain anywhere in the host, so a host
that merely contained it was classified as a subdomain of the install
rather than as a custom domain. Compare against the end of the host
instead, and reuse the same helper for the custom domain CNAME check.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Normalize host case and trailing root label
Hostnames are case-insensitive and may be given in fully qualified form
with a trailing dot, so normalize both before comparing against the base
domain. Without this a host such as MyTeam.Example.Com is classified as a
custom domain and a valid CNAME target is rejected.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feat: Normalized filter DSL for documents.list and search
Add a structured filter expression language (field/operator/value leaves
composed with AND/OR groups) shared by documents.list, documents.search and
documents.searchTitles. Values are validated against each field's column type
and per-field operator allowlists at the input layer, and translated to
Sequelize where-clauses server-side.
Supersedes the ad-hoc statusFilter/dateFilter/collectionId/userId parameters,
adds ISO 8601 duration matching for date fields, documentId subtree expansion
for search, and preserves draft visibility and collection authorization.
* chore: Fix flaky Encrypted "different key" test
AES-256-CBC is unauthenticated, so decrypting with the wrong key only
raises "bad decrypt" when the garbage plaintext has invalid PKCS#7 padding
(~255/256 of the time). Roughly 1 in 245 runs it decrypts to a non-matching
value instead of throwing, failing the strict toThrow assertion. Accept
either outcome, mirroring the adjacent tampered-data test.
* Hardening
The APIUpdateExtension subscriber connects to REDIS_COLLABORATION_URL when
set, but notifyUpdate always published on the default client, which is bound
to REDIS_URL. With a separate collaboration instance the notification never
reached the collaboration processes, so connected editors did not see API
edits until reload.
Publish on RedisAdapter.collaborationClient, which falls back to the default
client when no collaboration URL is configured.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The wrong-key test asserted a throw, but AES-256-CBC is unauthenticated so
decryption only fails when the resulting plaintext has invalid padding —
around 0.4% of runs returned garbage instead. Accept either outcome, matching
the pattern already used by the sibling tamper test.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Suggested users that share a group with the mentioning user are ranked
above the rest, both in the query so they fit inside the limit, and in
the menu itself.
The server returns a familiarity score per model id, which the client
applies as a multiplier on the relevance score of a suggestion. This
leaves room for other signals, and for other model types, without a
change to the response shape.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Align CSRF cookie resolution between attach and verify paths
The middleware that attaches the token picked one cookie name based on
whether the request was secure, while the verifier accepted either name.
Resolve the name through a single helper so both paths always agree, and
warn at startup when proxy headers are untrusted on an https install.
* Remove excessive tests
* fix: Describe the request scheme on the MCP-derived API context
Helpers shared between the MCP tools and the HTTP routes read the scheme
from the context, which the MCP stub did not provide.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Do not warn about proxy headers when the app terminates TLS itself
The socket is already encrypted in that case, so the request scheme is
known without X-Forwarded-Proto. Extract the certificate check that main
was doing inline so both call sites stay in step.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* simplify
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Skip revision diff when too expensive to compute
Recreating steps from a JSON patch copies and validates the full document
once per operation, so a structure collapse on a very large document could
block the worker event loop for minutes. Skip the changeset when the
product of operation count and document size exceeds a bound, and send
notification emails without the inline preview in that case.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* perf: Apply complexity guard to every patch computation
Centralize patch creation and the maxComplexity check in recalculateOps
so the recomputed patch in addSetNodeMarkup is bounded as well.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix: Consume OAuth authorization codes and refresh tokens atomically
The exchange of an authorization code, and the rotation of a refresh
token, read the credential and deleted it in two steps. Concurrent
requests with the same credential could both pass the read and each
receive a token.
Claim the credential with a single conditional statement instead, so
that only one of a set of concurrent requests continues to token
issuance.
* fix: Move OAuthAuthentications delete to predicate-scoped destroy.
The unfurl response for a share link included the name of the document's
last editor and a relative timestamp. That information is intentionally
withheld from the share document presenter, so drop it here too.
Include the file name in the Content-Disposition header set on S3 objects
at upload time, so browsers keep the uploaded extension instead of
deriving one from the content type.
* fix: Apply MCP preference to dynamically registered OAuth clients
Dynamically registered clients exist only to serve MCP, but the preference
was only consulted at registration time. They are now unreadable once the
preference is off, and their outstanding grants are revoked at the point it
changes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Keep default retry options on revocation task
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* refactor: Rename MCPDisabledProcessor to TeamUpdatedProcessor
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The home branch of pins.list returned every team pin regardless of whether
the linked document was visible to the requesting user, while the document
query was membership-scoped. Filter the pin list to match.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The view activity included in a mention preview was not subject to the
document's insights setting, nor to the ability check that guards the same
data on the other endpoints that expose it. Both are now applied, and the
preview falls back to online status alone when they do not pass.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Unhandled socket error during websocket upgrade crashes server
Node removes its own socket error handling before emitting the "upgrade"
event, so any socket detached from the HTTP server without a listener of
its own will terminate the process when the client goes away.
Handle errors for every upgraded socket in one place, and destroy sockets
we reject rather than leaving them half-open to be reset at any point in
the future.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Flush rejection response before destroying the socket
Destroying immediately after the write can truncate the response if the
socket's write buffer has not drained, leaving the client with a reset in
place of the rejection.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* noisy comment
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Session tokens were accepted from the request body and query string, unlike
the other credential types parsed by the same middleware. They are now only
read from the cookie or the Authorization header.
Short-lived single-use transfer tokens are unaffected, so the subdomain and
desktop sign-in hand-offs continue to work.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Tighten credential handling in OAuth client and batch endpoints
- Include an OAuth client secret in responses only when the presented
credential is itself scoped to manage clients, rather than deciding from
the user's abilities alone.
- Require an interactive session at the authorization endpoint, matching the
batch endpoint, so consent cannot be answered programmatically.
- Resolve a batched sub-request's scope against the dispatched method rather
than the parent path, and always run sub-requests as the parent's
credential.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Address review feedback on naming and documentation
- Name the batch test for what it asserts, as API keys do support per-method
scopes and the rejection comes from the session pin on the route.
- Add the missing @returns tag and terminal punctuation to the presenter's
JSDoc, matching the sibling presenter in the same file.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Apply all content transforms in DocumentHelper.toJSON
replaceInternalUrls was declared async although it does no async work, so the
promise it returned was passed into removeMarks, which returned it untouched
rather than walking it. Made the method synchronous, and typed the local in
toJSON so the compiler reports a promise flowing through the transform chain.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* chore: JSDoc punctuation and explicit return type on replaceInternalUrls
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Allows API clients to detect concurrent edits by rejecting the update
with a 409 when the document revision no longer matches. Collaborative
persists now also increment revisionCount so the check is reliable.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Listing revisions loads the document with paranoid disabled so that history
remains available for a document in the trash, but the accompanying policy
check does not consider deletedAt. Apply the same gate documentLoader uses,
so trashed history follows the same access rules as the document itself.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Proxies commonly forward a Host header without the port the installation is
publicly reachable on, so redirects derived from the incoming request pointed at
the wrong address – most visibly breaking the email magic sign-in link.
* fix: Warn before discarding unsaved template changes
Template content is only persisted when the form is explicitly submitted,
so navigating away or closing the tab silently lost everything typed.
Adds a navigation Prompt and a beforeunload handler to both template
scenes, and reverts the model on unmount so abandoned edits no longer
leak into other views rendering the same record.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Persist templates from the first keystroke
New templates were held only in browser memory until Save was pressed, so
a refresh, crash, or stray navigation lost everything written.
Templates are now created up front as an unpublished draft and autosaved,
mirroring how documents behave. Drafts are visible only to their author
until published, and are cleaned up if abandoned while empty.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Preserve icon edits made during an in-flight template save
applyEdits only restored title and content, so an icon or color changed
while a save was in flight was overwritten by the response and never
re-saved.
Pending edits are now tracked as a single record covering every field the
form can change, rather than one ref per field.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feedback
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Template content is nullable, but the presenter passed it through raw so
a template without content reached the client with no data at all.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Build canonical redirect url from team, not request host
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* test: Cover canonical host redirects
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* perf: Reduce database and Redis round-trips on the MCP endpoint
Profiling production traces for the /mcp endpoint showed the time is
spent in repeated permission and breadcrumb lookups rather than in the
MCP layer itself.
- Cache Document.membershipDocumentIds in Redis, mirroring the TTL and
key pattern of User.collectionIds. The two are resolved together for
every search and this half was uncached, measuring ~200ms.
- Resolve each collection's cached document structure once, concurrently,
when building breadcrumbs for a batch of documents. It was awaited per
document inside a loop, so a page of search results meant a serial
Redis round-trip for every result.
- Walk each collection structure once into a document ID to breadcrumb
map instead of searching the whole tree per document.
- Reuse the collection association already loaded by Document.findByPk
when resolving a single document's breadcrumb, rather than querying it
again under the same membership scope.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Invalidate cached document membership IDs on permission changes
The cache added alongside membershipDocumentIds relied on its TTL alone,
so a revoked grant stayed searchable until it expired. Clear the key on
the paths that change which documents a user is a member of, keeping the
TTL as a backstop.
- UserMembership create and destroy where documentId is set.
- GroupMembership create and destroy where documentId is set, for every
user in the group.
- GroupUser create and destroy, as joining or leaving a group changes
which group grants reach the user.
Sourced memberships are written with hooks disabled and destroyed without
individual hooks, so the parent membership invalidates once for the group
rather than once per descendant.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Resolve notification recipients through the same loader that backs the
public share endpoints, so a subscriber is only mailed about a document
the share would actually serve them.
* fix: Sanitize user-provided name when building export storage keys
Export keys interpolated a document title or collection name straight
into the storage path, so a name containing path separators could move
the archive out of the uploads bucket and into public, where files.get
serves content without authorization.
Sanitize the name down to a single path segment, dedupe the duplicated
key builder in collectionExporter, and reject traversal in LocalStorage
where resolve-path only guards the root, not movement between buckets.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* chore: Complete JSDoc on export key helpers
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: documents.import writes into an unauthorized collection when a parentDocumentId is also given
* test: assert imported child resolves to the parent's collection
suggestions.mention queried User and Group scoped only by team, while
users.list and groups.list both authorize against listUsers/listGroups,
which exclude guests. presentUser withheld the email, but membership in
the result set was unconditional and the query matched on email, so a
guest could enumerate the workspace and probe for addresses.
Gate both reads on the same policies. Documents and collections already
scope to the actor, so guests keep those suggestions.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Friendly error and retry for duplicate team subdomains
Picking a subdomain already in use in settings surfaced the raw unique
constraint violation as a 500, and concurrent signups could race between
the availability check and the insert.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* test: Use setCloudHosted helper rather than spying on env
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* refactor: Move retryOnUniqueConstraintError to storage/database
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Add Invited by and Joined columns to users table
* Move responsive column hiding into column definitions
Adds a hideOnMobile flag to the table column type, handled in the Table
component, replacing per-column isMobile ternaries in the users table.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Import tasks pass a known id to attachmentCreator so a retry can resume,
relying on a caught UniqueConstraintError to skip attachments that already
landed. The file was uploaded to storage before the insert though, so every
skipped attachment was re-uploaded in full and then orphaned, as the storage
key was derived from a fresh uuid rather than the supplied id.
Return the existing attachment before touching storage when the id is already
in use, and derive the key from the supplied id so a collision overwrites the
same object instead of leaking a new one. The lookup is scoped to the team, so
an id belonging elsewhere still falls through to the insert and collides there
as before.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: Unhandled rejection when a Redlock release fails
Releasing a lock is best-effort, a lock that has already expired or been
taken over by another process cannot be released and that is not an error
for the caller. Previously the ExecutionError thrown from release replaced
the successful return value of CacheHelper.populate.
Also catch failures when joining rooms after websocket authentication,
which was a floating promise and so crashed the process.
* fix: Coerce caught values to Error before logging
Deleting a document walked its subtree with one query per document and
destroyed each in a serial post-order recursion, so large subtrees could
exceed the request statement_timeout.
Resolve the subtree with the existing recursive CTE helper and load the
children in a single query instead. Documents are still destroyed one at
a time so model hooks run for each, and deepest-first ordering is kept.
The subtree lookup also dropped the options it was passed, so it ran
outside the request transaction.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
FOR UPDATE conflicts with the FOR KEY SHARE lock Postgres takes on a
parent row when checking a foreign key, so every insert referencing a
collection blocked behind unrelated document structure updates in it.
FOR NO KEY UPDATE still self-conflicts, keeping structure writers
mutually excluded, without blocking child row inserts.
Adds a sourceMetadata JSON column to revisions, populated with the
authentication type of the request that produced the edit, so the
document history sidebar can show "Tom edited via MCP"
* feat: Import PDF documents
Adds a PdfConverter that parses PDF files to markdown with pdf-inspector,
recovering headings, lists and tables from the layout of the text on the
page. A PDF with no embedded text is rejected, as reading it would need OCR.
Markdown has no syntax for underline, so the parser writes underlined text
as an HTML <u> element. Inline HTML is not enabled when the markdown is read
back, so the tags are rewritten to the underline syntax the editor knows.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Accept PDF files in the import dialog, and give it a two column layout
The supported formats move alongside the drop target rather than below it,
so the dialog reads in one glance. Their badge icons are dropped with the
grid they were laid out in, leaving FileFormatIcon unused.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feedback
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* perf: Index-friendly candidate scan in popularity score task
The chunked scan that populates the working table combined "has a non-zero
score" and "has recent insights" into a single OR, which forced a scan of
every document in the partition with a correlated subquery per row. In
production this reached a p95 of 16.9s per chunk on the read replica, which
also serves user reads.
Query each source separately so both can use an index, then union. Limiting
each branch and then the union still yields the globally lowest ids, so keyset
pagination is unchanged. Validity is now a join rather than a predicate, with
the cursor tracked over candidates so filtered rows can't end the walk early.
Adds a partial index on documents(id) where the score is non-zero; the full
index on popularityScore was dropped as unused in 20251217161051 and would not
help this access pattern.
* perf: Drop per-batch COUNT(*) from popularity score task
Every batch issued a COUNT(*) over the working table purely to decide whether
to continue, doubling the round-trips for a loop that already runs thousands of
iterations. processBatch already reports how many rows it handled, so a short
batch is sufficient to detect a drained table.
setupWorkingTable now returns the row count it inserted, which removes the
remaining call site.
* perf: Spread popularity scoring across teams over six hours
The task partitioned by document id over a 30 minute window, which the cron
route expands to one partition per minute. Thirty partitions each took minutes
to run, so they piled up and saturated the database for the whole window.
Partition by team over six hours instead: 360 slices, one starting each minute,
each covering a fraction of the team space. Peak concurrency is bounded by how
long a slice takes rather than by the number of partitions.
Spreading past the hour breaks the interval gate, which read the wall clock at
execution time and so would skip every partition that ran in a later hour --
and worse, would let the next hour's cron schedule a second full run. Cron now
records when a run was scheduled and the gate reads that instead.
The partial index added for the score walk leads with teamId to match the new
access pattern; it is not deployed yet, so it is amended in place.
* perf: Re-key popularity partitions to document id, reduce spread to one hour
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix: Compute scheduledAt once per cron run
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>