Ports upstream's "fix: jwt bypass" into our fork. All of Postiz's JWT
tokens (login, password reset, team invite, integration no-auth action,
enterprise billing portal) are signed with the same secret and were only
checked for the presence of certain fields, not their type or mutual
exclusivity - so a token minted for one purpose (e.g. a password-reset or
team-invite link, which a recipient's browser sends on every request)
could be replayed against a different endpoint (billing, integration
actions, enterprise webhooks) that happened to accept a payload shaped
similarly enough.
Tightens every one of those JWT consumers to:
- require the expected fields to be the correct type (string), not just
truthy
- reject payloads carrying fields unique to a different token kind
(`timeLimit` = team invite, `expires` = password reset)
- cross-check `provider`/`providerIdentifier` on the no-auth integration
action endpoint, closing a path where the wrong provider's integration
could be targeted
- select only `id` from Prisma integration updates instead of returning
the full row (defense in depth, matches the credential-model rule in
CLAUDE.md)
No functional change for any legitimate token flow; verified with
`tsc --noEmit` on apps/backend (zero new errors vs the pre-cherry-pick
baseline - the handful of reported errors are pre-existing, unrelated
`noImplicitAny` issues in agent/media/email files this change never
touches).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Organization.requireApprovalForQueue and Post.pendingApproval existed in
the schema but were never wired up. Adds the ADMIN-only settings toggle,
gates a USER-level member's schedule/publish-now save behind it (held as
a pendingApproval draft instead), and gives ADMIN/SUPERADMIN approve/
reject actions both inline on the calendar card and in a dedicated
Pending Approvals list on the team settings page.
The /compare/socialbee page shipped last round already claims Postiz
supports recycle-after-days evergreen content rotation, but the feature
didn't exist beyond an unused EvergreenRecycle Prisma model and a
RECYCLE enum value an earlier session had added and never wired up.
Built it for real so that claim is true.
- EvergreenRepository/EvergreenService (mirrors the existing
PostEngagementRepository/Service pattern) - create/list/pause/
resume/remove a recycle schedule for an already-published post, plus
a bounded (25/run) runDueBatch() that clones a due post's
content/media/settings into a brand-new Post (own id/group/Comments
thread, CreationMethod.RECYCLE) through the same validatePosts ->
mapTypeToPost -> createPost pipeline every other post-creation path
uses. A failed entry is pushed one interval out instead of retried
immediately; a schedule whose original post was deleted deactivates
itself.
- New daily Temporal workflow evergreenRecycleWorkflow, modeled on the
existing bestTimeToPostWorkflow infinite-loop pattern.
- POST|GET /posts/:id/evergreen and PUT|DELETE /posts/evergreen/:id;
only an already-PUBLISHED post can get a recycle schedule.
- Frontend: a recycle-icon calendar action (published posts only)
opening a modal to view/add/pause/remove recycle schedules.
Verified apps/backend, apps/orchestrator (nest build) and apps/frontend
(full production next build) all build clean with the already-generated
Prisma client.
Schema and some DTO/repository scaffolding for this already existed
uncommitted, but nothing called any of it - createPublicComment silently
dropped mentions/assignedToId even if a client sent them.
- createPublicComment resolves mentions/assignedToId against the org's
team list and rejects anyone not a member, but only for an
authenticated team member - the public no-auth preview link can never
set either field, checked server-side rather than relying on DTO
validation alone.
- New assignComment (+ PUT /posts/comments/:commentId/assign) to change
or clear a root comment's assignee, same org/root-only restrictions as
the existing resolveComment.
- New GET /posts/comments/team-members (any authenticated org member)
backs the mention/assign pickers.
- NotificationService.notifyUser sends a best-effort per-user in-app
notification on a mention or new assignment.
- Data-exposure fix: getComments is shared by the fully public preview
GET and a new authenticated GET (/posts/:id/comments) - mentioned
users' and assignees' names are only included once the caller is
verified as a logged-in member of the post's own org, so an external
reviewer on the public link never sees internal team member names.
Frontend fetches from the authenticated route when logged into the
owning org, the public route otherwise.
- Frontend: mention checkboxes + assign-to select in the composer,
reassign control and a "cc:" line of mentioned names on each thread.
Verified apps/backend, apps/orchestrator, and apps/frontend (full
production next build, including /p/[id]) all build clean.
Finish an in-progress, uncommitted implementation of two backlog items:
- POST/DELETE /public/v1/posts/bulk (up to 25 creates / 50 deletes per
call), sharing the single-post create/delete pipeline per item so one
bad entry never aborts the batch.
- Webhooks.events (additive, empty = every event) lets a webhook
subscribe to just post.published and/or post.failed instead of
everything; wired into the publish and failure delivery paths plus a
frontend checkbox picker.
Verified apps/backend, apps/orchestrator, and apps/frontend all build
clean with the generated Prisma client.
MastodonCustomProvider.generateAuthUrl declared (refresh?: string,
external?: ClientInformation) and called generateUrlDynamic with 5
arguments against its 4-argument signature, which doesn't type-check
against IAuthenticator.generateAuthUrl(clientInformation?) and broke
the apps/backend production build. The only real caller
(integrations.controller.ts) already passes a single ClientInformation
argument; align the signature to that and drop the unused refresh param.
Backend: adds a per-webhook HMAC-SHA256 signing secret, a WebhookDelivery
log model, and WebhooksService.sendWithRetry (3 attempts, exponential
backoff on 5xx/429/408, always persists the outcome). Wires the
orchestrator's post-publish webhook send and the manual /webhooks/send
test endpoint through it instead of a raw fetch with a silently
discarded failure. Adds secret regeneration and a paginated
deliveries/redeliver API.
Frontend: adds a delivery-log modal (apps/frontend/src/components/webhooks/webhook.deliveries.tsx)
with redeliver, a secret-reveal modal on create/regenerate, and wires
up the previously-dead "Regenerate secret" button.
MastodonCustomProvider was fully implemented but disabled in the
registry and inherited MastodonProvider's requiredEnvVars, which would
have blocked every self-hosted instance behind a "not configured on
this server" check even though it registers its own OAuth app per
instance via externalUrl() and needs no global env vars.
- re-enable registration in integration.manager.ts
- clear inherited requiredEnvVars, add a connect toolTip
- map the mastodon-custom identifier to the existing Mastodon composer
component so posts to custom instances render instead of falling
back to the empty composer
document.cookie.split(';').find(p => p.includes('auth=')) matched any
cookie whose string contains that substring, e.g. a `_pin_unauth`
cookie set by another app on the same parent domain. If it sorted
before the real `auth` cookie, Postiz sent it as the auth token, the
backend rejected it, and the user was bounced straight back to login.
Same substring bug existed for showorg/impersonate. Now matches the
exact cookie name via a shared getCookieValue() helper.
Previously the only way out of an organization you no longer wanted to
be part of was deleting your entire Postiz account - deleteTeamMember()
is admin-only (and, after the same-level/self fix in this series, never
allows removing yourself), and there was no self-service alternative.
Adds POST /settings/team/leave: OrganizationService.leaveOrganization()
removes the caller from their current org, blocking the two cases that
would otherwise break the account - leaving your only organization (the
auth middleware always needs at least one non-disabled org to fall back
into) and leaving as the organization's only Super Admin (nobody left
able to manage the team or billing). OrganizationRepository gains
countSuperAdmins() to check the latter.
The team settings page (teams.component.tsx) adds a "Leave organization"
button next to "Add another member", shown only when the user belongs to
more than one organization (reusing the 'organizations' SWR cache key
already used by the org switcher), following the existing confirm-dialog
and toast-on-error pattern used by member removal and invites.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
DELETE /settings/team/:id only blocked removal when the caller's role
level was strictly below the target's (`myLevel < userLevel`). The team
settings UI only ever shows the remove action when the caller's level is
strictly above the target's (teams.component.tsx:
`+myLevel > +getLevel(p.role)`) - it never lets you remove a same-level
peer or yourself. The backend was looser than the UI it backs: calling
the endpoint directly let a SUPERADMIN remove another SUPERADMIN, or
remove themselves - including as the organization's only SUPERADMIN,
orphaning the org with nobody left able to manage the team or billing.
Tightened the check to `myLevel <= userLevel` so the API can't do
anything the UI doesn't already allow. Account deletion's own cleanup
calls the repository method directly and is unaffected.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
processWebhook() looped over every organization id in a RevenueCat event
(app_user_id, original_app_user_id, transferred_from, transferred_to) and
awaited syncSubscription() for each with no try/catch. A TRANSFER event
carries both sides of the transfer, and a transient RevenueCat API error
or an unrecognized product id on the first organization threw out of the
loop, so later organizations in the same event were silently never
synced - exactly the "webhook throws -> billing state half-applied"
failure this codebase already calls out for Stripe/RevenueCat webhook
code. Each organization's sync is now wrapped individually and logs
instead of propagating, matching the console.error pattern already used
in SubscriptionService.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
On a self-hosted instance with a provider's *_CLIENT_ID/SECRET env vars
unset, "Add channel" still listed it and sent the user straight to the
provider with an empty or literal "undefined" client id - the provider's
own error page gave no hint that a Postiz env var was missing, and X's
failure was swallowed into a generic "Unknown Error" toast with nothing
logged server-side (closes#2238).
Adds a generic, provider-declared check instead of a provider-specific
if/else in shared code: SocialAbstract.missingEnvVars() filters each
provider's declared requiredEnvVars against process.env. Every OAuth
provider from the report now declares its required vars; GMB overrides
missingEnvVars() directly since it's configured via its own creds or a
fallback to YOUTUBE_CLIENT_ID/SECRET, not a plain AND of fixed names.
getIntegrationUrl() checks this before building the auth URL and returns
a message naming the missing vars instead of an empty-client-id redirect,
and its catch block now logs the provider and error message instead of
silently swallowing it. The frontend toast shows that message when
present.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The publish workflow only checked firstPost.state === 'QUEUE' once, at
workflow start, then slept until the scheduled publishDate - which can be
days or weeks out. Nothing re-validated the post's state after waking up,
so a post reverted to DRAFT, deleted, or otherwise moved out of QUEUE
during that wait still reached the provider once the sleep ended (#2275).
New post.workflow.v1.1.3 (post.workflow.v1.1.2 is already in production
and workflow files can't be edited in place) adds that re-check right
after the sleep, using the same "Already posted" ERROR path the pre-sleep
check already uses. startWorkflow() and the missing-posts sweep's
signalWithStart() both now start postWorkflowV113 for new executions;
already-running postWorkflowV112 executions keep running under their
original code.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
routeAuth() always called createOrgAndUser() for a new LOCAL registration
before checking for a pending invite, then only afterwards tried to also
add the user to the inviting org via addUserToOrg(). A user registering
through a valid invite link ended up SUPERADMIN of a brand-new throwaway
organization, with the invited org as a bonus membership rather than the
intended destination (closes#2199).
When a valid invite is present, create the user without an organization
and add them straight to the inviting org. Only fall back to a standalone
org if the invite can no longer be redeemed (already used, or the org hit
its seat limit), so the account never ends up with zero organizations.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
/third-party/function/:id/:functionName let any authenticated org member
invoke ANY method found on a third-party provider instance (checkConnection,
sendData, or a future internal helper) just by naming it in the URL - no
allowlist, unlike the analogous video-function dispatch endpoint which
already guards with @ExposeVideoFunction/checkAvailableVideoFunction.
Add the same allowlist shape for third-party providers:
@ExposeThirdPartyFunction + checkAvailableThirdPartyFunction, mark the
handful of methods the frontend actually dispatches this way
(HeyGen generateVoice/voices/avatars, Reel.Farm listMedia), and reject
everything else with a 400 in ThirdPartyController#callFunction.
Added libraries/nestjs-libraries/src/3rdparties/thirdparty.manager.standalone.spec.ts
(RED before the interface export existed, GREEN after); full
*.standalone.spec.ts suite (8 suites/50 tests) still green.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
X's v2 API answers an out-of-credits post with an RFC 7807 problem response
(HTTP 402, body like {"detail":"credits depleted",...}). XProvider.handleErrors
had no case for this body, so fetch() fell through to its generic "Unknown
Error" bad-body message, leaving the bell notification and calendar card
tooltip with no real explanation for why the post never reached X (closes
gitroomhq/postiz-app#2231).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The Moltbook provider leaked its API key into error output via
AxiosError.config.headers; a prior fix sanitized every Moltbook call
site individually. This adds a second, broader layer: a response
interceptor on the shared axios instances every social provider gets
from getSsrfSafeAxios() redacts Authorization, Cookie, Set-Cookie,
Proxy-Authorization, X-Api-Key, Api-Key and X-Auth-Token from
error.config.headers before a rejected request can propagate to logs,
Sentry, or activity failure records.
This closes the same leak for providers that don't individually wrap
every axios call (confirmed real unsanitized-raw-AxiosError paths in
discord.provider.ts and dribbble.provider.ts), without touching the
global `axios` default export used elsewhere in the codebase.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Reconnecting an existing OAuth channel (e.g. YouTube "Add Channel" on
an already-connected channel) creates a temporary integration holding
the fresh refreshToken/tokenExpiration, but saveProviderPage() only
forwards picture/internalId/name/token/profile to updateIntegration().
The temp record then gets soft-deleted and params (missing the refresh
token) is applied to the pre-existing record instead, so the new
refresh token is silently dropped and the channel breaks about an hour
later when the access token expires.
updateIntegration() now reads the temp record's refreshToken/
tokenExpiration before it's soft-deleted and carries them onto the
surviving record's params, but only when the caller didn't explicitly
pass a refreshToken (new-channel connections are unaffected).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
checkValidCard() placed a $1 off-session verification hold on every
trial signup. Per Stripe's India recurring-payments rules, networks
treat any off-session charge as recurring: without a mandate the hold
is declined outright, and even with one it sits in `processing` for
~26h and never reaches `requires_capture`. A valid India-issued card
that already passed 3DS/OTP at Checkout could never complete signup.
Skip the hold entirely for India-issued cards (card.country === 'IN'),
trusting the 3DS the Checkout Session already confirmed. Also fixes a
related bug on the failure path: it detached paymentMethods.data[0]
instead of the latestMethod actually being tested.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Adds the "best time to post" recommendation gap identified against
Buffer/Later, using the bounded design the prior session deliberately
held back instead of unbounded live provider calls per request:
- New PostEngagementSnapshot model: one row per post (upserted in place),
storing UTC day-of-week/hour-of-day and an engagement score derived from
the platform's own existing post analytics.
- New daily Temporal workflow (bestTimeToPostWorkflow, modeled on the
existing missingPostWorkflow infinite-loop pattern) drains up to a hard
capped number of published posts per run via PostEngagementService,
reusing PostsService.checkPostAnalytics rather than any new live-call
path. Expired-token integrations are skipped (not force-refreshed) to
avoid a background job silently disconnecting a channel; transient
provider failures are left as candidates for a later run instead of
permanently excluding a post from its channel's recommendation.
- New read-only GET /analytics/best-time/:integration endpoint aggregates
only the stored snapshots (plain DB groupBy, no provider calls), scoped
to the calling org's integration.
- Frontend: a "Suggested Best Times" panel in the per-channel time-slot
settings modal, with an explicit empty state when there isn't enough
history yet (no fake data), and an "Add" action that feeds a suggestion
straight into the existing autopost time-slot mechanism.
Also fixes an unrelated pre-existing implicit-any (TS7018) on the bulk
schedule post-validation payload in posts.service.ts, found while adding
test coverage for the new aggregation math.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Closes two real feature-parity gaps vs Buffer/Hootsuite/Later found during
a competitive audit (calendar view and per-post/per-platform analytics
already existed in this codebase, so those were not duplicated):
- Bulk CSV scheduling: POST /posts/bulk-schedule schedules many posts from
a pasted CSV (date,content), reusing the exact validatePosts ->
mapTypeToPost -> createPost pipeline the single-post endpoint already
uses, one row at a time, so a bad row never aborts the batch. Scoped to
the providers that need no extra settings beyond __type (threads,
mastodon, bluesky, telegram, nostr, vk) via new providerNeedsSettings()/
simpleTextProviders() helpers derived from the existing allProviders()
data, not a hardcoded per-provider branch. New "Bulk schedule from CSV"
button next to Create Post in the launches sidebar; the channel picker
fetches the supported-provider list from
GET /posts/bulk-schedule/supported-providers instead of duplicating it.
- Client-facing approval: the public preview link already had a
comments/review flow (recaptcha + reviewer-name capture) but no way for
an external client to actually approve a draft. New
POST /public/posts/:id/approve lets them flip a DRAFT post to QUEUE
through the same changePostStatus() path the internal "schedule" button
uses (so the Temporal publish workflow actually starts), and records a
system comment (new additive Comments.isApproval boolean) so the
approval shows in the thread. Only works on posts currently in DRAFT.
Schema: additive only (CreationMethod.BULK_CSV, Comments.isApproval
default false), applied via the existing prisma db push flow.
Also adds jest.standalone.config.js + a test:standalone script: this repo
has no working test runner (@nx/jest's getJestProjects() can't discover
anything without an nx.json), so the pure-logic units added here
(provider-capability check, CSV parsing) get a minimal, self-contained
ts-jest config instead of shipping untested.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
MastodonProvider's handleErrors had no case for HTTP 503, so a
temporarily-unavailable instance fell through to this.fetch's generic
`status === 500` retry branch, which 503 doesn't match, and failed the
post immediately. Add a 503 case returning type: 'retry', the same
pattern TumblrProvider already uses, so this.fetch's existing
retry-with-backoff (and runStreamedUpload's, for media uploads) kicks
in instead of failing on a transient outage.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
countLength('threads', text) used TextEncoder().encode(text).length,
which counts UTF-8 bytes - 2 to 4 per non-ASCII character (accents,
CJK, emoji). That double/quadruple-counted real content against
Threads' 500-character limit in both the UI counter and backend
validation. Array.from(text).length counts actual codepoints, so every
character counts once regardless of encoding width.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Every axios call in MoltbookProvider sent the agent's API key in an
Authorization header and let failures throw the raw AxiosError, which
carries the full request config (including that header) on
err.config/err.toJSON(). That raw error could reach logs, Sentry, or
activity failure details. Catch each call site and rethrow a plain
Error built only from the response status/body, never the config.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The HubSpot app's redirect URL (/oauth/hubspot/callback) dropped people on
the bare calendar, so nothing said the install worked or what to do next.
It now lands on /launches?hubspot=installed, where HubspotInstalled opens a
modal with the next steps in HubSpot (Agent Builder > MCP Servers > Postiz
MCP) and then clears the param. returnUrl brings someone who has to sign in
first back to it. Two new strings in en and the 14 Lingo locales.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since early October the Graph API rejects total_video_impressions on the
video_insights edge with "(#100) The value must be a valid insights
metric", on reels and feed videos alike and on every API version. The
metric is requested together with the others in one call, so the whole
request fails and videoPostAnalytics returns [] for every Facebook video
and reel post. Production logs show 100+ such rejections per hour.
Drop the metric and its Impressions case; the remaining metrics
(total_video_views, total_video_reactions_by_type_total and the reels
ones) are still accepted individually and together.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
VK asked integrations to move from the vk.com hosts to vk.ru
(api.vk.ru, id.vk.ru) by 2025-09-30. Switch the authorize, token,
user_info and API method URLs; the post releaseURL links stay on vk.com.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pinterest's pin creation endpoint intermittently answers with
{"code":2787,"message":"Sorry! Something went wrong on our end."}.
It was unmapped in handleErrors, so the post failed immediately as a
non-retryable BadBody with the 'Unknown Error' placeholder, even though
identical requests succeed minutes later.
Map it to a retry (3 attempts, 5s apart) with a curated message so a
short Pinterest hiccup no longer fails the post, and if it persists the
user sees what actually happened instead of 'Unknown Error'.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Instagram rejects a media container when a collaborator handle cannot be
tagged, with error_subcode 2207018 ("Invalid user id"). handleErrors had no
branch for it, so it fell through to the generic BadBody fallback and the
customer's failure email read "An error occurred while posting to Instagram:
Unknown Error", with nothing pointing at the collaborator tag.
Map 2207018 to a bad-body message naming the three real causes: wrong handle,
private account, or collaborator invites disabled. instagram.standalone
delegates to this handleErrors, so both channel types are covered.
Meta's own error_user_msg is not surfaced instead: it comes back localized to
the connected account's language (Hebrew, in the reproduction), so it is not
usable as user-facing text.
Verified against a live Instagram channel by creating a media container with
the customer's exact handle: pre-fix "Unknown Error", post-fix the new message.
The video is already live when thumbnails.set is rejected, but the post
ended in ERROR with no release URL, so users re-uploaded duplicates. The
provider now throws PublishedWithError with the video id and URL; the post
activity persists them through PostsService.updateResolvedRelease (the
existing org-scoped repository write, state untouched) and rethrows
BadBody, so every workflow version still marks the post ERROR while the
calendar can link to the live video.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The youtube.thumbnail error mapping said 'Your account is not verified',
which customers read as their Postiz account/channel connection - one
customer disconnected and re-added their YouTube channel trying to fix
it. The video is actually live on YouTube in this scenario; only the
thumbnails.set call is rejected because custom thumbnails require a
phone-verified YouTube channel.
The new text states the video was published, names the real requirement
(phone-verified channel, youtube.com/verify) and tells the user how to
set this video's thumbnail manually in YouTube Studio.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Meta returns subcode 1772107 ("Instagram Comment Not Added") from the
first comment call after the post itself was published. It fell back to
"Unknown Error", which hid it from the calendar tooltip and suggested
the whole post failed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getRenewalDate now returns { renewsAt, trialing }: while the Stripe
subscription is trialing, renewsAt is its trial_end and the card says
the free trial ends and the first payment is charged on that date.
After an in-place plan change the renewal date and the credits are
revalidated together with the invoices, so the counters don't mix the
new plan's totals with the old plan's remaining credits.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mention() used the global fetch and read elements without checking the
status, so a 401 surfaced as a TypeError instead of RefreshToken. The
public integration-trigger endpoint and the MCP triggerTool refresh and
retry on RefreshToken, so use SocialAbstract.fetch like the provider's
other calls.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds a Billing cycle card between the plans and the payment method card:
the next renewal date from the payment provider (new getRenewalDate on the
provider interface, null by default, Stripe reads current_period_end of the
live subscription) via GET /billing/renewal, and the remaining AI images,
AI videos and clipping minutes of the current month from the existing
/copilot/credits endpoint.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>