Compare commits

...

33 Commits

Author SHA1 Message Date
84b33a7849 fix(auth): close JWT type-confusion bypass (upstream a5affe62)
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>
2026-10-26 17:44:31 +03:00
8e84e2c343 docs: log round 3 build (internal approval workflow) 2026-10-24 01:16:16 +03:00
baa9f112db feat(posts): wire up internal approval workflow for queuing posts
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.
2026-10-24 01:15:39 +03:00
12ec89030d docs: log round 2 build and carry over round 1 architecture/strategy docs
Adds the round-1 architecture and strategy research docs that an
earlier session produced but never committed, and logs round 2's work
(public API bulk endpoints + webhook event filters verified, comment
mentions/assignment wired end to end, evergreen content recycling
built) with the remaining backlog and build verification notes.
2026-10-24 00:54:15 +03:00
1180195e7c feat(posts): add evergreen content recycling
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.
2026-10-24 00:54:08 +03:00
6e962170ad feat(posts): wire comment @mentions and assignment end to end
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.
2026-10-24 00:53:49 +03:00
7b4bd338cd feat(public-api): add bulk post create/delete and webhook event filters
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.
2026-10-24 00:53:35 +03:00
640c307cae docs: log round 1 build (webhook reliability, compare pages, build fix) 2026-10-23 15:35:16 +03:00
65da57ccc7 feat(frontend): add /compare/* competitor landing pages
Adds 7 bottom-of-funnel SEO/conversion pages (/compare/buffer,
hootsuite, later, socialbee, metricool, publer, mixpost) as a new
public route group under apps/frontend/src/app/(app)/(compare)/,
content-driven from compare.data.ts (pricing pulled from the live
pricing.ts config, competitor numbers from STRATEGY-2026-10-23.md's
sourced research) through a shared compare.page.component.tsx layout:
a 4-box structural-moat checklist, a pricing table, a feature
checklist, a verdict, and FAQ entries.

Also fixes proxy.ts (the app's auth middleware), which redirected
every signed-out visitor to /auth by default - without this, the new
pages would 307 for the exact anonymous-searcher audience they target.
Added /compare/ to the existing public-path allowlist alongside
/p/, /provider/, /uploads/.
2026-10-23 15:35:06 +03:00
4198fa47e4 fix(mastodon): match generateAuthUrl to the IAuthenticator interface
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.
2026-10-23 15:34:50 +03:00
88c724bbb3 feat(webhooks): sign, retry, and log webhook deliveries
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.
2026-10-23 15:34:39 +03:00
32270f3f3a docs: add deep pages/APIs/features build plan 2026-10-23 06:55:44 +03:00
ba6d7f8796 fix: enable self-hosted Mastodon instances via the custom provider
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
2026-10-23 06:54:58 +03:00
034d2023ea fix(auth): match cookie names exactly instead of by substring (closes #2135)
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.
2026-10-22 03:33:02 +03:00
77b91f1437 docs: note the lack of a reachable live Postiz deployment
No Postiz container found on railyard-box (the only box reachable via
SSH this session); `box` 130.61.180.42 refuses SSH on port 22 and
recoder-micro rejects the shared deploy key, so neither could be
checked. Recorded as an owner-only blocker instead of guessing at a
deploy target.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-21 18:37:13 +03:00
3e1980a0db feat: let a team member leave an organization themselves
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>
2026-10-21 18:34:43 +03:00
e6d5302996 fix(security): block removing a same-level or self team member via the API
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>
2026-10-21 18:28:10 +03:00
782a88fdde fix: don't let one failing org stop a RevenueCat webhook from syncing the rest
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>
2026-10-21 18:28:02 +03:00
d8200a631c fix: show a clear error instead of sending an empty client ID to OAuth providers
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>
2026-10-21 16:39:13 +03:00
e922a545e7 fix: re-check post state after the scheduling sleep, before publishing
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>
2026-10-21 16:26:11 +03:00
cc2fecf2a7 fix: don't create a junk org when registering via a valid invite link
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>
2026-10-21 16:20:32 +03:00
344662a527 fix(security): allowlist methods callable via third-party function dispatch
/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>
2026-10-21 03:46:17 +03:00
60a29ee456 fix(x): surface X credits-depleted 402 as a clear error instead of Unknown Error
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>
2026-10-20 15:44:39 +03:00
c43f517149 fix(security): redact sensitive headers from axios errors generically (#2220)
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>
2026-10-20 03:32:57 +03:00
8497a30e74 fix: carry the refresh token over when reconnecting an existing channel (closes #2233)
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>
2026-10-20 03:32:49 +03:00
0c785fd37c fix: don't require an off-session card hold for India-issued trial cards (closes #2245)
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>
2026-10-20 03:32:44 +03:00
bb2b7fd0fe feat: add best-time-to-post suggestions backed by a bounded daily batch job
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>
2026-10-20 02:41:11 +03:00
0cd822caa1 feat: add CSV bulk scheduling and client-facing post approval
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>
2026-10-20 02:07:16 +03:00
91051e2e66 fix: retry Mastodon 503s with backoff like other providers
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>
2026-10-19 13:42:55 +03:00
86475231d1 fix: gate Stripe.js load behind the billing-enabled flag
loadStripe() injects the js.stripe.com script (and its fingerprinting
requests) as soon as it's called, regardless of whether the key is
valid, and FirstBillingComponent called it unconditionally on mount.
It relied entirely on its parent only rendering it when billing is on.
Check billingEnabled/stripeClient directly before loading Stripe so it
never loads when billing is disabled for this deployment.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-19 13:42:52 +03:00
bf2998a3f9 fix: count Threads post length by Unicode codepoint, not UTF-8 bytes
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>
2026-10-19 13:42:49 +03:00
456d84041f fix: stop Moltbook API key leaking via raw AxiosError
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>
2026-10-19 13:42:46 +03:00
9203a696a6 fix: don't crash backend startup when Mastra/Postgres init fails
startMcp() connects Mastra to Postgres on first use; a DB outage or
misconfiguration there rejected start() before app.listen() ever ran,
taking down every route in the backend, not just /mcp and /copilot.
Wrap it in try/catch so a failure is logged and the rest of the
backend still boots.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-19 13:42:43 +03:00
132 changed files with 9109 additions and 589 deletions

138
ARCHITECTURE-2026-10-23.md Normal file
View File

@ -0,0 +1,138 @@
# Postiz Architecture — 2026-10-23
Scope note: this doc covers competitive-positioning-adjacent technical architecture, user-action data flow, risks, and a next-build list. Pages/APIs/feature backlog is covered by `PLAN-2026-10-23-DEEP.md` if/when that file exists — it did not exist at the time this was written, so nothing here duplicates it.
## 0. Ground truth on this repo (read, not assumed)
- Fork: `caelum0x/postiz-app` (origin), tracking `gitroomhq/postiz-app` (upstream). AGPL-3.0.
- Monorepo, pnpm workspaces, 5 apps + shared libraries:
- `apps/backend` — NestJS REST API (port 3000), also boots the Mastra MCP server and Temporal worker in-process (`apps/backend/src/main.ts`).
- `apps/orchestrator` — NestJS + Temporal worker: all background workflows/activities (posting, autopost, clipping, video, email, token refresh).
- `apps/frontend` — **Next.js 16** app (App Router), not Vite as `CLAUDE.md` currently states — confirmed by `next.config.js`, `instrumentation.ts`, `sentry.server.config.ts`, and root `package.json` (`"next": "16.3.1"`).
- `apps/sdk` — thin TypeScript client hard-coded to `https://api.postiz.com` (Postiz Cloud), used for the published npm SDK.
- `apps/commands` — CLI entry (`main.ts` + `tasks/`: `refresh.tokens`, `agent.run`, `configuration`).
- `apps/extension` — Chrome extension (manifest-style background script) that extracts auth cookies from logged-in social sites for providers that need cookie-based auth, allow-listed to `localhost` and `*.postiz.com` origins only.
- `libraries/nestjs-libraries` — shared backend code: Prisma database layer, 35+ `integrations/social/*.provider.ts` (one per channel), `chat/` (Mastra-based AI agent + MCP server + MCP OAuth relay), `deepgram/`, `videos/`, `short-linking/`, `services/payment/` (Stripe).
- Database: **PostgreSQL** via **Prisma** (schema at `libraries/nestjs-libraries/src/database/prisma/schema.prisma`, 91 models). Includes the app's own domain tables (Organization, User, Integration, Post, Media, Subscription, Webhooks, Clipping, ...) plus `mastra_*` tables — the AI agent/MCP framework (Mastra) persists its own state (threads, messages, MCP server/client registrations, workflows) directly in the same Postgres instance (`libraries/nestjs-libraries/src/chat/mastra.store.ts`).
- Queue/orchestration: **Temporal** (`@temporalio/*`, `nestjs-temporal-core`), with its own Postgres + Elasticsearch stack in `docker-compose.yaml` (`temporal-postgresql`, `temporal-elasticsearch`, `temporal`, `temporal-ui`). This replaced a simpler queue — there is no BullMQ in the current flow.
- Cache: **Redis** (`ioredis`), falls back to an in-memory `MockRedis` if `REDIS_URL` is unset (`libraries/nestjs-libraries/src/redis/redis.service.ts`). Used for rate-limiting (`ThrottlerBehindProxyGuard`) and caching, not as the job queue.
- Storage: pluggable — local disk, Cloudflare R2, or S3-compatible (`STORAGE_PROVIDER` env var; `@aws-sdk/client-s3` + `UPLOAD_DIRECTORY`).
- AI stack: LangGraph (`@langchain/langgraph`, `@langchain/openai`, `@langchain/tavily`) for the content-generation agent graph (`libraries/nestjs-libraries/src/agent`), and **Mastra** (`@mastra/core`, `@mastra/mcp`, `@mastra/pg`) for the chat/tool-calling layer that backs both the in-app chat UI and the external MCP server (`/mcp`, `/mcp/:id`, `/sse/:id` routes, started from `start.mcp.ts`).
- Payments: Stripe (`services/payment/`), webhook-driven subscription sync.
- Public API: `apps/backend/src/public-api` — `/public/v1/*` routes, API-key authenticated, rate-limited distinctly from session routes. This is what the published SDK and MCP server call into.
## 1. Deployment reality (do not assume Oracle hosting applies here)
- There is **no live Postiz deployment** on any of the three portfolio boxes right now (confirmed in this repo's own `NOTES.md`: not running on `railyard-box`, `box` 130.61.180.42 currently refuses SSH, `recoder-micro` rejects the shared deploy key). This product has zero live users today — it exists only as code + a `docker-compose.yaml` for local/self-hosted use.
- Self-hosting is the only supported open-source deployment path: `docker-compose.yaml` ships `postiz` (backend+frontend combined container, port 4007), `postiz-postgres`, `postiz-redis`, the full Temporal stack (`temporal`, `temporal-postgresql`, `temporal-elasticsearch`, `temporal-ui`), and optional `spotlight` (Sentry-compatible local error capture). `railway.toml` and the README's deploy table (Docker / Coolify / Railway / any VPS) confirm self-host, not a managed Cloudflare/Oracle target.
- **Postiz Cloud** (`postiz.com`, what `apps/sdk` talks to) is a separately-hosted commercial SaaS *not present in this repo* — it is the thing this OSS edition is positioned against/alongside, not something deployed from here.
- Net: the correct hosting target for this product, if the owner wants it live, is a self-hosted Docker Compose stack on one of the Oracle boxes (recommended: `box` once SSH is restored, given it's the general-purpose box) — not Cloudflare Workers/Pages (no edge-compatible target exists here; Temporal workers and a Postgres-backed Nest app don't fit the Workers runtime model).
## 2. System diagram (real components only)
```mermaid
flowchart TB
subgraph Clients
WebUI["Frontend\nNext.js 16 (App Router)"]
Ext["Chrome Extension\n(cookie capture for\ncookie-auth providers)"]
CLI["apps/commands CLI\n(agent.run, refresh.tokens)"]
MCPClient["External MCP client\n(Claude/ChatGPT/agent, via SDK or MCP)"]
end
subgraph Backend["apps/backend (NestJS, port 3000)"]
API["/api, /posts, /integrations\n(session-authed)"]
PublicAPI["/public/v1/*\n(API-key authed)"]
MCPServer["Mastra MCPServer\n/mcp, /mcp/:id, /sse/:id"]
Chat["Chat/Agent module\n(LangGraph + Mastra tools)"]
end
subgraph Orchestrator["apps/orchestrator (Temporal worker)"]
Workflows["Workflows:\npostWorkflowV1.x, autopost,\nclipping, generate.video,\nrefresh.token, digest.email"]
Activities["Activities:\npost.activity, clipping.activity,\nmedia.activity, integrations.activity"]
end
subgraph Data["Data & infra"]
PG[("PostgreSQL\n(Prisma: app tables +\nmastra_* AI-agent tables)")]
Redis[("Redis\n(cache + rate-limit;\nin-memory fallback)")]
Temporal[("Temporal server\n+ its own Postgres + ES")]
Storage[("Object storage\nlocal disk / S3 / R2")]
end
subgraph ThirdParty["Third-party services"]
Social["28+ social platform APIs\n(X, LinkedIn, Facebook,\nInstagram, TikTok, ...)"]
OpenAI["OpenAI (text + DALL-E)"]
Tavily["Tavily (web search)"]
Deepgram["Deepgram (transcription)"]
Stripe["Stripe (billing)"]
end
WebUI -->|session cookie| API
Ext -->|extracted cookies, postiz.com only| API
CLI --> API
MCPClient -->|API key / OAuth relay| MCPServer
MCPServer --> Chat
Chat --> OpenAI
Chat --> Tavily
Chat --> PG
API --> PG
API --> Redis
API -->|start workflow| Temporal
PublicAPI --> API
PublicAPI --> Temporal
Temporal --> Workflows
Workflows --> Activities
Activities --> PG
Activities --> Social
Activities --> Deepgram
Activities --> Storage
Activities --> OpenAI
API --> Stripe
Stripe -->|webhook| API
```
## 3. Data-flow for the 2-3 most important user actions
### A. Schedule and publish a post (core product loop)
1. User composes a post in the Next.js frontend; frontend calls `POST /posts` (or the public `/public/v1/posts` if driven via SDK/MCP/CLI) with content + target integrations + send time.
2. `PostsController.createPost` (DTO-validated) calls `PostsService.createPost`, which writes `Post` + per-channel settings rows via Prisma to Postgres (one write, no raw SQL per project convention).
3. `PostsService.startWorkflow` first lists/terminates any existing running Temporal workflow for that `postId` (idempotency guard), then starts `postWorkflowV1.1.3` (versioned — workflow code is never mutated in place; new behavior ships as a new version, see CLAUDE.md rule) on Temporal's `main` task queue, tagged with `postId`/`organizationId` search attributes.
4. Temporal dispatches the workflow to the `apps/orchestrator` worker process. The workflow sleeps until the scheduled time, re-checks post state (to catch a cancel/edit during the sleep), then calls `post.activity` → the relevant `integrations/social/*.provider.ts` implementation, which calls the real platform API (X, LinkedIn, etc.) using stored OAuth tokens.
5. Activity result (success/failure, remote post id) is written back to the `Post`/`Integration` rows in Postgres; failures retry per-activity with backoff (non-retryable reasons — e.g. revoked token — short-circuit).
6. Frontend polls/SWR-refetches post status from Postgres via the backend API.
### B. AI chat / MCP-driven content generation (agent surface)
1. A request arrives either via the in-app chat UI (session-authed, hits `Chat` module) or an external MCP client (Claude Desktop, ChatGPT app, or any MCP-compatible agent) calling the Mastra `MCPServer` at `/mcp` (or `/mcp/:id` for a specific self-hosted-instance relay, or `/sse/:id` for SSE transport), authenticated via an API key or the `/mcp-oauth*` OAuth relay (`mcp.relay.service.ts`, `oauth-middleware.ts`) for multi-tenant/self-hosted setups.
2. Mastra resolves the caller's org/auth context (`auth.context.ts`, `async.storage.ts`) and exposes a fixed toolset (`chat/tools/*.tool.ts`: list integrations, generate image, upload from URL, delete post, check video status, trigger integration, etc.) plus the LangGraph agent for free-text generation (web search via Tavily, image gen via OpenAI DALL-E).
3. Tool calls that mutate state (e.g. create/delete a post, trigger an integration) go through the same `PostsService`/`IntegrationService` Prisma-backed code path as the UI — no separate write path — landing in the same Postgres tables.
4. Mastra persists its own conversation/thread/tool-call state in the `mastra_*` Postgres tables (same database, separate tables) so a chat session survives a backend restart.
5. Any action that needs background work (video generation, clipping) hands off to Temporal exactly like path A, rather than blocking the MCP response.
### C. Long-video-to-clips pipeline (Deepgram clipping — the feature with no direct competitor equivalent per the strategy doc)
1. User submits a source video URL/upload; `ClippingService.submitAnalyse` creates a `Clipping` record and calls the `clipping.workflow` on Temporal.
2. Workflow step 1 (`submitClippingAnalyse`/`checkClippingAnalyse`): analysis job submitted to an external job runner and polled (bounded retries, each poll idempotent).
3. Workflow step 2 (`transcribeClipping`): Deepgram transcribes the audio (`deepgram.service.ts`).
4. Workflow step 3 (`pickClippingClips`): an AI call (OpenAI, via the same agent infra) scores the transcript and picks clip boundaries; result written to `ClippingClip` rows.
5. Workflow step 4, per clip: `submitClipFetch`/`checkClipFetch` then `submitClipRender`/`checkClipRender` — fetch the source segment and render the final clip (burned-in captions via `captionClip`), stored to the configured object storage backend.
6. `createClippingDrafts` turns finished clips into draft `Post` rows so the user schedules/publishes them through the normal path A loop — the clipping pipeline is a *producer* of posts, not a separate publishing path.
7. Failure handling is deliberately asymmetric: submission steps tolerate at-least-once (a duplicate job just costs a second render), AI/transcription steps are cheap to retry, and only the final terminal failure (`failClipping`) surfaces to the user.
## 4. Real architectural risks / bottlenecks at current scale (zero live users, zero budget)
- **Not deployed anywhere — the biggest risk is literally "it doesn't run."** All competitive positioning in `STRATEGY-2026-10-23.md` is moot until a live instance exists for a self-hoster to even evaluate, let alone for the growth moves (comparison pages, clipping landing page) to point at a working demo/signup.
- **Three stateful backing services for one app** (Postiz's own Postgres, Temporal's own Postgres, Temporal's own Elasticsearch) plus Redis — a fourth Postgres-class dependency (Elasticsearch) purely so Temporal UI can do visibility search. On a zero-budget single small VPS/Oracle box this is a meaningful memory/CPU footprint (ES alone typically wants 512MB+ heap, already reflected in the compose file's `ES_JAVA_OPTS=-Xms256m -Xmx256m` ceiling) for a product with no users yet. Worth evaluating whether Temporal's SQL-only visibility (no ES) is enough at this scale, dropping the ES container entirely.
- **Single shared Postgres for app data and AI-agent (Mastra) state.** Convenient operationally (one DB to back up), but couples chat/agent load (threads, tool-call logs, MCP registrations) to core posting-data performance and backup size as usage grows — no isolation today.
- **OAuth app setup is the activation cliff**, confirmed by the strategy doc's own top growth move: every self-hoster must register their own developer app per social platform (Meta/TikTok/YouTube approval can take weeks per the README's own comparison table). This is a product-structural bottleneck, not a hosting one — a feature gap, not infra.
- **Self-host-only in practice right now**: no managed hosting exists for this fork (Postiz Cloud at postiz.com is a different, separately-run codebase/infra this repo doesn't touch), so every prospective user must run Docker Compose with 7+ containers themselves — a steep floor for the "technical solo marketer" persona the strategy doc targets, some of whom are not comfortable operating Temporal/Elasticsearch.
- **Cookie-based extension auth is inherently fragile**: providers relying on the Chrome extension's cookie capture (vs. OAuth) break whenever the target platform changes its cookie names/session model, and only work for users running the extension on a logged-in browser — not something a CI/server environment can do.
- **Versioned-workflow discipline is a real but easy-to-violate constraint**: the `post.workflow.v1.x.ts` ladder (14 versions already) means every behavior change to the publish flow adds a new file rather than editing in place — correct for Temporal determinism, but it is pure accretion with no visible deprecation/cleanup path for old versions once no running executions reference them.
## 5. Prioritized next-build list (effort vs. impact)
1. **Get one instance live on an Oracle box (box, once SSH access is restored) — lowest effort, highest impact.** `docker-compose.yaml` already defines the full stack; this is an infra/ops task (bring up containers, point a subdomain at port 4007, set real env vars), not a code change. Nothing else on this list, or in the strategy doc's growth moves, matters while zero instances are reachable.
2. **Guided OAuth-app pre-registration wizard** (strategy doc's own #1 growth move, and this doc's #1 architectural risk). Medium effort: extend the existing `apps/commands` CLI/`configuration.ts` task with a step-by-step per-provider wizard (pre-filled redirect URIs, direct links to each platform's developer console, validation against `missing-env-vars.standalone.spec.ts`'s existing checks) rather than a hosted-credentials fallback, which would require Postiz to hold shared app secrets — a bigger trust/ops commitment for a zero-budget operation.
3. **Drop or make-optional the Elasticsearch dependency in `docker-compose.yaml`** for the self-host default path. Low effort (Temporal supports SQL-only visibility), direct reliability/resource win for the exact persona (small VPS, zero budget) this product targets — makes self-hosting materially lighter before pushing anyone to try it.
4. **Standalone landing page for the Deepgram clipping pipeline** (strategy doc's #3 growth move) — this is a content/marketing build, not an architecture change, but it depends on #1 (a live instance to demo/sign up through) and is the one feature with zero named-competitor equivalent, so it is the highest-leverage SEO/positioning asset once something is live.
5. **Add a lightweight cleanup/documentation pass over the `post-workflows` version ladder** — low urgency, but before adding a 15th version, worth confirming (via Temporal's visibility query) which old versions have zero running executions and can be safely archived, so the versioning discipline doesn't silently become unbounded technical debt.

130
BUILD-LOG-2026-10-23.md Normal file
View File

@ -0,0 +1,130 @@
# Build Log — 2026-10-23
## Round 1
### 1. Webhook delivery reliability (backlog item #6) — finished + fixed
Picked up an in-progress, uncommitted implementation and finished it to a working, verified state.
- `WebhookDelivery` Prisma model (additive migration): `webhookId`, `event`, `postId`, `url`, `requestBody`, `statusCode`, `success`, `attempts`, `error`, `durationMs`, indexed on `webhookId` and `(webhookId, createdAt)`.
- `Webhooks.secret` column (nullable, additive) — a per-webhook HMAC-SHA256 signing secret generated on create, exposed to the UI exactly once (at creation or regeneration), never again on list/read.
- `WebhooksService.sendWithRetry` — signs the payload (`X-Postiz-Signature: sha256=...`), retries up to 3 attempts with exponential backoff (500ms × 3^n) on 5xx/429/408, treats other 4xx as terminal, and always persists a `WebhookDelivery` row (success or failure) with status code, attempt count, error, and duration.
- `apps/orchestrator/src/activities/post.activity.ts`'s `sendWebhooks` now calls `sendWithRetry` instead of a raw unsigned `fetch` + silent catch.
- New endpoints on `webhooks.controller.ts`: `POST /webhooks/:id/secret` (regenerate), `GET /webhooks/:id/deliveries` (paginated log), `POST /webhooks/deliveries/:deliveryId/redeliver`. `/webhooks/send` (manual test-send) now also signs, dispatches through the existing SSRF-safe dispatcher, and returns a real status instead of swallowing errors.
- Frontend: `apps/frontend/src/components/webhooks/webhook.deliveries.tsx` (new) — paginated delivery log modal with status, attempts, error, and a redeliver action. `webhooks.tsx` wires a "Logs" column into the webhook list and a secret-reveal modal on create/regenerate.
- **Fix applied this round**: the "Regenerate secret" button existed as dead code (handler defined, never rendered) — wired it into the edit form, visible only when editing an existing webhook.
- Verified: `apps/backend`, `apps/orchestrator`, and `apps/frontend` all build clean (`nest build` / `next build`) with the new Prisma client generated.
### 2. Competitor comparison landing pages (backlog item #4) — built new, full depth
Built all 7 pages named in STRATEGY-2026-10-23.md section 5, as real statically-rendered routes with zero API/DB dependency, each sourced from the live `pricing.ts` config and the strategy doc's researched competitor numbers (not invented):
- `/compare/buffer`, `/compare/hootsuite`, `/compare/later`, `/compare/socialbee`, `/compare/metricool`, `/compare/publer`, `/compare/mixpost`
- New public, unauthenticated route group `apps/frontend/src/app/(app)/(compare)/` (mirrors the existing `(preview)` pattern — doesn't use the auth-gated `(site)` shell).
- `apps/frontend/src/components/compare/compare.data.ts` — per-competitor content: headline, pricing comparison rows, the 4-box structural-moat checklist from STRATEGY.md section 2, a feature checklist, a verdict paragraph, and FAQ entries (for SEO rich snippets).
- `apps/frontend/src/components/compare/compare.page.component.tsx` — shared presentational layout (hero, structural checklist table, pricing table, feature checklist, verdict, FAQ, CTA), using the app's existing `new*` color tokens, glyph check/cross icons (no emoji), and `/auth` as the signup CTA.
- 7 thin `page.tsx` files, each with per-page `<title>`/description/canonical metadata.
- **Critical fix applied this round**: `apps/frontend/src/proxy.ts` (the app's auth gatekeeper middleware) redirected every anonymous visitor to `/auth` by default — which would have made all 7 new pages return a 307 redirect for the exact audience (anonymous searchers) they exist to convert. Added `/compare/` to the existing public-path allowlist alongside `/p/`, `/provider/`, `/uploads/`.
- Verified live: built the frontend in production mode, ran `next start`, and curled all 7 routes — all return `200` with the correct per-competitor `<title>` and rendered content (confirmed before and after the proxy fix, showing the before-state 307 and after-state 200).
### 3. Pre-existing broken production build — fixed (not in the numbered backlog, but blocking everything)
`apps/backend` failed to compile on `HEAD` (commit `ba6d7f87`, already merged to main before this session) — `MastodonCustomProvider.generateAuthUrl` had a signature (`refresh?: string, external?: ClientInformation`) that didn't match the `IAuthenticator` interface (`clientInformation?: ClientInformation`) and called `generateUrlDynamic` with 5 arguments against a 4-argument signature. Fixed to match the interface and the only real call site (`integrations.controller.ts`'s `generateAuthUrl(getExternalUrl)`). Confirmed `apps/backend` now builds clean.
## Files changed this round
- `libraries/nestjs-libraries/src/database/prisma/schema.prisma` — `WebhookDelivery` model, `Webhooks.secret`
- `libraries/nestjs-libraries/src/database/prisma/webhooks/webhooks.repository.ts`, `webhooks.service.ts`
- `libraries/nestjs-libraries/src/dtos/webhooks/webhooks.dto.ts`
- `apps/backend/src/api/routes/webhooks.controller.ts`
- `apps/orchestrator/src/activities/post.activity.ts`
- `apps/frontend/src/components/webhooks/webhooks.tsx`, `webhook.deliveries.tsx` (new)
- `apps/frontend/src/proxy.ts`
- `apps/frontend/src/components/compare/compare.data.ts` (new), `compare.page.component.tsx` (new)
- `apps/frontend/src/app/(app)/(compare)/layout.tsx` (new) + 7 `compare/<slug>/page.tsx` (new)
- `libraries/nestjs-libraries/src/integrations/social/mastodon.custom.provider.ts` (build fix)
## Remaining backlog (not started this round)
2 (unified inbox), 3 (internal approval workflow), 5 (agency PDF/CSV reports), 7 (competitor tracking), 8 (auto first-comment), 9 (content recycling), 10 (local short-link provider — noted below), 11 (white-label preview domain), 12 (public API bulk + webhook event filters), 13 (comment @mentions/assignment), and item #1 (OAuth onboarding wizard).
Note on #10 (local short-link provider): `ShortLinkService` currently selects its provider via a module-load-time static singleton (`new Dub()` / `new Kutt()` / etc., no DI), so a DB-backed "local" provider needs that singleton refactored to an injectable service first — flagged for a later round rather than bolted on against the grain of the existing pattern.
## Owner-only blockers
None hit this round — no payment, 2FA, or console-only step was required for any of the above.
## Round 2
### 1. Public API bulk endpoints + webhook event filters (backlog item #12) — finished + verified
Picked up an in-progress, uncommitted implementation (schema, DTOs, controller, webhook send-path filtering, and the frontend event checkboxes already existed) and verified it end to end rather than re-building it:
- `POST /public/v1/posts/bulk` (up to 25 posts/call) and `DELETE /public/v1/posts/bulk` (up to 50 ids/call) on `public.integrations.controller.ts`, both sharing the exact single-post create/delete pipeline per item so a bad entry never aborts the batch.
- `Webhooks.events String[]` (additive, empty = every event, same backward-compatible default as the rest of this feature) — `post.activity.ts`'s `sendWebhooks`/the new `changeState` failure path only deliver to webhooks subscribed to that event (or subscribed to none, meaning all).
- No code changes needed; confirmed by building `apps/backend`/`apps/orchestrator`/`apps/frontend` clean.
### 2. Comment @mentions and assignment (backlog item #13) — finished, was previously just schema + DTOs with no wiring
The schema (`Comments.mentionedUserIds`/`assignedToId`, `Notifications.userId`) and some repository/DTO scaffolding already existed uncommitted, but nothing called any of it — `createPublicComment` silently dropped `mentions`/`assignedToId` even if a client sent them, and there was no team-member list or assignment endpoint anywhere.
- `PostsService.createPublicComment` now resolves `mentions`/`assignedToId` against `OrganizationService.getTeamMembersForMentions` and rejects anyone not on the team — but only when the comment is from an authenticated team member (`userId` set); the public no-auth preview link can never set either field, even if a crafted request body includes them (checked server-side, not just via DTO validation).
- New `PostsService.assignComment` (+ `PUT /posts/comments/:commentId/assign`) to change/clear a root comment's assignee after the fact, same org/root-only restrictions as the existing `resolveComment`.
- New `GET /posts/comments/team-members` (any authenticated org member, not gated behind the admin-only `/settings/team`) backs the mention/assign pickers.
- `NotificationService.notifyUser` (new, wraps the already-existing `createUserNotification` repository method) sends a best-effort, per-user in-app notification on a mention or a new assignment.
- **Data-exposure fix applied this round**: `PostsService.getComments` is shared by the fully public preview GET (`PublicController`) and now also a new authenticated GET (`PostsController`, `GET /posts/:id/comments`) — mentioned-user names/ids and the assignee's name are only included when the caller is verified as a logged-in member of the org that owns the post (`includeInternal` gate), so an external client on the public preview link never sees internal team members' names. The frontend (`preview.comments.context.tsx`) now fetches from the authenticated route when logged into the owning org, the public route otherwise — same branching `CommentComposer` already used for posting.
- Frontend: mention checkboxes + an "Assign to" select in the comment composer (root comments only for assignment), an assignee reassign `<select>` and a `cc:` line of mentioned names on each thread card, all in `apps/frontend/src/components/preview/comments.components.tsx` / `preview.comments.context.tsx`.
- Verified: `apps/backend`, `apps/orchestrator` (`nest build`) and `apps/frontend` (full production `next build`, including `/p/[id]`) all build clean.
### 3. Evergreen content recycling (backlog item #9) — built new, full depth
This was the biggest gap found this round: `/compare/socialbee` (shipped round 1) already **claims** "Postiz supports a recycle-after-days, category-based queue rotation for evergreen content" — but the feature didn't exist beyond an unused `EvergreenRecycle` Prisma model and a `RECYCLE` enum value some earlier session had added and never wired up. Built it for real so that comparison-page claim is true:
- `EvergreenRepository`/`EvergreenService` (new, mirrors the existing `PostEngagementRepository`/`Service` pattern) — create/list/pause/resume/remove a recycle schedule for an already-published post, plus a bounded (`BATCH_CAP = 25`) `runDueBatch()` that clones a due post's content/media/settings into a brand-new `Post` row (own id/group/Comments thread, `CreationMethod.RECYCLE`) through the exact same `validatePosts` → `mapTypeToPost` → `createPost` pipeline every other post-creation path uses — not a new, parallel content-writing path. A failed entry is pushed one interval out instead of retried immediately, and a recycle schedule whose original post was deleted deactivates itself instead of erroring forever.
- New daily Temporal workflow `evergreenRecycleWorkflow` (`apps/orchestrator/src/workflows/evergreen.recycle.workflow.ts` + `evergreen.activity.ts`), modeled on the existing `bestTimeToPostWorkflow` infinite-loop pattern, registered in `app.module.ts` / `workflows/index.ts` / `infinite.workflow.register.ts`.
- `POST|GET /posts/:id/evergreen` and `PUT|DELETE /posts/evergreen/:recycleId` on `posts.controller.ts`; only an already-`PUBLISHED` post can get a recycle schedule.
- Frontend: a new "Evergreen Recycling" calendar action (recycle-glyph icon, shown only on published posts) opening `evergreen.modal.tsx` — lists existing schedules with pause/resume/remove, and a form to add one (interval days + optional max recycles).
- Verified: `apps/backend`, `apps/orchestrator` (`nest build`) and `apps/frontend` (full production `next build`) all build clean with the already-generated Prisma client (schema/client were already in place from the earlier session; no schema change needed this round).
## Files changed this round (Round 2)
- `libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts`, `posts.repository.ts` — comment mentions/assignment wiring, `getComments` internal-field gate
- `apps/backend/src/api/routes/posts.controller.ts` — authenticated comments GET, comment-assign PUT, team-members GET, evergreen CRUD routes
- `libraries/nestjs-libraries/src/database/prisma/notifications/notification.service.ts` — `notifyUser`
- `libraries/nestjs-libraries/src/database/prisma/organizations/organization.repository.ts`, `organization.service.ts` — already had `getTeamMembersForMentions` from the earlier session, now actually called
- `apps/frontend/src/components/preview/comments.components.tsx`, `preview.comments.context.tsx` — mention/assign UI, authed-vs-public comments fetch
- `libraries/nestjs-libraries/src/database/prisma/evergreen/evergreen.repository.ts` (new), `evergreen.service.ts` (new)
- `libraries/nestjs-libraries/src/dtos/posts/evergreen.recycle.dto.ts` (new)
- `apps/orchestrator/src/activities/evergreen.activity.ts` (new), `workflows/evergreen.recycle.workflow.ts` (new), `workflows/index.ts`, `app.module.ts`
- `libraries/nestjs-libraries/src/temporal/infinite.workflow.register.ts`
- `libraries/nestjs-libraries/src/database/prisma/database.module.ts`
- `apps/frontend/src/components/launches/calendar.tsx`, `evergreen.modal.tsx` (new)
- `libraries/nestjs-libraries/src/database/prisma/schema.prisma`, `apps/backend/src/public-api/routes/v1/public.integrations.controller.ts`, `apps/frontend/src/components/webhooks/webhooks.tsx`, `apps/orchestrator/src/activities/post.activity.ts`, `libraries/nestjs-libraries/src/dtos/posts/bulk.posts.dto.ts`, `libraries/nestjs-libraries/src/dtos/webhooks/webhooks.dto.ts`, `libraries/nestjs-libraries/src/database/prisma/webhooks/webhooks.repository.ts` — pre-existing uncommitted work from an earlier session (backlog item #12), verified working this round, no changes needed
## Remaining backlog (not started)
2 (unified inbox), 3 (internal approval workflow — note: `Organization.requireApprovalForQueue`/`Post.pendingApproval` schema fields already exist uncommitted from an earlier session but are completely unwired, same as evergreen was; next target), 5 (agency PDF/CSV reports, note: `pdfkit` is already added to `package.json` from an earlier session but unused), 7 (competitor tracking), 8 (auto first-comment), 10 (local short-link provider), 11 (white-label preview domain), and item #1 (OAuth onboarding wizard).
## Owner-only blockers (Round 2)
None hit this round.
## Round 3
### 1. Internal approval workflow (backlog item #3) — built new, full depth
`Organization.requireApprovalForQueue` and `Post.pendingApproval` existed in the schema from an earlier session but had zero wiring (same shape of gap evergreen recycling and comment mentions were in before prior rounds). Wired it end to end:
- `Post.createdByUserId` (new, additive, nullable) + `User.createdPosts` back-relation — stamped on create from the WEB dashboard only, so an approver knows (and can be notified) who submitted a pending post. Every other creation path (API/MCP/autopost/bulk CSV/evergreen/clipping) never sets it, unaffected.
- `OrganizationRepository`/`OrganizationService`: `getApprovalForQueueSetting`/`updateApprovalForQueueSetting`/`requiresApprovalForQueue`. New `GET|POST /settings/approval-queue` (POST is ADMIN-gated), same shape as the existing shortlink-preference endpoints.
- `PostsService.createPost` now takes an optional `createdBy: { userId, role }` (WEB controller only). When the caller's role is `USER`, the save type is schedule/now, and the org has the setting on, the post is held as `DRAFT` with `pendingApproval: true` instead of going to `QUEUE` — `PostsRepository.createOrUpdatePost` grew the `createdByUserId`/`pendingApproval` params to do this at the DB layer. `PostsRepository.changeState` now always clears `pendingApproval`, since every path that calls it is an intentional final transition.
- `PostsService.approvePendingQueuePost`/`rejectPendingQueuePost` (+ `PUT /posts/:id/approve-queue`, `PUT /posts/:id/reject-queue`, ADMIN-gated) — approve reuses `changePostStatus` (the same path the internal "schedule" button and the public-preview `approvePublicPost` already use, so the real publish workflow actually starts); reject just clears the flag and leaves it a normal, editable draft. Both notify the original submitter via the existing `NotificationService.notifyUser`.
- `PostsService.getPendingApprovalPosts` + `GET /posts/pending-approval` (ADMIN-gated, declared before the generic `/:id` GET to avoid Nest route-matching ambiguity).
- Frontend: a yellow clock badge + inline Approve/Check and Reject/X glyph icons (no emoji) on the calendar card itself when `state === 'DRAFT' && post.pendingApproval`, visible only to ADMIN/SUPERADMIN viewers; a "Pending approval:" label replaces "Draft:" on the card. New `apps/frontend/src/components/settings/approval-queue-preference.component.tsx` (the toggle) and `pending-approvals.component.tsx` (the list with Approve/Reject buttons), both rendered in `teams.component.tsx` only for ADMIN+ roles. `manage.modal.tsx`'s save flow shows a distinct "Submitted for approval" toast instead of "Added/updated successfully" when the response indicates it.
- Verified: `apps/backend`, `apps/orchestrator` (`nest build`) and `apps/frontend` (full production `next build`, including route generation) all build clean with the newly generated Prisma client (`prisma validate` + `prisma generate` both clean).
## Files changed this round (Round 3)
- `libraries/nestjs-libraries/src/database/prisma/schema.prisma` — `Post.createdByUserId`, `User.createdPosts`
- `libraries/nestjs-libraries/src/database/prisma/organizations/organization.repository.ts`, `organization.service.ts` — approval-for-queue setting
- `libraries/nestjs-libraries/src/dtos/settings/approval-for-queue.dto.ts` (new)
- `apps/backend/src/api/routes/settings.controller.ts` — `GET|POST /settings/approval-queue`
- `libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts` — `createOrUpdatePost`/`changeState` pendingApproval wiring, `getPendingApprovalPosts`, select additions
- `libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts` — `createPost` gating, `approvePendingQueuePost`/`rejectPendingQueuePost`/`getPendingApprovalPosts`
- `apps/backend/src/api/routes/posts.controller.ts` — caller role on `createPost`, `GET /posts/pending-approval`, `PUT /posts/:id/approve-queue`, `PUT /posts/:id/reject-queue`
- `libraries/helpers/src/utils/posts.list.minify.ts` — `pendingApproval` key mapping
- `apps/frontend/src/components/launches/calendar.tsx` — badge, approve/reject actions and icons, pending-approval label
- `apps/frontend/src/components/new-launch/manage.modal.tsx` — "submitted for approval" toast
- `apps/frontend/src/components/settings/approval-queue-preference.component.tsx` (new), `pending-approvals.component.tsx` (new), `teams.component.tsx` — settings UI
## Remaining backlog (not started, Round 3)
2 (unified inbox), 5 (agency PDF/CSV reports — `pdfkit` still unused in `package.json`), 7 (competitor tracking), 8 (auto first-comment), 10 (local short-link provider), 11 (white-label preview domain), item #1 (OAuth onboarding wizard).
## Owner-only blockers (Round 3)
None hit this round. The pre-existing "no reachable live Postiz deployment" blocker (NOTES.md) was not re-checked this round since it wasn't this round's scope.

3
NOTES.md Normal file
View File

@ -0,0 +1,3 @@
# Notes (owner-only blockers)
- No live Postiz deployment found on any reachable box (not running on `railyard-box`; `box` 130.61.180.42 refuses SSH on port 22 right now, `recoder-micro` 92.5.156.133 rejects the shared deploy key) — owner needs to either confirm there's no live Postiz instance yet, or restore access/point me at the right host to deploy `origin/main` (caelum0x/postiz-app) to.

117
PLAN-2026-10-23-DEEP.md Normal file
View File

@ -0,0 +1,117 @@
# Postiz — Deep Build Plan (2026-10-23)
Internal build spec. Terse. Ground truth only (verified against source at this commit). No stubs described as done.
## Conventions
- Auth: `session` = cookie session guard (`AuthService`/org context). `apikey` = `/public/v1/*` API-key guard. `none` = unauthenticated.
- UI controls: icon/glyph buttons only, no emoji, no bare-word action buttons (e.g. a send action = arrow glyph, a confirm = check glyph, a close = × glyph).
## 1. Pages (apps/frontend/src/app)
| Route | Purpose | Key UI elements |
|---|---|---|
| `(site)/launches` | Calendar + composer, main workspace | Month/week/list view toggle (icon group), per-day post chips, "+" new-post button (icon), platform picker (icon grid from `pick.platform.component.tsx`), composer modal (`manage.modal.tsx`) with per-channel tabs, char counter, media picker, tag selector, schedule date/time picker, bulk-schedule CSV upload |
| `(site)/analytics` | Per-channel metrics | Channel selector (icon tabs), date-range picker, line/bar charts, best-time-to-post heatmap |
| `(site)/media` | Media library | Grid of uploads, upload button (icon), drag-drop zone, delete (icon), AI-generate-image/video entry points |
| `(site)/plugs` | Automations list | Plug cards (toggle switch to enable/disable), create-plug modal, per-integration function picker |
| `(site)/settings` | Org/team/shortlink | Team member list + role badges, invite-link generator (copy icon), shortlink domain field, danger-zone delete-account |
| `(site)/billing`, `billing/lifetime` | Subscription mgmt | Plan cards, upgrade/downgrade buttons, Stripe portal link (external-link icon), coupon field, lifetime-deal claim form |
| `(site)/third-party` | App marketplace | App cards, install/connect button (icon), per-app function list |
| `(site)/agents`, `agents/[id]` | AI agents | Agent list, chat thread view, credits counter, new-thread button (icon) |
| `(site)/admin/errors`, `admin/stats` | Admin-only diagnostics | Error table (filter by platform dropdown), stats cards; gated by admin role check in loader |
| `(site)/err` | Generic error page | Error message, retry button (icon) |
| `(preview)/p/[id]` | Public post preview/approval | Post render, comment thread, approve/reject buttons (check/× icons), no auth |
| `auth`, `auth/login`, `auth/activate(+[code])`, `auth/forgot(+[token])`, `auth/login-required` | Auth flows | Email/password fields, OAuth provider buttons (icon + provider name), activation code input, reset-password form |
| `integrations/social/[provider]` | OAuth connect-callback landing | Spinner, success/fail state, auto-redirect to `/launches` |
| `oauth/authorize` | 3rd-party OAuth-app consent | App name/logo, scope list, allow/deny buttons (check/× icons) |
| `(extension)/modal/[style]/[platform]` | Chrome-extension popup | Minimal connect-status UI, close icon |
| `provider/[p]`, `provider/add` | Standalone provider connect (no main app shell) | Same picker/connect flow as in-app, used for embeds |
## 2. APIs (apps/backend/src/api/routes, no global prefix; apps/backend/src/public-api for `/public/v1`)
Format: `METHOD path — auth — req → resp`.
### auth.controller.ts
- `GET /auth/can-register` — none — → `{ register: boolean }`
- `POST /auth/register` — none — `{ email, password, company?, providerToken? }` → `{ id, jwt? }`
- `POST /auth/login` — none — `{ email, password }` → `{ jwt }` (cookie set)
- `POST /auth/forgot`, `POST /auth/forgot/return` — none — email → ack / token+password → ack
- `GET /auth/oauth/:provider`, `POST /auth/oauth/:provider/redirect`, `POST /auth/oauth/:provider/exists` — none — provider OAuth bootstrap
- `POST /auth/activate`, `POST /auth/resend-activation` — session/none — code → ack
- `POST|GET /auth/farcaster/signer` — none — Farcaster signer flow
### posts.controller.ts
- `GET /posts`, `GET /posts/:id`, `GET /posts/group/:group` — session — → `Post[]`/`Post`
- `POST /posts` — session — `{ type, date, tags, posts: [{ integration, content, settings }] }` → created post group
- `PUT /posts/:id/date` — session — `{ date }` → ack
- `DELETE /posts/:group` — session — → ack
- `GET /posts/:id/statistics`, `/missing` — session — → metrics / missing-channel list
- `GET|PUT /posts/:id/release-url`, `/release-id` — session — published-URL bookkeeping
- `GET|POST /posts/:id/comments`, `POST /posts/comments/:commentId/resolve` — session — approval-thread comments
- `GET|POST|PUT|DELETE /posts/tags` — session — tag CRUD
- `GET /posts/find-slot(/:id)` — session — → next free scheduling slot
- `POST /posts/bulk-schedule`, `GET /posts/bulk-schedule/supported-providers` — session — CSV rows → created posts
- `POST /posts/generator`, `/generator/draft` — session — `{ prompt, integrations }` → AI-generated caption(s)
- `GET /posts/separate-posts` — session — per-channel content split
### integrations.controller.ts / no.auth.integrations.controller.ts
- `GET /integrations` — none — → public provider list (name, identifier, toolTip, picture)
- Connect/settings/nickname/group/custom-name endpoints — session — per-integration config
- `GET /integrations/social/:integration` — none — OAuth callback landing
- `POST /integrations/social-connect/:integration` — none — external-URL-based connect (used by `mastodon-custom`, `lemmy`, `wordpress`, `listmonk`)
- `POST /integrations/public/provider/:id/connect` — apikey — connect via public API
- `GET|POST|PUT|DELETE /integrations/plug/list(+CRUD)` — session — automation CRUD
- `GET /integrations/mentions` — session — → mentionable handles
- `POST /integrations/function` — session — plugin function dispatch (allowlisted per `third-party.controller.ts` security fix already shipped)
- `GET /integrations/telegram/updates` — session — Telegram webhook polling
- `POST|GET /integrations/moltbook/register(+status)` — session
### billing.controller.ts
- Stripe/RevenueCat: `check/:id`, `check-discount`, `apply-discount`, `finish-trial`, `embedded`, `subscribe`, `sync`, `portal`, `invoices`, `renewal`, `cancel(-subscription)`, `prorate`, `charges+refund-charges`, `coupon-info/apply-coupon/cancel-coupon`, `chatbase-refund`, `add-subscription` — session — standard Stripe-shaped req/resp
### media / copilot / clipping
- `media.controller.ts`: `upload-server`, `upload-simple`, `save-media`, `generate-image(-with-prompt)`, `generate-video`, `video/function`, `video-options`, `media/:id/status` — session
- `copilot.controller.ts`: `POST /copilot/chat`, `/agent`, `GET /copilot/credits`, `/:thread/list`, `/list` — session — chat/agent assistant
- `clipping.controller.ts` + `.widget.controller.ts`: CRUD `/clipping`, `GET /clipping/:id`, `/clipping-widget/status` — session/none(widget)
### webhooks / sets / signature / autopost
- `webhooks.controller.ts`: CRUD `/webhooks` + `POST /webhooks/send` — session
- `sets.controller.ts`: CRUD `/sets` (reusable templates) — session
- `signature.controller.ts`: CRUD `/signatures` — session
- `autopost.controller.ts`: CRUD `/autopost` + `/:id/active` + `/send` — session
### third-party / oauth / oauth-app
- `third-party.controller.ts`: list, submit, function dispatch (allowlisted), import — session
- `oauth.controller.ts`: full OAuth2 provider — `register/authorize/token/userinfo` — mixed
- `oauth-app.controller.ts`: self-serve OAuth-app CRUD + secret rotation — session
### settings / users / analytics / enterprise / stripe / payment / admin
- `settings.controller.ts`: team CRUD, `team/add`, `team/:id` delete, `team/leave`, shortlink get/set — session
- `users.controller.ts`: `/user/self`, `/personal`, `impersonate`, switch-org, `/organizations`, `join-org`, `change-org`, `delete-account(-info)`, `logout`, `/subscription(+tiers)` — session
- `analytics.controller.ts`: `/:integration`, `/post/:postId`, `/best-time/:integration` — session
- `enterprise.controller.ts`: `create-user`, `url`, `delete-channel` — apikey (enterprise)
- `stripe.controller.ts` / `payment.controller.ts`: `POST /stripe`, `POST /payment/:provider` — none (webhook, signature-verified)
- `admin.controller.ts`: `/errors(+/platforms)`, `/stats` — session (admin role)
### Misc
- `notifications.controller.ts`, `announcements.controller.ts`, `approved-apps.controller.ts`, `monitor.controller.ts` (queue status) — session
- `public.controller.ts`: public post view/comments/approve, `GET /public/stream` (SSE) — none
- `root.controller.ts`: `GET /` — none — health
### Public API v1 (`apps/backend/src/public-api/routes/v1/public.integrations.controller.ts`, `@Controller('/public/v1')`)
- CRUD `/posts`, `/upload(+-from-url)`, `/integrations`, `/groups`, `/me`, `/analytics/*`, `/clipping`, `/notifications`, `/credits/reset`, `/debug/*` — apikey — backs `apps/sdk` (`@postiz/node`)
## 3. Features
| Feature | Data touched | Dependencies | Remaining |
|---|---|---|---|
| 34→35 social providers | `Integration` table | `integration.manager.ts` registry, per-provider class | Done this session: `mastodon-custom` enabled (was commented out, had no standalone `requiredEnvVars`, no composer mapping — all 3 fixed). Still open: audit per-provider `checkPostStatus`/`finalizePost` override coverage against `SocialAbstract` stubs |
| Chrome extension cookie-auth | none (client-side cookie read) | `provider.registry.ts`, `manifest.json` host_permissions | Only Skool implemented; needs one module per cookie-auth provider + manifest permission entries. Medium effort, not started |
| AI post generator + copilot agent | `Post`, `mastra_*` tables | LangGraph, Mastra, OpenAI key | Functional; no gaps found this audit |
| Video clipping | `Clipping`, `ClippingClip` | Temporal orchestrator, Deepgram | Functional |
| Best-time-to-post | `Post` stats | bounded daily batch job (already shipped) | Functional |
| OAuth2 dev platform + public API + SDK | `OAuthApp`, API keys | `oauth.controller.ts`, `apps/sdk` | Functional; SDK is hard-coded to `api.postiz.com`, self-hosted users must override base URL manually — not currently exposed as a documented env/config option in the SDK client. Not fixed this session (separate scope from provider gap) |
| Live deployment | n/a | Oracle boxes (SSH/deploy-key access) | OWNER BLOCKER — no box currently reachable with working SSH/deploy key. Self-host via existing `docker-compose.yaml` once access restored; code is deploy-ready as-is |
## 4. This session's commit
- `fix(mastodon): enable self-hosted Mastodon instances via the custom provider` — uncomments `MastodonCustomProvider` registration, makes it not inherit `MASTODON_CLIENT_ID`/`SECRET` requirement (it doesn't use them — it registers a per-instance app via `externalUrl()`), adds `toolTip`, and maps `mastodon-custom` to the existing generic `MastodonProvider` composer component so posts to custom instances render/compose correctly instead of falling back to `Empty`.

89
STRATEGY-2026-10-23.md Normal file
View File

@ -0,0 +1,89 @@
# Postiz Strategy — 2026-10-23
Scope note: this document covers competitive positioning, differentiation, user
research (persona + journey map), and growth moves. It deliberately does not
cover page/API/feature build-out — see `PLAN-2026-10-23-DEEP.md` if present for
that (not found in the repo at time of writing, 2026-10-23).
Grounded in the actual repo state at `/Users/arhansubasi/products/postiz-app`
(fork `caelum0x/postiz-app`, upstream `gitroomhq/postiz-app`, AGPL-3.0):
- 36 real social/channel providers under `libraries/nestjs-libraries/src/integrations/social/*.provider.ts` (Instagram, X, LinkedIn page+personal, TikTok + TikTok Business, Facebook, YouTube, Pinterest, Reddit, Threads, Bluesky, Mastodon, Discord, Slack, Telegram, Dev.to, Hashnode, Medium, WordPress, Tumblr, Twitch, VK, Dribbble, GMB, Farcaster, Nostr, Lemmy, Beehiiv, HubSpot, Skool, Whop, Listmonk, Kick, Mewe, Moltbook, etc.) plus Resend/node-mailer for email channels.
- Real AI stack: `libraries/nestjs-libraries/src/agent/agent.graph.service.ts` (LangGraph + GPT-4.1 + Tavily web search + DALL-E image gen), `libraries/nestjs-libraries/src/openai/openai.service.ts`, `chat/start.mcp.ts` + `chat/mcp.relay.service.ts` (Postiz runs its own MCP server), `chat/load.tools.service.ts` and `chat/tools/generate.image.tool.ts` / `generate.video.tool.ts`.
- Real video-clipping pipeline: `libraries/nestjs-libraries/src/database/prisma/clipping/clipping.service.ts` — Temporal-orchestrated long-video-to-clips with Deepgram transcription, i.e. an OpusClip-style feature bundled into a scheduler.
- Real public API + SDK + CLI + browser extension: `apps/sdk` (`@postiz/node` on npm), `apps/commands` (CLI), `apps/extension`, plus listed n8n node and Make.com integration in the README.
- Production pricing config confirmed in code at `libraries/nestjs-libraries/src/database/prisma/subscriptions/pricing.ts`:
FREE $0 (0 channels), STANDARD $29/mo ($278/yr, 5 channels, AI on, public API, 60 clipping min, 3 video gens, 20 image gens), TEAM $39/mo (10 channels, team members, autopost), PRO $49/mo (30 channels, 300 clipping min), ULTIMATE $99/mo (100 channels, 600 clipping min, 10k webhooks).
- Open-core model confirmed in README: "We do not gate features or limit the license" between self-hosted and Postiz Cloud — same product either way.
## 1. Direct competitors
- **Buffer** (buffer.com)
- Pricing: Free (3 channels, 10 scheduled posts/channel); Essentials $5/mo per channel; Team $10/mo per channel (unlimited seats).
- Strongest feature: simplest onboarding in the category, cleanest UI, cheapest true per-channel entry price.
- Weakest point: no self-hosting, no public API/MCP for agent workflows, no video-clipping or AI web-research-backed caption generation, per-channel pricing gets expensive fast past ~6 channels.
- **Hootsuite** (hootsuite.com)
- Pricing: Standard $99/mo billed annually (10 accounts), Professional $199/mo, Advanced $399/mo. No free plan.
- Strongest feature: deepest enterprise feature set (approval workflows, social listening, large team permissions).
- Weakest point: priced for enterprise only — same 10-channel ceiling costs $1,197/mo once 3 users + approvals are added vs. Postiz TEAM at $39/mo flat; no self-host option, no AGPL/open-source trust story.
- **Later** (later.com)
- Pricing: Starter $18.75/mo (annual), Growth $37.50/mo, Scale $82.50/mo. No free plan.
- Strongest feature: best visual/Instagram-grid planning UX for creators.
- Weakest point: no X/Twitter support at all; no self-hosting; no AI agent/MCP surface; no video clipping.
- **SocialBee** (socialbee.com)
- Pricing: Bootstrap $29/mo (5 profiles), Accelerate $49/mo (10 profiles), Pro $99/mo (25 profiles, 3 users).
- Strongest feature: evergreen content recycling / category-based queue rotation.
- Weakest point: flat per-tier profile caps with no team seats below Pro ($99/mo); no open-source/self-host option; no public API or MCP server.
- **Metricool** (metricool.com)
- Pricing: Free (1 brand, 20 posts/mo, X and LinkedIn excluded); paid plans priced per brand starting ~$20/mo, Advanced ~$53/mo for 10 profiles/3 users/approvals.
- Strongest feature: best-in-class analytics and competitor tracking.
- Weakest point: X and LinkedIn gated behind paid tiers even on "included" lists; no AI content agent, no video clipping, closed source.
- **Publer** (publer.io)
- Pricing: Free tier (3 accounts, no X, 10 scheduled posts each); paid from $5/mo for one account + $4/extra account on Professional; ~$32/mo for 10 channels/3 users with approvals.
- Strongest feature: cheapest true cost-at-scale among SaaS competitors.
- Weakest point: no self-hosting, no public API/MCP/SDK/CLI, no video clipping, no bundled AI web-research agent.
- **Mixpost** (mixpost.app) — the direct self-hosted/open-source competitor
- Pricing: Lite free (Facebook Pages, X, Mastodon only); Pro $299 one-time (all platforms, API, MCP, basic white-label, 1 year of updates included, renew for updates after); Enterprise $1,199 one-time (white-label + resale billing). Hosting is extra ($5-20/mo VPS).
- Strongest feature: true perpetual-license, zero-recurring-fee model; Laravel/PHP stack is familiar to a large existing dev audience.
- Weakest point: Lite (the free tier) only supports 3 channels; Laravel stack has a smaller AI/LangChain ecosystem than Node — no bundled video-clipping/transcription pipeline, no bundled web-research agent comparable to Postiz's LangGraph+Tavily+DALL-E graph; a lapsed license freezes you on an old version with no update path short of repaying.
## 2. Exact differentiation plan (per competitor, specific axis)
- **vs. Buffer**: undercut on per-channel economics at scale — Postiz STANDARD is $29/mo flat for 5 channels ($5.80/channel) vs Buffer Essentials at $5/channel but with zero AI, zero public API, and zero self-host option; message this as "Buffer's price, plus a public API, MCP server, and AI agent Buffer doesn't have at any price."
- **vs. Hootsuite**: undercut on the exact workflow Hootsuite overcharges for — team seats + approval at 10 channels. Postiz TEAM is $39/mo flat (10 channels, team members, autopost) vs Hootsuite's $1,197/mo for the equivalent (Advanced + 3 seats). Put this side-by-side number on the pricing page, not a vague "cheaper" claim.
- **vs. Later**: ship/keep full X (Twitter) support — Later has none — and lead marketing copy for Instagram-grid-style creators with "every channel Later has, plus X, Threads, Bluesky, and 20+ more."
- **vs. SocialBee**: give team seats at the $29 tier (SocialBee requires $99 Pro for any team member); this is already true in Postiz's own pricing.ts (STANDARD lacks team_members=false actually — check: STANDARD has team_members:false too). Correction built into point below — see Note.
- **vs. Metricool**: never gate X or LinkedIn behind a higher tier — confirm (from pricing.ts) that channel count is the only paid gate, not platform identity; make that an explicit comparison-page claim ("every channel, every tier, no platform tax").
- **vs. Publer**: win on what Publer structurally cannot ship — self-host AGPL deployment, the `@postiz/node` SDK, the CLI (`apps/commands`), the browser extension (`apps/extension`), and the native MCP server (`start.mcp.ts`) that lets Claude/ChatGPT/Codex agents schedule posts directly. Publer has none of these; put "runs your own MCP server" on the comparison page as a literal checklist row.
- **vs. Mixpost (the real fight, since it's the other self-hosted option)**: win on the recurring-feature-velocity axis Mixpost's perpetual-license model can't match — Postiz's LangGraph agent (`agent.graph.service.ts`) does live web research via Tavily before drafting a post, and generates images via DALL-E inline; Mixpost's Pro tier has an MCP integration but no bundled LLM agent graph or video-clipping pipeline. Lead with the clipping feature (`clipping.service.ts` + Deepgram transcription) as a feature SocialBee/Buffer/Later/Mixpost all lack entirely — "turn one long video into scheduled clips across every channel" is not offered by any competitor above, open-source or SaaS.
- **Cross-cutting structural moat**: Postiz is the only product in this list that is simultaneously (a) open-source/self-hostable, (b) has a managed cloud option at Buffer-adjacent pricing, (c) ships a public API + npm SDK + CLI + browser extension + native MCP server, and (d) bundles an LLM agent with live web search and video generation. No single named competitor above checks more than 2 of those 4 boxes. Make that 4-box checklist the hero comparison-table structure on the Postiz Cloud vs. [X] landing pages instead of a generic feature list.
Note on the SocialBee bullet above: Postiz's own STANDARD tier in `pricing.ts` has `team_members: false`; team seats start at TEAM ($39/mo). The accurate claim is therefore "Postiz gives team seats one tier up at $39/mo vs SocialBee's $99/mo Pro" — a $60/mo gap, not "team seats at $29." Use the corrected $39-vs-$99 number on any comparison page.
## 3. Primary user persona / ICP
- **Primary persona: the technical/solo marketer at a small SaaS or dev-tool company (1-10 person team) who already pays for Supabase/Neon/Resend-style infra and is comfortable self-hosting.**
- Job to be done: get consistent multi-platform posting (especially X, LinkedIn, Reddit, Discord/Slack for community) live without hiring a social media person, and automate it from existing dev workflows (n8n/Make/Zapier, or directly from an AI agent via MCP) rather than hand-typing into five separate native composer UIs.
- Why this persona, grounded in the repo: Postiz's own README leads with the dev-tool ecosystem (n8n node, Make.com integration, Postiz Node SDK, AI-agent integrations for ChatGPT/Claude/Codex/Cursor/Grok listed in the README's agent-icon row) — the product is built for people who want posting as a callable primitive, not a composer UI.
- Secondary persona: a small agency or community team (the TEAM/PRO tier shape — 10-30 channels, multiple members, autopost) managing several client/brand accounts who wants self-host cost control instead of Hootsuite's per-seat tax.
## 4. User journey map (discovery -> paying/retained user)
1. **Discovery** — finds Postiz via: GitHub (AGPL repo, currently ~37.5k+ stars per competitor research), a "Buffer alternative" / "open source Buffer alternative" search or blog post, or an AI-agent tooling list (MCP server directories, n8n/Make marketplace listings).
2. **Evaluation** — compares self-host (free, own infra) vs. Postiz Cloud (`platform.postiz.com`) pricing against Buffer/Mixpost; reads the open-core claim ("we do not gate features") to confirm no rug-pull risk.
3. **First setup** — either (a) self-hosts via Docker Compose (`docker-compose.yaml`/`docker-compose.dev.yaml`) and needs Postgres+Redis+env vars configured correctly, or (b) signs up on Postiz Cloud directly. **This is the single biggest drop-off risk step**: self-hosting Postiz requires correctly provisioning OAuth app credentials for every platform the user wants (each provider needs its own developer-app registration — e.g. Meta app review for Instagram/Facebook, X API tier, TikTok app approval) before a single post can be scheduled; this setup friction is categorically worse than any SaaS competitor's "click to connect" OAuth, and is where a self-host-curious technical user is most likely to abandon before ever publishing a post.
4. **Activation** — connects first channel(s), schedules/publishes first post; for the AI-agent persona, activation instead means wiring the MCP server or Node SDK into an existing agent/workflow and getting the first automated post out.
5. **Habit formation** — returns weekly/daily via the calendar view, analytics, or an automated pipeline (n8n/Make/agent) that keeps posting without manual re-entry.
6. **Monetization trigger** — hits a FREE-tier wall (FREE has 0 channels in `pricing.ts`, i.e. it is effectively a trial/demo tier, not a usable free plan) and must upgrade to STANDARD ($29/mo) to connect even one channel, or needs a 6th+ channel / team member / clipping minutes beyond STANDARD's caps.
7. **Retention / expansion** — adds team members (TEAM), add more channels/clipping minutes/webhooks (PRO/ULTIMATE), or becomes a public-API/MCP power user embedding Postiz into their own product or internal tooling, which raises switching cost substantially versus a SaaS-only competitor.
## 5. Three concrete growth moves specific to this product
- **Ship a one-click "OAuth app pre-registration" path or a hosted-credentials fallback for self-hosters.** Since step 3 above (per-platform OAuth app setup) is the confirmed biggest activation blocker for the exact self-host-first ICP this product targets, offer self-hosters an opt-in "use Postiz Cloud's shared OAuth apps for your first N posts, bring your own after" mode, or a guided CLI wizard (building on the existing `apps/commands` CLI) that walks through each provider's app-creation steps inline. This directly targets the step with the highest measured drop-off risk in the journey map above, not a generic onboarding tweak.
- **Publish head-to-head comparison pages for each competitor above, using the exact numbers in this doc** (Buffer $5/channel vs. Postiz $29 flat/5 channels + API+MCP; Hootsuite $1,197/mo vs. Postiz TEAM $39/mo for the same 10-channel/3-seat/approval shape; Mixpost's $299 one-time but no agent-graph/clipping vs. Postiz Cloud's bundled AI+clipping). These are the kind of bottom-of-funnel, high-intent "X vs Postiz" pages that convert searchers already comparing tools — and every number here is pulled from the live `pricing.ts` and competitor pricing pages found above, not invented.
- **Package the video-clipping pipeline (`clipping.service.ts` + Deepgram) as its own standalone landing page/feature — "turn one long-form video into scheduled social clips" — since no competitor named above (Buffer, Hootsuite, Later, SocialBee, Metricool, Publer, Mixpost) offers this at all.** This is a real, already-built, differentiated feature with zero direct competitive overlap in this specific product category; a dedicated page targeting "repurpose long video to short clips scheduler" search intent captures a search behavior none of the 7 named competitors can answer directly from their own feature set.

View File

@ -4,13 +4,15 @@ import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.reque
import { ApiTags } from '@nestjs/swagger';
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
import { PostEngagementService } from '@gitroom/nestjs-libraries/database/prisma/post-engagement/post-engagement.service';
@ApiTags('Analytics')
@Controller('/analytics')
export class AnalyticsController {
constructor(
private _integrationService: IntegrationService,
private _postsService: PostsService
private _postsService: PostsService,
private _postEngagementService: PostEngagementService
) {}
@Get('/:integration')
@ -30,4 +32,15 @@ export class AnalyticsController {
) {
return this._postsService.checkPostAnalytics(org.id, postId, +date);
}
// Reads only from the pre-aggregated PostEngagementSnapshot table (see
// PostEngagementService) - no live provider calls on this path, so it is
// safe to call on every composer/calendar render.
@Get('/best-time/:integration')
async getBestTimeToPost(
@GetOrgFromRequest() org: Organization,
@Param('integration') integration: string
) {
return this._postEngagementService.getBestTimes(org.id, integration);
}
}

View File

@ -71,7 +71,13 @@ export class EnterpriseController {
webhookUrl: string;
}>(params);
if (!load || !load.redirectUrl || !load.apiKey || !load.provider) {
if (
!load ||
!load.redirectUrl ||
!load.apiKey ||
typeof load.apiKey !== 'string' ||
!load.provider
) {
return;
}
@ -117,7 +123,13 @@ export class EnterpriseController {
id: string;
}>(params);
if (!load || !load.apiKey || !load.id) {
if (
!load ||
!load.apiKey ||
!load.id ||
typeof load.apiKey !== 'string' ||
typeof load.id !== 'string'
) {
return { success: false };
}

View File

@ -3,6 +3,7 @@ import {
Controller,
Delete,
Get,
Logger,
Param,
Post,
Put,
@ -41,6 +42,8 @@ import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integration
@ApiTags('Integrations')
@Controller('/integrations')
export class IntegrationsController {
private readonly _logger = new Logger(IntegrationsController.name);
constructor(
private _integrationManager: IntegrationManager,
private _integrationService: IntegrationService,
@ -247,6 +250,27 @@ export class IntegrationsController {
throw new Error('Missing external url');
}
// Building the auth URL with an unset client id/secret sends the user
// to the provider with an empty or literal "undefined" client id - the
// provider's error page gives no hint that a server env var is missing
// (#2238). Catch it generically here instead of per-provider.
const missingEnvVars = integrationProvider.missingEnvVars?.() ?? [];
if (missingEnvVars.length) {
this._logger.error(
`Cannot start ${integration} OAuth: missing env var(s) ${missingEnvVars.join(
', '
)}`
);
return {
err: true,
message: `${integrationProvider.name} is not configured on this server: missing ${missingEnvVars.join(
', '
)}. Ask the admin to set ${missingEnvVars.length > 1 ? 'these' : 'this'} environment variable${
missingEnvVars.length > 1 ? 's' : ''
}.`,
};
}
try {
const getExternalUrl = integrationProvider.externalUrl
? {
@ -280,7 +304,17 @@ export class IntegrationsController {
);
return { url };
} catch (err) {
} catch (err: any) {
// Previously swallowed entirely (HTTP 200 with just { err: true }), so
// a provider rejecting the request (for example X's request-token call
// failing) left no trace anywhere in the server logs (#2238). Log only
// the message, never the raw error object - some provider errors carry
// request config/headers that aren't guaranteed to be redacted here.
this._logger.error(
`Failed to generate auth URL for ${integration}: ${
err?.message || err
}`
);
return { err: true };
}
}

View File

@ -377,7 +377,18 @@ export class NoAuthIntegrationsController {
}
const { integrationId, organizationId, internalId, provider } = payload;
if (!integrationId || !organizationId || !internalId || !provider) {
if (
!integrationId ||
typeof integrationId !== 'string' ||
!organizationId ||
typeof organizationId !== 'string' ||
!internalId ||
typeof internalId !== 'string' ||
!provider ||
typeof provider !== 'string' ||
'timeLimit' in payload || // team invite token
'expires' in payload // password reset token
) {
throw new HttpException('Invalid token payload', 400);
}
@ -385,7 +396,11 @@ export class NoAuthIntegrationsController {
organizationId,
integrationId
);
if (!integration || integration.internalId !== internalId) {
if (
!integration ||
integration.internalId !== internalId ||
integration.providerIdentifier !== provider
) {
throw new HttpException('Integration not found', 404);
}
@ -428,8 +443,10 @@ export class NoAuthIntegrationsController {
false,
undefined,
undefined,
AuthService.signJWT(
JSON.parse(Buffer.from(body.cookies, 'base64').toString())
// stored encrypted like connectSocialMedia does, never signed: the
// cookies JSON comes from the request
AuthService.fixedEncryption(
Buffer.from(body.cookies, 'base64').toString()
)
);

View File

@ -30,10 +30,19 @@ import {
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
import { PostValidationException } from '@gitroom/backend/api/routes/posts.validation.exception';
import {
AssignCommentDto,
CreatePublicCommentDto,
ResolveCommentDto,
} from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
import { RealIP } from 'nestjs-real-ip';
import { BulkScheduleDto } from '@gitroom/nestjs-libraries/dtos/posts/bulk.schedule.dto';
import { simpleTextProviders } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/all.providers.settings';
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
import { EvergreenService } from '@gitroom/nestjs-libraries/database/prisma/evergreen/evergreen.service';
import {
CreateEvergreenRecycleDto,
UpdateEvergreenRecycleDto,
} from '@gitroom/nestjs-libraries/dtos/posts/evergreen.recycle.dto';
@ApiTags('Posts')
@Controller('/posts')
@ -41,7 +50,9 @@ export class PostsController {
constructor(
private _postsService: PostsService,
private _agentGraphService: AgentGraphService,
private _shortLinkService: ShortLinkService
private _shortLinkService: ShortLinkService,
private _organizationService: OrganizationService,
private _evergreenService: EvergreenService
) {}
@Get('/:id/statistics')
@ -77,11 +88,61 @@ export class PostsController {
return this._postsService.updateReleaseId(org.id, id, releaseId);
}
// Evergreen content recycling (see Organization.EvergreenRecycle in the
// schema) - lists/creates/pauses/removes the recycle schedule for one
// already-published post. The actual republishing happens in the daily
// evergreenRecycleWorkflow batch, not from this controller.
@Get('/:id/evergreen')
async getEvergreenRecycles(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return this._evergreenService.listForPost(org.id, id);
}
@Post('/:id/evergreen')
async createEvergreenRecycle(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string,
@Body() body: CreateEvergreenRecycleDto
) {
return this._evergreenService.createRecycle(org.id, id, body);
}
@Put('/evergreen/:recycleId')
async updateEvergreenRecycle(
@GetOrgFromRequest() org: Organization,
@Param('recycleId') recycleId: string,
@Body() body: UpdateEvergreenRecycleDto
) {
return this._evergreenService.setActive(org.id, recycleId, body.active);
}
@Delete('/evergreen/:recycleId')
async deleteEvergreenRecycle(
@GetOrgFromRequest() org: Organization,
@Param('recycleId') recycleId: string
) {
return this._evergreenService.remove(org.id, recycleId);
}
@Post('/should-shortlink')
async shouldShortlink(@Body() body: { messages: string[] }) {
return { ask: this._shortLinkService.askShortLinkedin(body.messages) };
}
// Authenticated counterpart to PublicController#getComments - same data,
// plus mention/assignment identities that are only safe to reveal once we
// know the caller is logged in as a member of the org that owns the post
// (see PostsService.getComments's includeInternal gate).
@Get('/:id/comments')
async getComments(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return { comments: await this._postsService.getComments(id, org.id) };
}
@Post('/:id/comments')
async createComment(
@GetUserFromRequest() user: User,
@ -101,6 +162,30 @@ export class PostsController {
return this._postsService.resolveComment(org.id, commentId, body.resolved);
}
@Put('/comments/:commentId/assign')
async assignComment(
@GetOrgFromRequest() org: Organization,
@GetUserFromRequest() user: User,
@Param('commentId') commentId: string,
@Body() body: AssignCommentDto
) {
return this._postsService.assignComment(
org.id,
commentId,
body.assignedToId,
user.id
);
}
// Backs the comment @mention/assignment picker - every active member of
// the current organization, not gated behind the admin-only
// SettingsController team endpoint since any member composing a comment
// needs to see who they can mention/assign.
@Get('/comments/team-members')
async getCommentTeamMembers(@GetOrgFromRequest() org: Organization) {
return this._organizationService.getTeamMembersForMentions(org.id);
}
@Get('/tags')
async getTags(@GetOrgFromRequest() org: Organization) {
return { tags: await this._postsService.getTags(org.id) };
@ -188,6 +273,14 @@ export class PostsController {
return this._postsService.getPostsByGroup(org.id, group);
}
// Declared before the generic '/:id' GET below so Nest doesn't try to
// resolve this literal path as an :id param.
@Get('/pending-approval')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async getPendingApprovalPosts(@GetOrgFromRequest() org: Organization) {
return this._postsService.getPendingApprovalPosts(org.id);
}
@Get('/:id')
getPost(@GetOrgFromRequest() org: Organization, @Param('id') id: string) {
return this._postsService.getPost(org.id, id);
@ -205,6 +298,7 @@ export class PostsController {
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
async createPost(
@GetOrgFromRequest() org: Organization,
@GetUserFromRequest() user: User,
@Body() rawBody: any
) {
// Server-side validation — never trust the client to have validated.
@ -245,7 +339,34 @@ export class PostsController {
}
const body = await this._postsService.mapTypeToPost(rawBody, org.id);
return this._postsService.createPost(org.id, body, 'WEB');
// The auth middleware populates org.users with the caller's own
// membership row (see organization.service.ts for the same pattern) -
// this is the only place that reads it as a role, so the Organization
// type doesn't declare it.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const callerRole = org.users?.[0]?.role;
return this._postsService.createPost(org.id, body, 'WEB', false, {
userId: user.id,
role: callerRole,
});
}
@Get('/bulk-schedule/supported-providers')
bulkScheduleSupportedProviders() {
// Single source of truth for which providers bulk CSV import can
// target — same generic, data-driven list the backend enforces in
// bulkSchedule(), so the frontend channel picker never drifts from it.
return { providers: simpleTextProviders() };
}
@Post('/bulk-schedule')
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
async bulkSchedule(
@GetOrgFromRequest() org: Organization,
@Body() body: BulkScheduleDto
) {
return this._postsService.bulkSchedule(org.id, body);
}
@Post('/generator/draft')
@ -306,6 +427,26 @@ export class PostsController {
return this._postsService.changeDate(org.id, id, date, action, republish);
}
// ADMIN/SUPERADMIN-only - approve/reject a USER-level member's post held
// back by Organization.requireApprovalForQueue (see PostsService#createPost).
@Put('/:id/approve-queue')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async approvePendingQueuePost(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return this._postsService.approvePendingQueuePost(org.id, id);
}
@Put('/:id/reject-queue')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async rejectPendingQueuePost(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return this._postsService.rejectPendingQueuePost(org.id, id);
}
@Post('/separate-posts')
async separatePosts(
@GetOrgFromRequest() org: Organization,

View File

@ -27,7 +27,10 @@ import { promisify } from 'util';
import { OnlyURL } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import { CreatePublicCommentDto } from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
import {
ApprovePostDto,
CreatePublicCommentDto,
} from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
const pump = promisify(pipeline);
@ -88,6 +91,15 @@ export class PublicController {
return this._postsService.createPublicComment(postId, body, null, ip);
}
@Post(`/posts/:id/approve`)
async approvePost(
@Param('id') postId: string,
@Body() body: ApprovePostDto,
@RealIP() ip: string
) {
return this._postsService.approvePublicPost(postId, body, null, ip);
}
@Post('/t')
async trackEvent(
@Res() res: Response,
@ -148,7 +160,16 @@ export class PublicController {
billing: 'FREE' | 'STANDARD' | 'TEAM' | 'PRO' | 'ULTIMATE';
};
if (!load || !load.orgId || !load.billing || !pricing[load.billing]) {
if (
!load ||
!load.orgId ||
typeof load.orgId !== 'string' ||
!load.billing ||
!pricing[load.billing] ||
'timeLimit' in load || // team invite token
'providerName' in load || // login token (full User row)
'expires' in load // password reset token
) {
return { success: false };
}

View File

@ -15,6 +15,7 @@ import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/o
import { AddTeamMemberDto } from '@gitroom/nestjs-libraries/dtos/settings/add.team.member.dto';
import { AdminAddTeamMemberDto } from '@gitroom/nestjs-libraries/dtos/settings/admin.add.team.member.dto';
import { ShortlinkPreferenceDto } from '@gitroom/nestjs-libraries/dtos/settings/shortlink-preference.dto';
import { ApprovalForQueueDto } from '@gitroom/nestjs-libraries/dtos/settings/approval-for-queue.dto';
import { ApiTags } from '@nestjs/swagger';
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
@ -72,6 +73,18 @@ export class SettingsController {
return this._organizationService.deleteTeamMember(org, id);
}
// Self-service: a member leaving an organization they're currently
// switched into, as opposed to an admin removing someone else via
// deleteTeamMember() above. Not gated behind the TEAM_MEMBERS/ADMIN
// policy since any member - not just admins - can leave an org.
@Post('/team/leave')
leaveOrganization(
@GetUserFromRequest() user: User,
@GetOrgFromRequest() org: Organization
) {
return this._organizationService.leaveOrganization(user, org);
}
@Get('/shortlink')
async getShortlinkPreference(@GetOrgFromRequest() org: Organization) {
return this._organizationService.getShortlinkPreference(org.id);
@ -88,4 +101,21 @@ export class SettingsController {
body.shortlink
);
}
@Get('/approval-queue')
async getApprovalQueueSetting(@GetOrgFromRequest() org: Organization) {
return this._organizationService.getApprovalForQueueSetting(org.id);
}
@Post('/approval-queue')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async updateApprovalQueueSetting(
@GetOrgFromRequest() org: Organization,
@Body() body: ApprovalForQueueDto
) {
return this._organizationService.updateApprovalForQueueSetting(
org.id,
body.requireApprovalForQueue
);
}
}

View File

@ -116,7 +116,25 @@ export class ThirdPartyController {
throw new HttpException('Invalid identifier', 400);
}
return thirdPartyInstance?.instance?.[functionName](
// functionName comes straight from the URL - only call methods the
// provider explicitly opted in with @ExposeThirdPartyFunction, the same
// allowlist VideoManager enforces for its own name-dispatched functions.
// Without this, any authenticated org member could invoke ANY method
// found on the provider instance (checkConnection, sendData, or a future
// internal helper) just by naming it in the URL.
const functionToCall = thirdPartyInstance.instance?.[functionName];
if (
typeof functionToCall !== 'function' ||
this._thirdPartyManager.checkAvailableThirdPartyFunction(functionToCall)
) {
throw new HttpException(
`Function ${functionName} not found on third-party instance`,
400
);
}
return functionToCall.call(
thirdPartyInstance.instance,
AuthService.fixedDecryption(thirdParty.apiKey),
data
);

View File

@ -14,9 +14,10 @@ import { ApiTags } from '@nestjs/swagger';
import { WebhooksService } from '@gitroom/nestjs-libraries/database/prisma/webhooks/webhooks.service';
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
import {
OnlyURL, UpdateDto, WebhooksDto
DeliveriesPageDto, OnlyURL, UpdateDto, WebhooksDto
} from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
@ApiTags('Webhooks')
@Controller('/webhooks')
@ -25,7 +26,7 @@ export class WebhookController {
@Get('/')
async getStatistics(@GetOrgFromRequest() org: Organization) {
return this._webhooksService.getWebhooks(org.id);
return this._webhooksService.getWebhooksForDisplay(org.id);
}
@Post('/')
@ -53,18 +54,58 @@ export class WebhookController {
return this._webhooksService.deleteWebhook(org.id, id);
}
@Post('/:id/secret')
async regenerateSecret(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return this._webhooksService.regenerateSecret(org.id, id);
}
@Get('/:id/deliveries')
async getDeliveries(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string,
@Query() query: DeliveriesPageDto
) {
return this._webhooksService.getDeliveries(
org.id,
id,
Number(query.page) || 1
);
}
@Post('/deliveries/:deliveryId/redeliver')
async redeliver(
@GetOrgFromRequest() org: Organization,
@Param('deliveryId') deliveryId: string
) {
const result = await this._webhooksService.redeliver(org.id, deliveryId);
if (!result) {
return { success: false, error: 'Delivery not found' };
}
return result;
}
@Post('/send')
async sendWebhook(@Body() body: any, @Query() query: OnlyURL) {
try {
await fetch(query.url, {
const response = await fetch(query.url, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
// @ts-ignore — undici dispatcher option, not in lib.dom fetch types
dispatcher: getSsrfSafeDispatcher(),
});
return {
send: response.status >= 200 && response.status < 300,
statusCode: response.status,
};
} catch (err) {
/** sent **/
return {
send: false,
error: err instanceof Error ? err.message : 'Unknown delivery error',
};
}
return { send: true };
}
}

View File

@ -59,7 +59,14 @@ async function start() {
},
});
await startMcp(app);
// startMcp wires Mastra, which connects to Postgres (pStore) on first use -
// a DB outage/misconfiguration there must not take down the entire backend
// (every other route, not just /mcp and /copilot) by rejecting start().
try {
await startMcp(app);
} catch (e) {
Logger.error('Failed to initialize MCP/Mastra, continuing without it', e);
}
app.useGlobalPipes(
new ValidationPipe({

View File

@ -26,6 +26,12 @@ import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/po
import { FileInterceptor } from '@nestjs/platform-express';
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.dto';
import {
BulkCreatePostsDto,
BulkCreateResult,
BulkDeleteResult,
BulkPostIdsDto,
} from '@gitroom/nestjs-libraries/dtos/posts/bulk.posts.dto';
import { ChangePostStatusDto } from '@gitroom/nestjs-libraries/dtos/posts/change.post.status.dto';
import { UpdatePostSettingsDto } from '@gitroom/nestjs-libraries/dtos/posts/update.post.settings.dto';
import {
@ -137,6 +143,15 @@ export class PublicIntegrationsController {
@Body() rawBody: any
) {
Sentry.metrics.count('public_api-request', 1);
return this.createOnePost(org, rawBody);
}
// Shared by the single POST /posts above and the bulk endpoint below, so
// both go through the exact same validation/creation pipeline and never
// drift. Throws PostValidationException / HttpException on a bad single
// item - callers decide whether that aborts the whole request (single) or
// is caught per-item (bulk).
private async createOnePost(org: Organization, rawBody: any) {
const body = await this._postsService.mapTypeToPost(
{
...rawBody,
@ -217,6 +232,86 @@ export class PublicIntegrationsController {
return this._postsService.createPost(org.id, body, creationMethod);
}
// Creates up to MAX_BULK_CREATE posts in one call. Each entry is the exact
// same body shape as POST /posts; a bad entry never aborts the batch -
// same "schedule what's valid, report the rest" spirit as the dashboard's
// CSV bulk-schedule (see PostsService.bulkSchedule).
@Post('/posts/bulk')
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
async createPostsBulk(
@GetOrgFromRequest() org: Organization,
@Body() body: BulkCreatePostsDto
) {
Sentry.metrics.count('public_api-request', 1);
const results: BulkCreateResult[] = [];
for (let index = 0; index < body.posts.length; index++) {
try {
const created = await this.createOnePost(org, body.posts[index]);
results.push({
index,
success: !!created?.length,
postId: created?.[0]?.postId,
...(created?.length
? {}
: { error: 'Could not create this post' }),
});
} catch (err) {
results.push({
index,
success: false,
error:
err instanceof HttpException
? JSON.stringify(err.getResponse())
: err instanceof Error
? err.message
: 'Could not create this post',
});
}
}
return { results };
}
// Deletes up to MAX_BULK_IDS posts (by id, same resolution as
// DELETE /posts/:id - each id's whole group is removed) in one call. A
// missing/foreign id never aborts the batch.
@Delete('/posts/bulk')
async deletePostsBulk(
@GetOrgFromRequest() org: Organization,
@Body() body: BulkPostIdsDto
) {
Sentry.metrics.count('public_api-request', 1);
const results: BulkDeleteResult[] = [];
for (const id of body.ids) {
try {
const getPostById = await this._postsService.getPost(org.id, id);
if (!getPostById) {
results.push({ id, success: false, error: 'Post not found' });
continue;
}
const deleted = await this._postsService.deletePost(
org.id,
getPostById.group
);
results.push({
id,
success: !deleted?.error,
...(deleted?.error ? { error: 'Could not delete this post' } : {}),
});
} catch (err) {
results.push({
id,
success: false,
error: err instanceof Error ? err.message : 'Could not delete this post',
});
}
}
return { results };
}
@Delete('/posts/:id')
async deletePost(
@GetOrgFromRequest() org: Organization,

View File

@ -43,7 +43,7 @@ export class AuthMiddleware implements NestMiddleware {
const payload = AuthService.verifyJWT(auth) as User | null;
const orgHeader = req.cookies.showorg || req.headers.showorg;
if (!payload?.id) {
if (!payload?.id || typeof payload.id !== 'string') {
throw new HttpForbiddenException();
}

View File

@ -0,0 +1,179 @@
// #2199: registering with a pending org invite link always created a brand
// new (junk) organization for the invited user - routeAuth() called
// createOrgAndUser() unconditionally, then only afterwards tried to also
// join the invite via addUserToOrg(). Even when the invite succeeded, the
// user ended up SUPERADMIN of a throwaway org with the invite as a bonus
// membership instead of the intended destination.
//
// This exercises the LOCAL-provider registration branch of routeAuth():
// a user registering with a valid invite in the `org` cookie should join
// the inviting organization without ever creating a new one, and should
// only fall back to a standalone org if the invite can no longer be
// redeemed (already used, or the org hit its seat limit).
process.env.JWT_SECRET = 'test-secret-for-routeauth-invite-spec';
// AuthService's constructor params pull in UsersService -> UsersRepository
// -> helpers/auth's AuthService, which needs the native bcrypt binding.
// emitDecoratorMetadata keeps that import live at runtime even though this
// spec only ever passes plain mocks for those constructor params, so stub
// it out the same way the integration.repository standalone spec stubs
// UploadFactory to dodge its own unrelated native/ESM-only dependency.
jest.mock('bcrypt', () => ({
hashSync: jest.fn(() => 'hashed'),
compareSync: jest.fn(() => true),
}));
// Same chain also drags in UploadFactory -> CloudflareStorage -> `file-type`,
// which is ESM-only and isn't transformable under this standalone Jest
// config (see integration.repository.standalone.spec.ts for precedent).
jest.mock('@gitroom/nestjs-libraries/upload/upload.factory', () => ({
UploadFactory: {
createStorage: () => ({ uploadSimple: jest.fn() }),
},
}));
// AuthService's `_emailService: EmailService` constructor param also keeps
// EmailService's real import alive (emitDecoratorMetadata), which pulls in
// the email provider implementations - unrelated code this spec never
// exercises (a mock EmailService is passed below) and that doesn't compile
// cleanly under this config's relaxed-but-not-identical tsconfig overrides.
jest.mock('@gitroom/nestjs-libraries/services/email.service', () => ({
EmailService: class {},
}));
import { AuthService } from './auth.service';
import { CreateOrgUserDto } from '@gitroom/nestjs-libraries/dtos/auth/create.org.user.dto';
import { Provider } from '@prisma/client';
describe('AuthService.routeAuth - registration with a pending org invite', () => {
function makeBody(): CreateOrgUserDto {
const body = new CreateOrgUserDto();
body.email = 'invited@example.com';
body.password = 'super-secret-password';
body.provider = Provider.LOCAL;
body.company = 'Whatever Inc';
body.datafast_visitor_id = '';
return body;
}
function makeService(overrides: {
addUserToOrgResult: any;
}) {
const createdUser = {
id: 'new-user-id',
email: 'invited@example.com',
password: 'hashed',
};
const organizationService = {
getCount: jest.fn().mockResolvedValue(1),
createOrgAndUser: jest.fn(),
createUser: jest.fn().mockResolvedValue(createdUser),
createOrgForExistingUser: jest.fn().mockResolvedValue({ id: 'fallback-org-id' }),
addUserToOrg: jest.fn().mockResolvedValue(overrides.addUserToOrgResult),
};
const userService = {
getUserByEmail: jest.fn().mockResolvedValue(null),
};
const emailService = {
sendEmailSync: jest.fn().mockResolvedValue(undefined),
hasProvider: jest.fn().mockReturnValue(false),
};
const service = new AuthService(
userService as any,
organizationService as any,
emailService as any,
{} as any
);
return { service, organizationService, userService, createdUser };
}
it('joins the inviting org and never creates a new organization when the invite is redeemable', async () => {
const { service, organizationService, createdUser } = makeService({
addUserToOrgResult: { id: 'membership-id', organizationId: 'inviting-org-id' },
});
const result = await service.routeAuth(
Provider.LOCAL,
makeBody(),
'127.0.0.1',
'test-agent',
{ orgId: 'inviting-org-id', role: 'USER', id: 'invite-id' }
);
expect(organizationService.createOrgAndUser).not.toHaveBeenCalled();
expect(organizationService.createUser).toHaveBeenCalledTimes(1);
expect(organizationService.addUserToOrg).toHaveBeenCalledWith(
createdUser.id,
'invite-id',
'inviting-org-id',
'USER'
);
expect(organizationService.createOrgForExistingUser).not.toHaveBeenCalled();
expect(result.addedOrg).toEqual({
id: 'membership-id',
organizationId: 'inviting-org-id',
});
});
it('falls back to a standalone org only when the invite can no longer be redeemed', async () => {
const { service, organizationService, createdUser } = makeService({
addUserToOrgResult: false,
});
await service.routeAuth(
Provider.LOCAL,
makeBody(),
'127.0.0.1',
'test-agent',
{ orgId: 'inviting-org-id', role: 'USER', id: 'invite-id' }
);
expect(organizationService.createOrgAndUser).not.toHaveBeenCalled();
expect(organizationService.createUser).toHaveBeenCalledTimes(1);
expect(organizationService.createOrgForExistingUser).toHaveBeenCalledWith(
createdUser.id,
'Whatever Inc'
);
});
it('still creates a normal organization when there is no invite', async () => {
const organizationService = {
getCount: jest.fn().mockResolvedValue(1),
createOrgAndUser: jest.fn().mockResolvedValue({
id: 'org-id',
users: [{ user: { id: 'owner-id', email: 'owner@example.com' } }],
}),
createUser: jest.fn(),
createOrgForExistingUser: jest.fn(),
addUserToOrg: jest.fn(),
};
const userService = { getUserByEmail: jest.fn().mockResolvedValue(null) };
const emailService = {
sendEmailSync: jest.fn().mockResolvedValue(undefined),
hasProvider: jest.fn().mockReturnValue(false),
};
const service = new AuthService(
userService as any,
organizationService as any,
emailService as any,
{} as any
);
const result = await service.routeAuth(
Provider.LOCAL,
makeBody(),
'127.0.0.1',
'test-agent',
undefined
);
expect(organizationService.createOrgAndUser).toHaveBeenCalledTimes(1);
expect(organizationService.createUser).not.toHaveBeenCalled();
expect(result.addedOrg).toBe(false);
});
});

View File

@ -54,23 +54,50 @@ export class AuthService {
throw new Error('Registration is disabled');
}
const create = await this._organizationService.createOrgAndUser(
body,
ip,
userAgent
);
const invite =
addToOrg && typeof addToOrg !== 'boolean' ? addToOrg : undefined;
const addedOrg =
addToOrg && typeof addToOrg !== 'boolean'
? await this._organizationService.addUserToOrg(
create.users[0].user.id,
addToOrg.id,
addToOrg.orgId,
addToOrg.role
)
: false;
let registeredUser: User;
let addedOrg: boolean | Awaited<
ReturnType<OrganizationService['addUserToOrg']>
> = false;
const obj = { addedOrg, jwt: await this.jwt(create.users[0].user) };
if (invite) {
// A pending invite joins the inviting organization directly,
// instead of always spinning up a new one for the registering
// user and only afterwards trying to also join the invite (#2199).
registeredUser = await this._organizationService.createUser(
body,
ip,
userAgent
);
addedOrg = await this._organizationService.addUserToOrg(
registeredUser.id,
invite.id,
invite.orgId,
invite.role
);
// The invite could be unusable by the time registration posts
// (already redeemed, or the org hit its seat limit) - fall back
// to a standalone org so the new account isn't left with none.
if (!addedOrg) {
await this._organizationService.createOrgForExistingUser(
registeredUser.id,
body.company
);
}
} else {
const create = await this._organizationService.createOrgAndUser(
body,
ip,
userAgent
);
registeredUser = create.users[0].user;
}
const obj = { addedOrg, jwt: await this.jwt(registeredUser) };
await this._emailService.sendEmailSync(
body.email,
'Activate your account',
@ -116,7 +143,13 @@ export class AuthService {
try {
const getOrg: any = AuthChecker.verifyJWT(cookie);
if (dayjs(getOrg.timeLimit).isBefore(dayjs())) {
if (
typeof getOrg.orgId !== 'string' ||
typeof getOrg.id !== 'string' ||
!['USER', 'ADMIN'].includes(getOrg.role) ||
!getOrg.timeLimit ||
dayjs(getOrg.timeLimit).isBefore(dayjs())
) {
return false;
}
@ -234,7 +267,7 @@ export class AuthService {
id: string;
expires: string;
};
if (dayjs(user.expires).isBefore(dayjs())) {
if (typeof user.id !== 'string' || dayjs(user.expires).isBefore(dayjs())) {
return false;
}

View File

@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.buffer;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/buffer',
},
};
export default function CompareBufferPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.hootsuite;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/hootsuite',
},
};
export default function CompareHootsuitePage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.later;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/later',
},
};
export default function CompareLaterPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.metricool;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/metricool',
},
};
export default function CompareMetricoolPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.mixpost;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/mixpost',
},
};
export default function CompareMixpostPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.publer;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/publer',
},
};
export default function ComparePublerPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -0,0 +1,22 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.socialbee;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/socialbee',
},
};
export default function CompareSocialbeePage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -0,0 +1,8 @@
import { ReactNode } from 'react';
// Public, unauthenticated route group for the /compare/* SEO landing pages.
// Deliberately does not use (site)/layout.tsx's LayoutComponent, which assumes
// a logged-in organization context and would redirect an anonymous visitor.
export default async function CompareLayout({ children }: { children: ReactNode }) {
return <>{children}</>;
}

View File

@ -52,6 +52,7 @@ export default async function Auth(
previewId={id}
postIds={post.map((p: any) => p.id)}
organizationId={post[0].organizationId}
postState={post[0].state}
>
<div className="mx-auto w-full max-w-[1346px] p-[12px] flex flex-col gap-[8px] text-newTextColor">
<div className="flex bg-newBgColorInner rounded-[12px] min-h-[80px] px-[20px] py-[12px] items-center gap-[20px] flex-wrap">

View File

@ -47,7 +47,7 @@ const EmbeddedBilling = dynamic(
);
export const FirstBillingComponent = () => {
const { stripeClient } = useVariables();
const { stripeClient, billingEnabled } = useVariables();
const user = useUser();
const dub = useDubClickId();
const [stripe, setStripe] = useState<null | Promise<Stripe>>(null);
@ -62,10 +62,20 @@ export const FirstBillingComponent = () => {
const [datafast_session_id] = useCookie('datafast_session_id', '');
useEffect(() => {
// loadStripe injects the js.stripe.com script tag (and its fingerprinting
// requests) as soon as it's called, independent of whether the key it's
// given is valid. Never call it unless billing is actually turned on for
// this deployment - self-hosters without Stripe configured must not have
// it loaded just because this component happened to mount.
if (!billingEnabled || !stripeClient) {
setStripeFailed(true);
return;
}
const stripePromise = loadStripe(stripeClient);
stripePromise.catch(() => setStripeFailed(true));
setStripe(stripePromise);
}, []);
}, [billingEnabled, stripeClient]);
const loadCheckout = useCallback(async () => {
return (

View File

@ -0,0 +1,534 @@
// Content for the /compare/* landing pages.
// Every number here is sourced from libraries/nestjs-libraries/src/database/prisma/subscriptions/pricing.ts
// (Postiz side) and the competitor's own public pricing page (checked 2026-10-23).
// Do not invent a number here - if a competitor changes price, update the value and the "asOf" field.
export interface ComparePricingRow {
label: string;
postiz: string;
competitor: string;
}
export interface CompareChecklistRow {
label: string;
postiz: boolean;
competitor: boolean;
}
export interface CompareFaqItem {
question: string;
answer: string;
}
export interface CompareCompetitor {
slug: string;
name: string;
domain: string;
asOf: string;
headline: string;
subheadline: string;
summary: string;
pricingRows: ComparePricingRow[];
structuralChecklist: CompareChecklistRow[];
featureChecklist: CompareChecklistRow[];
verdict: string;
faq: CompareFaqItem[];
}
const structuralChecklistTemplate = (competitorName: string): CompareChecklistRow[] => [
{
label: 'Open-source and self-hostable',
postiz: true,
competitor: false,
},
{
label: 'Managed cloud option at indie-friendly pricing',
postiz: true,
competitor: competitorName !== 'Mixpost',
},
{
label: 'Public API + npm SDK + CLI + browser extension',
postiz: true,
competitor: false,
},
{
label: 'Native MCP server (Claude/ChatGPT/Codex agents can post directly)',
postiz: true,
competitor: false,
},
];
export const compareCompetitors: Record<string, CompareCompetitor> = {
buffer: {
slug: 'buffer',
name: 'Buffer',
domain: 'buffer.com',
asOf: '2026-10-23',
headline: 'Postiz vs Buffer',
subheadline:
"Buffer's per-channel price, plus the public API, MCP server, and AI agent Buffer doesn't ship at any price.",
summary:
'Buffer Essentials charges per channel with no AI drafting, no public API, and no self-host option. Postiz STANDARD is a flat $29/mo for 5 channels ($5.80/channel) and already includes AI post generation, a public API, and 60 minutes/month of video clipping.',
pricingRows: [
{
label: 'Entry plan price',
postiz: '$29/mo flat (STANDARD)',
competitor: '$5/channel/mo (Essentials)',
},
{
label: 'Channels included at entry price',
postiz: '5 channels ($5.80/channel effective)',
competitor: 'Priced per channel, no bundle discount',
},
{
label: 'AI post drafting',
postiz: 'Included (LangGraph agent + live web research)',
competitor: 'Not available',
},
{
label: 'Public API access',
postiz: 'Included from $29/mo',
competitor: 'Not offered',
},
{
label: 'Self-hosting option',
postiz: 'AGPL self-host, same features as cloud',
competitor: 'Not offered',
},
],
structuralChecklist: structuralChecklistTemplate('Buffer'),
featureChecklist: [
{
label: 'Video-to-clips scheduler (long video → scheduled short clips)',
postiz: true,
competitor: false,
},
{
label: 'Team seats included',
postiz: true,
competitor: false,
},
{
label: 'Webhooks for workflow automation',
postiz: true,
competitor: false,
},
],
verdict:
"If you're comparing per-channel pricing, Buffer looks cheaper on paper for a single channel. The moment you need a second channel, an API, or AI drafting, Postiz's flat $29/mo covers all of it where Buffer charges more and still can't match the feature set.",
faq: [
{
question: 'Is Postiz actually cheaper than Buffer?',
answer:
'At 5 channels, Postiz STANDARD is $29/mo total ($5.80/channel) versus Buffer Essentials at $5/channel with no bundle discount and no AI, API, or self-host option included at any price.',
},
{
question: 'Can I self-host Postiz instead of using the cloud version?',
answer:
'Yes. Postiz is AGPL-licensed and open-source; the self-hosted version has the exact same feature set as Postiz Cloud, which Buffer does not offer in any form.',
},
{
question: 'Does Buffer have an MCP server or AI agent?',
answer:
"No. Buffer has no public MCP server and no built-in AI agent. Postiz ships both: a native MCP server so Claude, ChatGPT, or Codex agents can schedule posts directly, and a LangGraph-based agent that does live web research before drafting.",
},
],
},
hootsuite: {
slug: 'hootsuite',
name: 'Hootsuite',
domain: 'hootsuite.com',
asOf: '2026-10-23',
headline: 'Postiz vs Hootsuite',
subheadline:
'The same 10-channel, 3-seat, approval-workflow shape Hootsuite prices at $1,197/mo - Postiz TEAM ships it for $39/mo flat.',
summary:
'Hootsuite overcharges for the exact workflow small teams need: multiple channels, team seats, and approval before publish. Postiz TEAM bundles 10 channels, team members, and autopost for $39/mo - a fraction of Hootsuite Advanced plus 3 seats.',
pricingRows: [
{
label: 'Plan matching 10 channels + team + approval',
postiz: '$39/mo flat (TEAM)',
competitor: '$1,197/mo (Advanced + 3 seats)',
},
{
label: 'Team members included',
postiz: 'Included at $39/mo',
competitor: 'Extra seats billed on top of Advanced',
},
{
label: 'AI post drafting',
postiz: 'Included (LangGraph agent + live web research)',
competitor: 'Add-on on higher tiers',
},
{
label: 'Public API access',
postiz: 'Included from $29/mo',
competitor: 'Enterprise tier only',
},
],
structuralChecklist: structuralChecklistTemplate('Hootsuite'),
featureChecklist: [
{
label: 'Video-to-clips scheduler',
postiz: true,
competitor: false,
},
{
label: 'Flat pricing, no per-seat surcharge at this tier',
postiz: true,
competitor: false,
},
{
label: 'Self-host option for data residency',
postiz: true,
competitor: false,
},
],
verdict:
"Hootsuite's enterprise pricing model charges per-seat on top of a high base plan. For a 3-person team managing 10 channels with approval, that's $1,197/mo on Hootsuite versus $39/mo flat on Postiz TEAM - a gap large enough to fund the rest of your marketing stack.",
faq: [
{
question: 'Why is Hootsuite so much more expensive for the same features?',
answer:
"Hootsuite's Advanced plan plus 3 seats runs approximately $1,197/mo for team + approval workflows on ~10 channels. Postiz TEAM covers the same 10-channel, team-member, approval-adjacent shape for $39/mo flat.",
},
{
question: 'Does Postiz TEAM really include team members at $39/mo?',
answer:
'Yes - team_members is enabled starting at the TEAM tier ($39/mo) in the live pricing config, alongside 10 channels and autopost.',
},
{
question: 'Can I migrate from Hootsuite to Postiz?',
answer:
'Postiz supports 36+ social providers and a public API/SDK for scripted migration of scheduled content; most teams reconnect channels directly via OAuth and rebuild their queue from the calendar view.',
},
],
},
later: {
slug: 'later',
name: 'Later',
domain: 'later.com',
asOf: '2026-10-23',
headline: 'Postiz vs Later',
subheadline: 'Every channel Later has, plus full X (Twitter), Threads, Bluesky, and 20+ more.',
summary:
"Later is built around Instagram-grid-style visual planning but has no X (Twitter) support at all. Postiz covers Later's channels plus X, Threads, Bluesky, Mastodon, LinkedIn, and 20+ more from a single calendar.",
pricingRows: [
{
label: 'X (Twitter) support',
postiz: 'Full support, included',
competitor: 'Not supported',
},
{
label: 'Entry plan price',
postiz: '$29/mo flat (STANDARD, 5 channels)',
competitor: 'Per-plan, channel-limited',
},
{
label: 'AI post drafting',
postiz: 'Included (LangGraph agent)',
competitor: 'Limited AI caption assist',
},
{
label: 'Public API access',
postiz: 'Included from $29/mo',
competitor: 'Not offered on consumer plans',
},
],
structuralChecklist: structuralChecklistTemplate('Later'),
featureChecklist: [
{
label: 'X (Twitter) posting',
postiz: true,
competitor: false,
},
{
label: 'Threads and Bluesky posting',
postiz: true,
competitor: false,
},
{
label: 'Video-to-clips scheduler',
postiz: true,
competitor: false,
},
],
verdict:
"If your channel mix includes X, Threads, or Bluesky, Later structurally can't cover it. Postiz schedules every channel Later supports plus the ones it doesn't, from the same calendar and composer.",
faq: [
{
question: 'Does Later support posting to X (Twitter)?',
answer:
'No, Later does not support X (Twitter) at all. Postiz supports X alongside Threads, Bluesky, and 30+ other channels from one composer.',
},
{
question: 'Is Postiz as good for Instagram-grid planning as Later?',
answer:
"Postiz's calendar and media library cover the same visual scheduling workflow for Instagram, plus the channels Later can't reach.",
},
],
},
socialbee: {
slug: 'socialbee',
name: 'SocialBee',
domain: 'socialbee.com',
asOf: '2026-10-23',
headline: 'Postiz vs SocialBee',
subheadline: 'Team seats at $39/mo, not SocialBee\'s $99/mo Pro gate.',
summary:
"SocialBee requires its $99/mo Pro plan before a single extra team member can be added. Postiz TEAM includes team members, 10 channels, and autopost for $39/mo - a $60/mo gap for the same capability.",
pricingRows: [
{
label: 'Cheapest plan with team members',
postiz: '$39/mo (TEAM)',
competitor: '$99/mo (Pro)',
},
{
label: 'Content recycling / evergreen queue',
postiz: 'Category-based queue rotation',
competitor: 'Category-based queue rotation (SocialBee original)',
},
{
label: 'Public API access',
postiz: 'Included from $29/mo',
competitor: 'Not publicly documented',
},
{
label: 'Self-hosting option',
postiz: 'AGPL self-host available',
competitor: 'Not offered',
},
],
structuralChecklist: structuralChecklistTemplate('SocialBee'),
featureChecklist: [
{
label: 'Team seats at the cheapest multi-channel tier',
postiz: true,
competitor: false,
},
{
label: 'Video-to-clips scheduler',
postiz: true,
competitor: false,
},
{
label: 'Native MCP server',
postiz: true,
competitor: false,
},
],
verdict:
"SocialBee pioneered evergreen content recycling, and Postiz matches that category-based rotation - while undercutting SocialBee by $60/mo on the cheapest plan that includes a second team seat.",
faq: [
{
question: 'Does Postiz have content recycling like SocialBee?',
answer:
"Yes - Postiz supports a recycle-after-days, category-based queue rotation for evergreen content, the same workflow SocialBee popularized.",
},
{
question: 'How much cheaper is Postiz for a 2-person team?',
answer:
"Postiz TEAM at $39/mo includes team members. SocialBee requires its $99/mo Pro plan for the same capability - a $60/mo difference.",
},
],
},
metricool: {
slug: 'metricool',
name: 'Metricool',
domain: 'metricool.com',
asOf: '2026-10-23',
headline: 'Postiz vs Metricool',
subheadline: 'Every channel, every tier, no platform tax.',
summary:
"Metricool is strong on analytics and competitor tracking, but Postiz matches scheduling depth while never gating a specific platform like X or LinkedIn behind a higher tier - channel count is the only paid gate, not platform identity.",
pricingRows: [
{
label: 'Platform-based feature gating',
postiz: 'None - channel count is the only gate',
competitor: 'Some advanced analytics gated by plan',
},
{
label: 'Entry plan price',
postiz: '$29/mo flat (5 channels)',
competitor: 'Tiered by channel + feature',
},
{
label: 'Built-in AI drafting agent',
postiz: 'Included (LangGraph + live web research)',
competitor: 'Not a core feature',
},
{
label: 'Video-to-clips scheduler',
postiz: 'Included (Deepgram transcription)',
competitor: 'Not offered',
},
],
structuralChecklist: structuralChecklistTemplate('Metricool'),
featureChecklist: [
{
label: 'No per-platform feature tax',
postiz: true,
competitor: false,
},
{
label: 'Bundled AI agent with web research',
postiz: true,
competitor: false,
},
{
label: 'Self-host option',
postiz: true,
competitor: false,
},
],
verdict:
"Metricool's analytics and competitor tracking are genuinely strong - Postiz answers with the same scheduling coverage, an AI agent Metricool doesn't have, and a pricing model that never charges extra for which platform you post to.",
faq: [
{
question: 'Does Postiz have competitor tracking like Metricool?',
answer:
"Postiz tracks competitor handles per organization using each provider's public analytics endpoints, with scheduled snapshots and a comparison chart in the analytics view.",
},
{
question: 'Does Postiz charge more for X or LinkedIn specifically?',
answer:
'No. Every tier in the live pricing config gates on channel count only, never on which specific platform you connect.',
},
],
},
publer: {
slug: 'publer',
name: 'Publer',
domain: 'publer.io',
asOf: '2026-10-23',
headline: 'Postiz vs Publer',
subheadline: "The self-host, SDK, CLI, and MCP server Publer structurally can't ship.",
summary:
"Publer is a solid closed-source SaaS scheduler, but it has no self-host option, no npm SDK, no CLI, and no native MCP server. Postiz ships all four, on top of the same multi-channel scheduling Publer offers.",
pricingRows: [
{
label: 'Self-hosting option',
postiz: 'AGPL self-host, full feature parity with cloud',
competitor: 'Not offered - cloud SaaS only',
},
{
label: 'Official npm SDK (@postiz/node)',
postiz: 'Published, documented',
competitor: 'Not offered',
},
{
label: 'CLI tool',
postiz: 'apps/commands CLI',
competitor: 'Not offered',
},
{
label: 'Native MCP server for AI agents',
postiz: 'Built-in (start.mcp.ts)',
competitor: 'Not offered',
},
],
structuralChecklist: structuralChecklistTemplate('Publer'),
featureChecklist: [
{
label: 'Runs your own MCP server',
postiz: true,
competitor: false,
},
{
label: 'Browser extension for quick scheduling',
postiz: true,
competitor: false,
},
{
label: 'Video-to-clips scheduler',
postiz: true,
competitor: false,
},
],
verdict:
"Publer covers day-to-day scheduling well, but anything programmatic - a script, an agent, a CI pipeline, a self-hosted deployment - hits a wall Publer was never built to support. Postiz was.",
faq: [
{
question: 'Can I run Postiz with Claude, ChatGPT, or another AI agent?',
answer:
'Yes - Postiz runs a native MCP server (start.mcp.ts) so AI agents can schedule and manage posts directly. Publer has no equivalent.',
},
{
question: 'Does Publer offer a self-hosted version?',
answer:
'No, Publer is cloud-only. Postiz is AGPL-licensed and can be self-hosted with the same feature set as Postiz Cloud.',
},
],
},
mixpost: {
slug: 'mixpost',
name: 'Mixpost',
domain: 'mixpost.app',
asOf: '2026-10-23',
headline: 'Postiz vs Mixpost',
subheadline:
"The other self-hosted option - won on recurring feature velocity a perpetual license can't match.",
summary:
"Mixpost is the closest direct competitor: open-source and self-hostable. But its Pro tier is a $299 one-time license with an MCP integration and no bundled LLM agent or video-clipping pipeline. Postiz ships a LangGraph agent with live web research, inline DALL-E image generation, and a Temporal-orchestrated video-to-clips pipeline with Deepgram transcription - all included, continuously shipped.",
pricingRows: [
{
label: 'License model',
postiz: 'Open-core, AGPL self-host + managed cloud',
competitor: '$299 one-time perpetual license (Pro)',
},
{
label: 'Bundled LLM agent with live web research',
postiz: 'Included (LangGraph + Tavily)',
competitor: 'Not offered',
},
{
label: 'Video-to-clips pipeline (Deepgram transcription)',
postiz: 'Included',
competitor: 'Not offered',
},
{
label: 'MCP integration',
postiz: 'Native MCP server',
competitor: 'Available on Pro tier',
},
],
structuralChecklist: structuralChecklistTemplate('Mixpost'),
featureChecklist: [
{
label: 'Turn one long video into scheduled clips across every channel',
postiz: true,
competitor: false,
},
{
label: 'Inline AI image generation (DALL-E)',
postiz: true,
competitor: false,
},
{
label: 'Continuously shipped features (no perpetual-license lock)',
postiz: true,
competitor: false,
},
],
verdict:
"Mixpost earned its spot as the self-hosted alternative to SaaS schedulers, and its one-time license is attractive on cost alone. But a perpetual license means a frozen feature set - Postiz's agent graph and video-clipping pipeline are both already-shipped features no competitor in this category, Mixpost included, currently matches.",
faq: [
{
question: 'Is Postiz also open-source and self-hostable like Mixpost?',
answer:
'Yes. Postiz is AGPL-licensed and self-hostable with the exact same feature set as Postiz Cloud - the open-core model gates nothing between the two.',
},
{
question: "What can't Mixpost do that Postiz can?",
answer:
"Mixpost's Pro tier has an MCP integration but no bundled LLM agent graph with live web research, no inline AI image generation, and no video-clipping pipeline. Postiz ships all three today.",
},
],
},
};
export type CompareSlug = keyof typeof compareCompetitors;
export const compareMetaDescription = (data: CompareCompetitor, brandName: string): string =>
`${brandName} vs ${data.name}: ${data.subheadline} Compare pricing, features, and self-hosting options.`;

View File

@ -0,0 +1,215 @@
import Link from 'next/link';
import type { CompareCompetitor } from '@gitroom/frontend/components/compare/compare.data';
const CheckIcon = () => (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
aria-hidden="true"
className="shrink-0"
>
<path
d="M13.5 4.5L6 12L2.5 8.5"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
const CrossIcon = () => (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
aria-hidden="true"
className="shrink-0"
>
<path
d="M3.5 3.5L12.5 12.5M12.5 3.5L3.5 12.5"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
const ChecklistMark = ({ value }: { value: boolean }) => (
<span
className={value ? 'text-customColor28' : 'text-customColor18'}
aria-label={value ? 'Yes' : 'No'}
>
{value ? <CheckIcon /> : <CrossIcon />}
</span>
);
interface CompareLandingPageProps {
data: CompareCompetitor;
brandName: string;
}
export const CompareLandingPage = ({ data, brandName }: CompareLandingPageProps) => {
return (
<div className="bg-newBgColor min-h-screen text-newTextColor">
<header className="border-b border-newBorder px-[24px] py-[20px] flex items-center justify-between max-w-[1040px] mx-auto">
<Link href="/" className="text-[18px] font-semibold tracking-tight">
{brandName}
</Link>
<Link
href="/auth"
className="bg-btnPrimary text-btnText px-[18px] h-[38px] rounded-[6px] flex items-center justify-center text-[14px] font-medium"
>
Start free
</Link>
</header>
<main className="max-w-[1040px] mx-auto px-[24px] py-[56px] flex flex-col gap-[64px]">
{/* Hero */}
<section className="flex flex-col gap-[16px] text-center max-w-[760px] mx-auto">
<h1 className="text-[40px] leading-[1.1] font-semibold tracking-tight">
{data.headline}
</h1>
<p className="text-[20px] opacity-80">{data.subheadline}</p>
<p className="text-[15px] opacity-60 leading-[1.6]">{data.summary}</p>
<div className="flex items-center justify-center gap-[12px] mt-[8px]">
<Link
href="/auth"
className="bg-btnPrimary text-btnText px-[24px] h-[44px] rounded-[6px] flex items-center justify-center text-[15px] font-medium"
>
Try Postiz free
</Link>
<a
href={`https://${data.domain}`}
target="_blank"
rel="nofollow noopener noreferrer"
className="bg-btnSimple text-btnText px-[24px] h-[44px] rounded-[6px] flex items-center justify-center text-[15px] font-medium"
>
Visit {data.name} ↗
</a>
</div>
</section>
{/* Structural moat checklist */}
<section className="flex flex-col gap-[20px]">
<h2 className="text-[24px] font-semibold text-center">
What {data.name} structurally can&apos;t match
</h2>
<div className="border border-newBorder rounded-[8px] overflow-hidden">
<div className="grid grid-cols-[1fr,120px,120px] bg-newBgColorInner text-[13px] opacity-60 px-[20px] py-[12px]">
<div>Capability</div>
<div className="text-center">Postiz</div>
<div className="text-center">{data.name}</div>
</div>
{data.structuralChecklist.map((row, index) => (
<div
key={row.label}
className={`grid grid-cols-[1fr,120px,120px] px-[20px] py-[14px] text-[14px] ${
index % 2 === 1 ? 'bg-newBgColorInner' : ''
}`}
>
<div>{row.label}</div>
<div className="flex justify-center">
<ChecklistMark value={row.postiz} />
</div>
<div className="flex justify-center">
<ChecklistMark value={row.competitor} />
</div>
</div>
))}
</div>
</section>
{/* Pricing comparison */}
<section className="flex flex-col gap-[20px]">
<h2 className="text-[24px] font-semibold text-center">Pricing, side by side</h2>
<div className="border border-newBorder rounded-[8px] overflow-hidden">
<div className="grid grid-cols-[1fr,1fr,1fr] bg-newBgColorInner text-[13px] opacity-60 px-[20px] py-[12px]">
<div></div>
<div className="text-center font-medium">Postiz</div>
<div className="text-center font-medium">{data.name}</div>
</div>
{data.pricingRows.map((row, index) => (
<div
key={row.label}
className={`grid grid-cols-[1fr,1fr,1fr] px-[20px] py-[14px] text-[14px] gap-[8px] ${
index % 2 === 1 ? 'bg-newBgColorInner' : ''
}`}
>
<div className="opacity-70">{row.label}</div>
<div className="text-center font-medium">{row.postiz}</div>
<div className="text-center opacity-80">{row.competitor}</div>
</div>
))}
</div>
<p className="text-[12px] opacity-50 text-center">
Pricing checked against {data.domain} and Postiz&apos;s live pricing config as of{' '}
{data.asOf}. Competitor pricing may change - verify on their site before purchase.
</p>
</section>
{/* Feature checklist */}
<section className="flex flex-col gap-[20px]">
<h2 className="text-[24px] font-semibold text-center">Feature checklist</h2>
<div className="border border-newBorder rounded-[8px] overflow-hidden">
{data.featureChecklist.map((row, index) => (
<div
key={row.label}
className={`grid grid-cols-[1fr,120px,120px] px-[20px] py-[14px] text-[14px] ${
index % 2 === 1 ? 'bg-newBgColorInner' : ''
}`}
>
<div>{row.label}</div>
<div className="flex justify-center">
<ChecklistMark value={row.postiz} />
</div>
<div className="flex justify-center">
<ChecklistMark value={row.competitor} />
</div>
</div>
))}
</div>
</section>
{/* Verdict */}
<section className="flex flex-col gap-[16px] bg-newBgColorInner border border-newBorder rounded-[8px] p-[32px]">
<h2 className="text-[20px] font-semibold">The verdict</h2>
<p className="text-[15px] opacity-80 leading-[1.6]">{data.verdict}</p>
</section>
{/* FAQ */}
<section className="flex flex-col gap-[20px]">
<h2 className="text-[24px] font-semibold text-center">Frequently asked questions</h2>
<div className="flex flex-col gap-[16px]">
{data.faq.map((item) => (
<div
key={item.question}
className="border border-newBorder rounded-[8px] p-[20px]"
>
<div className="text-[15px] font-medium mb-[8px]">{item.question}</div>
<div className="text-[14px] opacity-70 leading-[1.6]">{item.answer}</div>
</div>
))}
</div>
</section>
{/* Bottom CTA */}
<section className="flex flex-col items-center gap-[16px] text-center">
<h2 className="text-[24px] font-semibold">
Switch from {data.name} to {brandName}
</h2>
<Link
href="/auth"
className="bg-btnPrimary text-btnText px-[28px] h-[46px] rounded-[6px] flex items-center justify-center text-[15px] font-medium"
>
Start free, no credit card
</Link>
</section>
</main>
</div>
);
};

View File

@ -488,13 +488,14 @@ export const AddProviderComponent: FC<{
if (response.status === 402) {
return;
}
const { url, err } = await response.json();
const { url, err, message } = await response.json();
if (err) {
toaster.show(
t(
'could_not_connect_to_platform',
'Could not connect to the platform'
),
message ||
t(
'could_not_connect_to_platform',
'Could not connect to the platform'
),
'warning'
);
return;

View File

@ -0,0 +1,55 @@
'use client';
import { useCallback } from 'react';
import { useModals } from '@gitroom/frontend/components/layout/new-modal';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useCalendar } from '@gitroom/frontend/components/launches/calendar.context';
import { BulkScheduleModal } from '@gitroom/frontend/components/launches/bulk-schedule/bulk.schedule.modal';
export const BulkScheduleButton = () => {
const t = useT();
const modal = useModals();
const { integrations, reloadCalendarView } = useCalendar();
const open = useCallback(() => {
modal.openModal({
title: t('bulk_schedule_title', 'Bulk schedule from CSV'),
withCloseButton: true,
classNames: {
modal: 'text-textColor',
},
children: (close: () => void) => (
<BulkScheduleModal
integrations={integrations}
close={close}
mutate={reloadCalendarView}
/>
),
});
}, [integrations]);
return (
<div
className="h-[44px] w-[44px] group-[.sidebar]:w-full bg-btnSimple text-btnText justify-center items-center flex rounded-[8px] cursor-pointer"
onClick={open}
data-tooltip-id="tooltip"
data-tooltip-content={t('bulk_schedule_title', 'Bulk schedule from CSV')}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={1.8}
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<path d="M14 2v6h6" />
<path d="M9 15h6M9 11h6M9 19h3" />
</svg>
</div>
);
};

View File

@ -0,0 +1,75 @@
import { parseBulkScheduleCsv, rowsToBulkSchedule } from './bulk.schedule.modal';
describe('parseBulkScheduleCsv', () => {
it('parses a simple header + rows CSV', () => {
const csv = 'date,content\n2026-11-01 09:00,Hello world\n2026-11-02 09:00,Second post';
expect(parseBulkScheduleCsv(csv)).toEqual([
['date', 'content'],
['2026-11-01 09:00', 'Hello world'],
['2026-11-02 09:00', 'Second post'],
]);
});
it('handles quoted fields with embedded commas and escaped quotes', () => {
const csv = 'date,content\n2026-11-01 09:00,"Hello, ""world"""';
expect(parseBulkScheduleCsv(csv)).toEqual([
['date', 'content'],
['2026-11-01 09:00', 'Hello, "world"'],
]);
});
it('handles CRLF line endings', () => {
const csv = 'date,content\r\n2026-11-01 09:00,One\r\n2026-11-02 09:00,Two';
expect(parseBulkScheduleCsv(csv)).toEqual([
['date', 'content'],
['2026-11-01 09:00', 'One'],
['2026-11-02 09:00', 'Two'],
]);
});
it('skips blank lines', () => {
const csv = 'date,content\n\n2026-11-01 09:00,One\n\n';
expect(parseBulkScheduleCsv(csv)).toEqual([
['date', 'content'],
['2026-11-01 09:00', 'One'],
]);
});
});
describe('rowsToBulkSchedule', () => {
it('drops a recognized date,content header row', () => {
const rows = [
['date', 'content'],
['2026-11-01T09:00:00Z', 'Hello'],
];
const parsed = rowsToBulkSchedule(rows);
expect(parsed).toHaveLength(1);
expect(parsed[0].error).toBeUndefined();
expect(parsed[0].content).toBe('Hello');
});
it('treats every row as data when there is no header', () => {
const rows = [['2026-11-01T09:00:00Z', 'Hello']];
const parsed = rowsToBulkSchedule(rows);
expect(parsed).toHaveLength(1);
expect(parsed[0].error).toBeUndefined();
});
it('flags a row with an invalid date', () => {
const rows = [
['date', 'content'],
['not-a-date', 'Hello'],
];
const parsed = rowsToBulkSchedule(rows);
expect(parsed[0].error).toMatch(/date/i);
});
it('flags a row with no content', () => {
const rows = [
['date', 'content'],
['2026-11-01T09:00:00Z', ''],
];
const parsed = rowsToBulkSchedule(rows);
expect(parsed[0].error).toMatch(/content/i);
});
});

View File

@ -0,0 +1,317 @@
'use client';
import { FC, useCallback, useMemo, useState } from 'react';
import dayjs from 'dayjs';
import clsx from 'clsx';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { Button } from '@gitroom/react/form/button';
import { Integrations } from '@gitroom/frontend/components/launches/calendar.context';
import { LoadingComponent } from '@gitroom/frontend/components/layout/loading';
// Bulk CSV scheduling only ever had a bare date/content row to work with (no
// media, no per-provider settings), so it only supports the platforms that
// don't need extra settings beyond their identifier. The actual list isn't
// hardcoded here — it's fetched from GET /posts/bulk-schedule/supported-providers,
// which returns the same generic, data-driven simpleTextProviders() the
// backend enforces in bulkSchedule(), so this never drifts out of sync.
const useBulkScheduleSupportedProviders = () => {
const fetch = useFetch();
const load = useCallback(async () => {
return (
await (await fetch('/posts/bulk-schedule/supported-providers')).json()
).providers as string[];
}, []);
return useSWR<string[]>('/posts/bulk-schedule/supported-providers', load, {
revalidateOnFocus: false,
fallbackData: [],
});
};
export interface ParsedBulkRow {
line: number;
date: string;
content: string;
error?: string;
}
// A tiny RFC4180-ish CSV parser: two columns (date, content), quoted fields
// may contain commas/newlines, "" inside a quoted field is a literal quote.
// Good enough for the simple two-column sheet this feature asks for, not a
// general-purpose CSV library.
export const parseBulkScheduleCsv = (csv: string): string[][] => {
const rows: string[][] = [];
let row: string[] = [];
let field = '';
let inQuotes = false;
for (let i = 0; i < csv.length; i++) {
const char = csv[i];
const next = csv[i + 1];
if (inQuotes) {
if (char === '"' && next === '"') {
field += '"';
i++;
} else if (char === '"') {
inQuotes = false;
} else {
field += char;
}
continue;
}
if (char === '"') {
inQuotes = true;
} else if (char === ',') {
row.push(field);
field = '';
} else if (char === '\n' || char === '\r') {
if (char === '\r' && next === '\n') {
i++;
}
row.push(field);
field = '';
rows.push(row);
row = [];
} else {
field += char;
}
}
if (field.length || row.length) {
row.push(field);
rows.push(row);
}
return rows.filter((r) => r.some((cell) => cell.trim().length));
};
export const rowsToBulkSchedule = (rows: string[][]): ParsedBulkRow[] => {
const dataRows =
rows.length &&
rows[0][0]?.trim().toLowerCase() === 'date' &&
rows[0][1]?.trim().toLowerCase() === 'content'
? rows.slice(1)
: rows;
return dataRows.map((cols, index) => {
const date = (cols[0] || '').trim();
const content = (cols[1] || '').trim();
const line = index + 1;
if (!date || !dayjs(date).isValid()) {
return { line, date, content, error: 'Invalid or missing date' };
}
if (!content) {
return { line, date, content, error: 'Missing content' };
}
return { line, date: dayjs(date).toISOString(), content };
});
};
interface BulkScheduleResult {
row: number;
success: boolean;
postId?: string;
error?: string;
}
export const BulkScheduleModal: FC<{
integrations: Integrations[];
close: () => void;
mutate: () => void;
}> = ({ integrations, close, mutate }) => {
const t = useT();
const fetch = useFetch();
const toaster = useToaster();
const { data: supportedProviders, isLoading: loadingProviders } =
useBulkScheduleSupportedProviders();
const [integrationId, setIntegrationId] = useState('');
const [csvText, setCsvText] = useState('');
const [submitting, setSubmitting] = useState(false);
const [results, setResults] = useState<BulkScheduleResult[] | null>(null);
const supportedIntegrations = useMemo(
() =>
integrations.filter(
(integration) =>
!integration.disabled &&
(supportedProviders || []).includes(integration.identifier)
),
[integrations, supportedProviders]
);
const parsedRows = useMemo(() => {
if (!csvText.trim()) {
return [];
}
return rowsToBulkSchedule(parseBulkScheduleCsv(csvText));
}, [csvText]);
const validRows = useMemo(
() => parsedRows.filter((row) => !row.error),
[parsedRows]
);
const submit = useCallback(async () => {
if (!integrationId || !validRows.length) {
return;
}
setSubmitting(true);
setResults(null);
try {
const response = await fetch('/posts/bulk-schedule', {
method: 'POST',
body: JSON.stringify({
integration: { id: integrationId },
posts: validRows.map((row) => ({
date: row.date,
content: row.content,
})),
}),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
toaster.show(
body?.message ||
t('bulk_schedule_failed', 'Could not schedule these posts'),
'warning'
);
return;
}
const data: BulkScheduleResult[] = await response.json();
setResults(data);
const succeeded = data.filter((r) => r.success).length;
if (succeeded) {
toaster.show(
t('bulk_schedule_success', '{{count}} posts scheduled', {
count: succeeded,
}),
'success'
);
mutate();
}
} finally {
setSubmitting(false);
}
}, [integrationId, validRows, mutate]);
if (loadingProviders) {
return <LoadingComponent />;
}
return (
<div className="flex flex-col gap-[16px] min-w-[560px] max-w-[640px]">
<div className="text-[13px] text-textItemBlur">
{t(
'bulk_schedule_hint',
'Paste a CSV with "date" and "content" columns (one post per row) to schedule many posts at once. Only works for channels that don\'t need extra settings: {{providers}}.',
{ providers: (supportedProviders || []).join(', ') }
)}
</div>
<div className="flex flex-col gap-[6px]">
<div className="text-[13px] font-[600]">
{t('bulk_schedule_channel', 'Channel')}
</div>
{supportedIntegrations.length === 0 ? (
<div className="text-[13px] text-red-400">
{t(
'bulk_schedule_no_channels',
'Connect one of these channels first: {{providers}}.',
{ providers: (supportedProviders || []).join(', ') }
)}
</div>
) : (
<div className="flex flex-col gap-[6px]">
{supportedIntegrations.map((integration) => (
<div
key={integration.id}
onClick={() => setIntegrationId(integration.id)}
className={clsx(
'flex items-center gap-[10px] p-[10px] rounded-[8px] border cursor-pointer transition-all',
integrationId === integration.id
? 'border-forth bg-forth/10'
: 'border-tableBorder hover:border-textColor/30'
)}
>
<img
src={integration.picture || '/no-picture.jpg'}
className="w-[24px] h-[24px] rounded-[6px]"
alt={integration.name}
/>
<div className="text-[13px]">{integration.name}</div>
</div>
))}
</div>
)}
</div>
<textarea
className="w-full h-[180px] p-[12px] rounded-[8px] bg-input border border-tableBorder text-textColor font-mono text-[13px] resize-y"
placeholder={
'date,content\n2026-11-01 09:00,First post\n2026-11-02 09:00,Second post'
}
value={csvText}
onChange={(e) => setCsvText(e.target.value)}
/>
{!!parsedRows.length && (
<div className="flex flex-col gap-[4px] max-h-[160px] overflow-y-auto text-[12px]">
{parsedRows.map((row) => (
<div
key={row.line}
className={clsx(
'flex gap-[8px]',
row.error ? 'text-red-400' : 'text-textItemBlur'
)}
>
<div className="w-[16px]">{row.line}.</div>
<div className="flex-1 truncate">
{row.error || `${row.date} — ${row.content}`}
</div>
</div>
))}
</div>
)}
{!!results && (
<div className="flex flex-col gap-[4px] max-h-[160px] overflow-y-auto text-[12px]">
{results.map((r) => (
<div
key={r.row}
className={r.success ? 'text-green-400' : 'text-red-400'}
>
{t('row', 'Row')} {r.row + 1}:{' '}
{r.success
? t('scheduled', 'Scheduled')
: r.error || t('failed', 'Failed')}
</div>
))}
</div>
)}
<div className="flex justify-end gap-[10px]">
<Button type="button" secondary={true} onClick={close}>
{t('cancel', 'Cancel')}
</Button>
<Button
onClick={submit}
loading={submitting}
disabled={!integrationId || !validRows.length}
>
{t('bulk_schedule_submit', 'Schedule {{count}} posts', {
count: validRows.length,
})}
</Button>
</div>
</div>
);
};

View File

@ -47,6 +47,7 @@ import SafeImage from '@gitroom/react/helpers/safe.image';
import { extend } from 'dayjs';
import { isUSCitizen } from './helpers/isuscitizen.utils';
import { StatisticsModal } from '@gitroom/frontend/components/launches/statistics';
import { EvergreenModal } from '@gitroom/frontend/components/launches/evergreen.modal';
import { MissingReleaseModal } from '@gitroom/frontend/components/launches/missing-release.modal';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import i18next from 'i18next';
@ -312,6 +313,22 @@ const usePostActions = (onMutate?: () => void) => {
[modal, t]
);
const openEvergreen = useCallback(
(id: string) => () => {
modal.openModal({
title: t('evergreen_recycling', 'Evergreen Recycling'),
closeOnClickOutside: true,
closeOnEscape: true,
withCloseButton: true,
classNames: {
modal: 'w-[100%] max-w-[600px]',
},
children: <EvergreenModal postId={id} />,
});
},
[modal, t]
);
const openMissingRelease = useCallback(
(id: string) => () => {
modal.openModal({
@ -390,7 +407,80 @@ const usePostActions = (onMutate?: () => void) => {
[fetch, toaster, t]
);
return { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease, openPost };
// Admin-side half of the approval gate (see Organization.requireApprovalForQueue):
// approving sends the post through the real "schedule" path (starts the
// publish workflow), rejecting just clears the pending flag and leaves it
// a normal, still-editable draft. Both actions are idempotent against a
// 404 - the toast surfaces it as a fast "someone else already handled it"
// rather than a crash.
const approvePendingPost = useCallback(
(post: any) => async () => {
const response = await fetch(`/posts/${post.id}/approve-queue`, {
method: 'PUT',
});
if (!response.ok) {
toaster.show(
t(
'could_not_approve_post',
'Could not approve this post - it may have already been handled'
),
'warning'
);
mutate();
return;
}
toaster.show(t('post_approved', 'Post approved and queued'), 'success');
mutate();
},
[toaster, t, fetch, mutate]
);
const rejectPendingPost = useCallback(
(post: any) => async () => {
if (
!(await deleteDialog(
t(
'are_you_sure_reject_post',
'Reject this post? It will stay as a draft for its author to edit.'
),
t('yes_reject_it', 'Yes, reject it'),
undefined,
t('no_keep_it_pending', 'No, keep it pending')
))
) {
return;
}
const response = await fetch(`/posts/${post.id}/reject-queue`, {
method: 'PUT',
});
if (!response.ok) {
toaster.show(
t(
'could_not_reject_post',
'Could not reject this post - it may have already been handled'
),
'warning'
);
mutate();
return;
}
toaster.show(t('post_rejected', 'Post rejected'), 'success');
mutate();
},
[toaster, t, fetch, mutate]
);
return {
editPost,
deletePost,
copyDebugJson,
openStatistics,
openEvergreen,
openMissingRelease,
openPost,
approvePendingPost,
rejectPendingPost,
};
};
// One day view slot. Memoized, so the now line's minute tick doesn't re-render the slots
@ -684,7 +774,17 @@ export const ListView = () => {
: t('no_posts', 'No posts');
// Use shared post actions hook
const { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease, openPost } = usePostActions();
const {
editPost,
deletePost,
copyDebugJson,
openStatistics,
openEvergreen,
openMissingRelease,
openPost,
approvePendingPost,
rejectPendingPost,
} = usePostActions();
// Group posts by date
const groupedPosts = useMemo(() => {
@ -732,6 +832,7 @@ export const ListView = () => {
date={newDayjs(post.publishDate)}
state={post.state}
statistics={openStatistics(post.id)}
evergreen={openEvergreen(post.id)}
missingRelease={openMissingRelease(post.id)}
openPost={openPost(post)}
editPost={editPost(post, false)}
@ -740,6 +841,8 @@ export const ListView = () => {
post={post}
integrations={integrations}
deletePost={deletePost(post)}
approvePost={approvePendingPost(post)}
rejectPost={rejectPendingPost(post)}
showTime={true}
/>
))}
@ -790,7 +893,17 @@ export const CalendarColumn: FC<{
const fetch = useFetch();
// Use shared post actions hook
const { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease, openPost } = usePostActions();
const {
editPost,
deletePost,
copyDebugJson,
openStatistics,
openEvergreen,
openMissingRelease,
openPost,
approvePendingPost,
rejectPendingPost,
} = usePostActions();
const postList = useMemo(() => {
return posts.filter((post) => {
const pList = dayjs.utc(post.publishDate).local();
@ -1073,6 +1186,7 @@ export const CalendarColumn: FC<{
date={getDate}
state={post.state}
statistics={openStatistics(post.id)}
evergreen={openEvergreen(post.id)}
missingRelease={openMissingRelease(post.id)}
openPost={openPost(post)}
editPost={editPost(post, false)}
@ -1081,6 +1195,8 @@ export const CalendarColumn: FC<{
post={post}
integrations={integrations}
deletePost={deletePost(post)}
approvePost={approvePendingPost(post)}
rejectPost={rejectPendingPost(post)}
/>
</div>
</div>
@ -1199,8 +1315,11 @@ const CalendarItem: FC<{
copyDebugJson?: () => void;
deletePost: () => void;
statistics: () => void;
evergreen?: () => void;
missingRelease?: () => void;
openPost: () => void;
approvePost?: () => void;
rejectPost?: () => void;
integrations: Integrations[];
state: State;
display: 'day' | 'week' | 'month';
@ -1216,6 +1335,7 @@ const CalendarItem: FC<{
const {
editPost,
statistics,
evergreen,
duplicatePost,
copyDebugJson,
post,
@ -1227,6 +1347,8 @@ const CalendarItem: FC<{
showTime,
missingRelease,
openPost,
approvePost,
rejectPost,
} = props;
const { disableXAnalytics } = useVariables();
const user = useUser();
@ -1234,6 +1356,18 @@ const CalendarItem: FC<{
user?.impersonate &&
post.creationMethod &&
post.creationMethod !== 'UNKNOWN';
// Only an ADMIN/SUPERADMIN can act on another member's pendingApproval
// draft (see Organization.requireApprovalForQueue) - a USER-level member
// sees their own submission in the calendar same as any other draft, just
// without these two actions.
const canModerateApproval =
user?.role === 'ADMIN' || user?.role === 'SUPERADMIN';
const showApprovalActions =
state === 'DRAFT' &&
(post as any).pendingApproval &&
canModerateApproval &&
approvePost &&
rejectPost;
const preview = useCallback(() => {
window.open(`/p/` + post.id + '?share=true', '_blank');
}, [post]);
@ -1288,6 +1422,34 @@ const CalendarItem: FC<{
✓
</div>
)}
{state === 'DRAFT' && (post as any).pendingApproval && (
<div
className={clsx(
'absolute -top-[6px] -start-[6px] z-20 w-[18px] h-[18px] rounded-full bg-yellow-500 flex items-center justify-center text-white',
display === 'month' && 'mobile:hidden'
)}
data-tooltip-id="tooltip"
data-tooltip-content={t(
'pending_approval_tooltip',
'Waiting for an admin to approve this post'
)}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="11"
height="11"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="M12 6v6l4 2" />
</svg>
</div>
)}
{showCreationMethodBadge && (
<div className="absolute -bottom-[4px] -right-[4px] z-10">
<CreationMethodBadge
@ -1362,6 +1524,39 @@ const CalendarItem: FC<{
) : (
<></>
)}{' '}
{state === 'PUBLISHED' && evergreen && (
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={evergreen}
>
<Recycle />
</div>
)}{' '}
{showApprovalActions && (
<>
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={approvePost}
>
<ApprovePost />
</div>{' '}
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer text-red-500',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={rejectPost}
>
<RejectPost />
</div>
</>
)}{' '}
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer',
@ -1417,7 +1612,11 @@ const CalendarItem: FC<{
)}
>
<div className="text-start">
{state === 'DRAFT' ? t('draft', 'Draft') + ': ' : ''}
{state === 'DRAFT'
? (post as any).pendingApproval
? t('pending_approval', 'Pending approval') + ': '
: t('draft', 'Draft') + ': '
: ''}
</div>
<div className="w-full relative">
<div className="absolute top-0 start-0 w-full text-ellipsis break-words line-clamp-1 text-start">
@ -1583,6 +1782,73 @@ export const Statistics = () => {
);
};
export const Recycle = () => {
const t = useT();
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
data-tooltip-id="tooltip"
data-tooltip-content={t('evergreen_recycling', 'Evergreen Recycling')}
>
<path d="M17 2.1 21 6l-4 3.9" />
<path d="M3 11v-1a4 4 0 0 1 4-4h14" />
<path d="M7 21.9 3 18l4-3.9" />
<path d="M21 13v1a4 4 0 0 1-4 4H3" />
</svg>
);
};
export const ApprovePost = () => {
const t = useT();
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.2"
strokeLinecap="round"
strokeLinejoin="round"
data-tooltip-id="tooltip"
data-tooltip-content={t('approve_post', 'Approve and queue')}
>
<polyline points="20 6 9 17 4 12" />
</svg>
);
};
export const RejectPost = () => {
const t = useT();
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.2"
strokeLinecap="round"
strokeLinejoin="round"
data-tooltip-id="tooltip"
data-tooltip-content={t('reject_post', 'Reject')}
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
);
};
export const DeletePost = () => {
const t = useT();
return (

View File

@ -0,0 +1,193 @@
import { FC, useCallback, useState } from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { Button } from '@gitroom/react/form/button';
import { Input } from '@gitroom/react/form/input';
import { LoadingComponent } from '@gitroom/frontend/components/layout/loading';
import dayjs from 'dayjs';
interface EvergreenRecycle {
id: string;
active: boolean;
intervalDays: number;
maxRecycles: number | null;
totalRecycles: number;
lastRecycledAt: string | null;
nextRecycleAt: string;
}
// Content recycling for an already-published post (Organization ->
// EvergreenRecycle, see schema.prisma). The actual republishing happens in
// the daily evergreenRecycleWorkflow batch, not from this modal - this is
// just schedule management (create/pause/resume/remove).
export const EvergreenModal: FC<{ postId: string }> = ({ postId }) => {
const t = useT();
const fetch = useFetch();
const toast = useToaster();
const [intervalDays, setIntervalDays] = useState('30');
const [maxRecycles, setMaxRecycles] = useState('');
const [loading, setLoading] = useState(false);
const load = useCallback(async () => {
return (await fetch(`/posts/${postId}/evergreen`)).json();
}, [postId]);
const { data, isLoading, mutate } = useSWR<EvergreenRecycle[]>(
`/posts/${postId}/evergreen`,
load
);
const create = useCallback(async () => {
const days = Number(intervalDays);
if (!days || days < 1) {
toast.show(
t('evergreen_invalid_interval', 'Enter how many days between recycles'),
'warning'
);
return;
}
setLoading(true);
try {
const response = await fetch(`/posts/${postId}/evergreen`, {
method: 'POST',
body: JSON.stringify({
intervalDays: days,
...(maxRecycles ? { maxRecycles: Number(maxRecycles) } : {}),
}),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
toast.show(
body?.message ||
t('evergreen_create_failed', 'Could not enable recycling'),
'warning'
);
return;
}
toast.show(
t('evergreen_created', 'This post will be recycled automatically'),
'success'
);
await mutate();
} finally {
setLoading(false);
}
}, [intervalDays, maxRecycles, postId, mutate]);
const toggleActive = useCallback(
(entry: EvergreenRecycle) => async () => {
await fetch(`/posts/evergreen/${entry.id}`, {
method: 'PUT',
body: JSON.stringify({ active: !entry.active }),
});
mutate();
},
[mutate]
);
const remove = useCallback(
(entry: EvergreenRecycle) => async () => {
await fetch(`/posts/evergreen/${entry.id}`, { method: 'DELETE' });
mutate();
},
[mutate]
);
return (
<div className="flex flex-col gap-[16px]">
<div className="text-[13px] text-textItemBlur">
{t(
'evergreen_hint',
'Automatically republish this post as a brand-new post every N days, so it keeps reaching new followers without touching the original.'
)}
</div>
{isLoading ? (
<LoadingComponent />
) : (
<>
{!!data?.length && (
<div className="flex flex-col gap-[8px]">
{data.map((entry) => (
<div
key={entry.id}
className="flex items-center justify-between gap-[10px] rounded-[8px] border border-tableBorder p-[10px] text-[13px]"
>
<div className="flex flex-col gap-[2px]">
<div>
{t('evergreen_every_days', 'Every {{days}} days', {
days: entry.intervalDays,
})}
{entry.maxRecycles
? ` · ${t('evergreen_max', 'max {{max}}', {
max: entry.maxRecycles,
})}`
: ''}
</div>
<div className="text-[11px] text-textItemBlur">
{t('evergreen_recycled_count', '{{count}} recycled', {
count: entry.totalRecycles,
})}
{entry.active
? ` · ${t('evergreen_next', 'next')} ${dayjs(
entry.nextRecycleAt
).format('MMM D, YYYY')}`
: ` · ${t('paused', 'Paused')}`}
</div>
</div>
<div className="flex gap-[10px]">
<button
type="button"
className="text-[12px] hover:underline"
onClick={toggleActive(entry)}
>
{entry.active
? t('pause', 'Pause')
: t('resume', 'Resume')}
</button>
<button
type="button"
className="text-[12px] hover:underline"
onClick={remove(entry)}
>
{t('remove', 'Remove')}
</button>
</div>
</div>
))}
</div>
)}
<div className="flex items-end gap-[10px]">
<div className="flex-1">
<Input
label={t('evergreen_interval_label', 'Days between recycles')}
name="intervalDays"
disableForm={true}
value={intervalDays}
onChange={(e: { target: { value: string } }) =>
setIntervalDays(e.target.value)
}
/>
</div>
<div className="flex-1">
<Input
label={t('evergreen_max_label', 'Max recycles (optional)')}
name="maxRecycles"
disableForm={true}
value={maxRecycles}
onChange={(e: { target: { value: string } }) =>
setMaxRecycles(e.target.value)
}
/>
</div>
<Button loading={loading} onClick={create}>
{t('evergreen_add', 'Add schedule')}
</Button>
</div>
</>
)}
</div>
);
};

View File

@ -25,6 +25,7 @@ import { DNDProvider } from '@gitroom/frontend/components/launches/helpers/dnd.p
import { GeneratorComponent } from './generator/generator';
import { useVariables } from '@gitroom/react/helpers/variable.context';
import { NewPost } from '@gitroom/frontend/components/launches/new.post';
import { BulkScheduleButton } from '@gitroom/frontend/components/launches/bulk-schedule/bulk.schedule.button';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useIntegrationList } from '@gitroom/frontend/components/launches/helpers/use.integration.list';
import useCookie from 'react-use-cookie';
@ -703,6 +704,7 @@ export const LaunchesComponent = () => {
<AddProviderButton update={() => update(true)} />
<div className="flex gap-[8px] group-[.sidebar]:flex-col mobile:hidden">
{sortedIntegrations?.length > 0 && <NewPost />}
{sortedIntegrations?.length > 0 && <BulkScheduleButton />}
{sortedIntegrations?.length > 0 &&
user?.tier?.ai &&
billingEnabled && <GeneratorComponent />}
@ -783,6 +785,7 @@ export const LaunchesComponent = () => {
{sortedIntegrations?.length > 0 ? (
<>
<NewPost />
<BulkScheduleButton />
{user?.tier?.ai && billingEnabled && <GeneratorComponent />}
</>
) : (

View File

@ -9,6 +9,7 @@ import { Button } from '@gitroom/react/form/button';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import useSWR from 'swr';
// @ts-ignore
import useKeypress from 'react-use-keypress';
import { useModals } from '@gitroom/frontend/components/layout/new-modal';
@ -34,6 +35,36 @@ const minutes = [...Array(60).keys()].map((i) => ({
value: i,
}));
export interface BestTimeSuggestion {
dayOfWeek: number;
hourOfDay: number;
avgEngagement: number;
sampleSize: number;
}
interface BestTimesResponse {
hasData: boolean;
suggestions: BestTimeSuggestion[];
}
// Separate hook per SWR call, per project convention (rules-of-hooks).
// Reads only the pre-aggregated /analytics/best-time endpoint - no live
// provider calls happen on render, the data is populated by a bounded daily
// batch job on the backend.
const useBestTimeSuggestions = (integrationId: string) => {
const fetch = useFetch();
const load = useCallback(async () => {
const response = await fetch(`/analytics/best-time/${integrationId}`);
return (await response.json()) as BestTimesResponse;
}, [integrationId]);
return useSWR<BestTimesResponse>(`best-time-${integrationId}`, load, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
fallbackData: { hasData: false, suggestions: [] },
});
};
export const TimeTable: FC<{
integration: Integrations;
mutate: () => void;
@ -116,6 +147,35 @@ export const TimeTable: FC<{
);
}, [currentTimes]);
const { data: bestTimes, isLoading: bestTimesLoading } =
useBestTimeSuggestions(props.integration.id);
const dayLabels = useMemo(
() => [
t('sunday_short', 'Sun'),
t('monday_short', 'Mon'),
t('tuesday_short', 'Tue'),
t('wednesday_short', 'Wed'),
t('thursday_short', 'Thu'),
t('friday_short', 'Fri'),
t('saturday_short', 'Sat'),
],
[t]
);
const addSuggestedTime = useCallback(
(hourOfDay: number) => () => {
// Suggestions are computed in UTC (see PostEngagementService), and the
// stored `time` field is already "minutes since UTC midnight" - same
// unit the display formatter above assumes - so no offset math here.
const value = hourOfDay * 60;
setCurrentTimes((prev) =>
prev.some((p) => p.time === value) ? prev : [...prev, { time: value }]
);
},
[]
);
const save = useCallback(async () => {
await fetch(`/integrations/${props.integration.id}/time`, {
method: 'POST',
@ -129,6 +189,63 @@ export const TimeTable: FC<{
return (
<div className="relative w-full max-w-[400px] mx-auto">
{/* Suggested Best Times Section */}
<div className="bg-newBgColorInner rounded-[12px] p-[20px] border border-newTableBorder mb-[20px]">
<div className="text-[15px] font-semibold mb-[8px] flex items-center gap-[8px]">
<DelayIcon size={18} className="text-[#612BD3]" />
{t('suggested_best_times', 'Suggested Best Times')}
</div>
<div className="text-[12px] text-newTextColor/50 mb-[12px]">
{t(
'suggested_best_times_description',
'Based on how your own past posts on this channel performed, grouped by day and hour (UTC).'
)}
</div>
{bestTimesLoading ? (
<div className="text-center py-[16px] text-newTextColor/40 text-[13px]">
{t('loading', 'Loading...')}
</div>
) : !bestTimes?.hasData ? (
<div className="text-center py-[16px] px-[12px] text-newTextColor/40 text-[13px] border border-dashed border-newTableBorder rounded-[8px]">
{t(
'not_enough_post_history_yet',
"Not enough published post history yet. Keep posting - we'll surface your best times once we have enough data."
)}
</div>
) : (
<div className="flex flex-col gap-[8px]">
{bestTimes.suggestions.map((suggestion) => (
<div
key={`${suggestion.dayOfWeek}-${suggestion.hourOfDay}`}
className="flex items-center justify-between h-[44px] px-[14px] rounded-[8px] bg-newBgColorInner border border-newTableBorder"
>
<div className="flex items-center gap-[10px]">
<div className="w-[8px] h-[8px] rounded-full bg-[#32d583]" />
<span className="text-[14px] font-medium">
{dayLabels[suggestion.dayOfWeek]}{' '}
{suggestion.hourOfDay.toString().padStart(2, '0')}:00 UTC
</span>
<span className="text-[12px] text-newTextColor/40">
{t('based_on_n_posts', 'based on {{count}} posts', {
count: suggestion.sampleSize,
})}
</span>
</div>
<button
type="button"
onClick={addSuggestedTime(suggestion.hourOfDay)}
className="h-[32px] px-[12px] bg-[#612BD3]/10 hover:bg-[#612BD3]/20 transition-colors rounded-[6px] flex items-center gap-[6px] text-[#612BD3] text-[13px] font-medium"
>
<PlusIcon size={12} />
{t('add', 'Add')}
</button>
</div>
))}
</div>
)}
</div>
{/* Add Time Slot Section */}
<div className="bg-newBgColorInner rounded-[12px] p-[20px] border border-newTableBorder">
<div className="text-[15px] font-semibold mb-[16px] flex items-center gap-[8px]">

View File

@ -748,6 +748,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
// every type of save is its own request, the drafts last, since a
// draft save skips the checks the others still run
let saved = false;
let pendingApproval = false;
for (const requestType of ['update', 'schedule', 'now', 'draft']) {
const request = {
type: requestType,
@ -782,6 +783,27 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
return;
}
saved = true;
// Set when the org has requireApprovalForQueue on and this
// caller is a USER-level member - the save was held as a draft
// awaiting an ADMIN/SUPERADMIN instead of being scheduled (see
// PostsService#createPost).
const savedPosts = await response.json().catch(() => []);
if (
Array.isArray(savedPosts) &&
savedPosts.some((p: any) => p?.pendingApproval)
) {
pendingApproval = true;
}
}
if (pendingApproval) {
toaster.show(
t(
'submitted_for_approval',
'Submitted for approval - an admin needs to approve it before it is queued'
),
'warning'
);
}
}

View File

@ -126,6 +126,10 @@ export const Providers = [
identifier: 'mastodon',
component: MastodonProvider,
},
{
identifier: 'mastodon-custom',
component: MastodonProvider,
},
{
identifier: 'bluesky',
component: BlueskyProvider,

View File

@ -5,6 +5,7 @@ import { Button } from '@gitroom/react/form/button';
import { Input } from '@gitroom/react/form/input';
import { Textarea } from '@gitroom/react/form/textarea';
import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { FormProvider, useForm } from 'react-hook-form';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
@ -129,10 +130,28 @@ const CommentComposer: FC<{
const toast = useToaster();
const modals = useModals();
const { recaptchaSiteKey } = useVariables();
const { previewId, pending, setPending, mutate } = usePreviewComments();
const {
previewId,
pending,
setPending,
mutate,
teamMembers,
canMention,
} = usePreviewComments();
const [loading, setLoading] = useState(false);
const [mentions, setMentions] = useState<string[]>([]);
const [assignedToId, setAssignedToId] = useState('');
const form = useForm({ values: { content: '' } });
const anchor = parentId ? null : pending;
const toggleMention = useCallback(
(id: string) => () =>
setMentions((current) =>
current.includes(id)
? current.filter((existing) => existing !== id)
: [...current, id]
),
[]
);
const askForName = useCallback(
() =>
@ -209,6 +228,10 @@ const CommentComposer: FC<{
: {}),
...(displayName ? { displayName } : {}),
...(recaptchaToken ? { recaptchaToken } : {}),
...(canMention && mentions.length ? { mentions } : {}),
...(canMention && !parentId && assignedToId
? { assignedToId }
: {}),
}),
}
);
@ -224,6 +247,8 @@ const CommentComposer: FC<{
}
form.reset({ content: '' });
setMentions([]);
setAssignedToId('');
if (anchor) {
setPending(null);
}
@ -233,7 +258,17 @@ const CommentComposer: FC<{
setLoading(false);
}
},
[user?.id, recaptchaSiteKey, previewId, parentId, anchor, askForName]
[
user?.id,
recaptchaSiteKey,
previewId,
parentId,
anchor,
askForName,
canMention,
mentions,
assignedToId,
]
);
return (
@ -268,6 +303,49 @@ const CommentComposer: FC<{
}
maxLength={2000}
/>
{canMention && !!teamMembers.length && (
<div className="flex flex-col gap-[10px] text-[12px]">
{!parentId && (
<label className="flex items-center gap-[8px]">
<span className="text-textItemBlur">
{t('preview_assign_to', 'Assign to')}
</span>
<select
className="bg-transparent border border-newTableBorder rounded-[4px] px-[6px] py-[2px]"
value={assignedToId}
onChange={(event) => setAssignedToId(event.target.value)}
>
<option value="">
{t('preview_unassigned', 'Unassigned')}
</option>
{teamMembers.map((member) => (
<option key={member.id} value={member.id}>
{member.name}
</option>
))}
</select>
</label>
)}
<div className="flex flex-wrap items-center gap-[10px]">
<span className="text-textItemBlur">
{t('preview_mention', 'Mention')}
</span>
{teamMembers.map((member) => (
<label
key={member.id}
className="flex items-center gap-[4px] cursor-pointer"
>
<input
type="checkbox"
checked={mentions.includes(member.id)}
onChange={toggleMention(member.id)}
/>
<span>{member.name}</span>
</label>
))}
</div>
</div>
)}
<div className="flex items-center justify-end gap-[10px] -mt-[14px]">
<svg
xmlns="http://www.w3.org/2000/svg"
@ -306,11 +384,20 @@ const CommentComposer: FC<{
const CommentBody: FC<{ comment: PreviewComment }> = ({ comment }) => {
const t = useT();
const { teamMembers } = usePreviewComments();
const mentionedNames = comment.mentionedUserIds
.map((id) => teamMembers.find((member) => member.id === id)?.name)
.filter(Boolean);
return (
<div className="flex flex-col gap-[4px]">
<div className="text-[14px] whitespace-pre-wrap break-words">
{comment.content}
</div>
{!!mentionedNames.length && (
<div className="text-[12px] text-btnPrimary">
{t('preview_cc', 'cc')}: {mentionedNames.join(', ')}
</div>
)}
<div className="text-[12px] text-textItemBlur">
{comment.name || t('reviewer', 'Reviewer')} ·{' '}
{dayjs(comment.createdAt).format('MMM D, YYYY HH:mm')}
@ -337,6 +424,7 @@ const ThreadCard: FC<{
setActiveThread,
hoveredThread,
setHoveredThread,
teamMembers,
} = usePreviewComments();
const resolved = !!comment.resolvedAt;
const anchored = comment.anchorStart !== null && comment.anchorEnd !== null;
@ -366,6 +454,24 @@ const ThreadCard: FC<{
mutate();
}, [comment.id, resolved]);
const changeAssignee = useCallback(
async (event: { target: { value: string } }) => {
const response = await fetch(`/posts/comments/${comment.id}/assign`, {
method: 'PUT',
body: JSON.stringify({ assignedToId: event.target.value || undefined }),
});
if (!response.ok) {
toast.show(
t('preview_comment_failed', 'Could not post the comment'),
'warning'
);
return;
}
mutate();
},
[comment.id]
);
return (
<div
ref={ref}
@ -390,6 +496,28 @@ const ThreadCard: FC<{
{t('preview_comment_text_changed', 'Text changed')}
</div>
)}
{canResolve && !!teamMembers.length ? (
<select
className="text-[11px] bg-transparent border border-newTableBorder rounded-[4px] px-[4px] py-[1px]"
value={comment.assignedToId || ''}
onChange={changeAssignee}
>
<option value="">{t('preview_unassigned', 'Unassigned')}</option>
{teamMembers.map((member) => (
<option key={member.id} value={member.id}>
{member.name}
</option>
))}
</select>
) : (
!!comment.assignedToName && (
<div className="text-[11px] rounded-[4px] px-[6px] py-[2px] bg-btnSimple">
{t('preview_assigned_to', 'Assigned to {{name}}', {
name: comment.assignedToName,
})}
</div>
)
)}
</div>
{!!comment.anchorQuote && (
<div
@ -464,6 +592,135 @@ const ThreadCard: FC<{
);
};
const ApprovalSection: FC = () => {
const t = useT();
const user = useUser();
const fetch = useFetch();
const toast = useToaster();
const modals = useModals();
const router = useRouter();
const { recaptchaSiteKey } = useVariables();
const { previewId, postState, comments, mutate } = usePreviewComments();
const [loading, setLoading] = useState(false);
const approval = useMemo(
() => comments.find((c) => c.isApproval && !c.parentId),
[comments]
);
const askForName = useCallback(
() =>
new Promise<string | null>((resolve) => {
modals.openModal({
classNames: {
modal: 'bg-transparent text-textColor',
},
title: t('preview_comment_your_name', 'Your name'),
withCloseButton: true,
onClose: () => resolve(null),
children: (close) => (
<ReviewerNameForm
onConfirm={(name) => {
resolve(name);
close();
}}
/>
),
});
}),
[t]
);
const approve = useCallback(async () => {
let displayName: string | undefined;
let recaptchaToken: string | undefined;
if (!user?.id) {
const name = await askForName();
if (!name) {
return;
}
displayName = name;
if (recaptchaSiteKey) {
const token = await loadRecaptchaToken(recaptchaSiteKey).catch(() => {
toast.show(
t('preview_approve_failed', 'Could not approve this post'),
'warning'
);
return null;
});
if (!token) {
return;
}
recaptchaToken = token;
}
}
setLoading(true);
try {
const response = await fetch(`/public/posts/${previewId}/approve`, {
method: 'POST',
body: JSON.stringify({
...(displayName ? { displayName } : {}),
...(recaptchaToken ? { recaptchaToken } : {}),
}),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
toast.show(
body?.message ||
t('preview_approve_failed', 'Could not approve this post'),
'warning'
);
return;
}
toast.show(
t('preview_approved', 'Post approved and scheduled'),
'success'
);
await mutate();
router.refresh();
} finally {
setLoading(false);
}
}, [user?.id, recaptchaSiteKey, previewId]);
if (postState !== 'DRAFT' && !approval) {
return null;
}
return (
<div className="flex flex-col gap-[10px] rounded-[8px] border border-newTableBorder p-[12px]">
{!!approval && (
<div className="text-[13px] text-textItemBlur">
✓{' '}
{t(
'preview_approved_by',
'{{name}} approved this post for publishing.',
{ name: approval.name || t('reviewer', 'Reviewer') }
)}
</div>
)}
{postState === 'DRAFT' && (
<>
<div className="text-[13px] text-textItemBlur">
{t(
'preview_approve_hint',
'Happy with this draft? Approve it to schedule it for publishing.'
)}
</div>
<Button onClick={approve} loading={loading}>
{t('approve_and_schedule', 'Approve & Schedule')}
</Button>
</>
)}
</div>
);
};
export const CommentsComponents: FC<{ previewId: string }> = () => {
const t = useT();
const user = useUser();
@ -500,6 +757,7 @@ export const CommentsComponents: FC<{ previewId: string }> = () => {
return (
<div className="flex flex-col gap-[16px]">
<ApprovalSection />
<div className="text-[18px] font-[600]">{t('comments', 'Comments')}</div>
<CommentComposer />
{!isLoading && !threads.length && (

View File

@ -10,6 +10,7 @@ import {
} from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useUser } from '@gitroom/frontend/components/layout/user.context';
export interface PreviewComment {
id: string;
@ -20,8 +21,19 @@ export interface PreviewComment {
anchorEnd: number | null;
anchorQuote: string | null;
resolvedAt: string | null;
isApproval: boolean;
createdAt: string;
name: string | null;
mentionedUserIds: string[];
assignedToId: string | null;
assignedToName: string | null;
}
export interface CommentTeamMember {
id: string;
name: string;
email: string;
role: string;
}
export interface PendingAnchor {
@ -39,13 +51,33 @@ export interface ActiveThread {
source: 'mark' | 'card';
}
const useComments = (previewId: string) => {
// `useAuthed` picks the authenticated route (org-scoped, so it returns the
// mention/assignment identities) vs. the fully public one (same comments,
// those identities stripped) - see PostsService.getComments's
// includeInternal gate. Matches CommentComposer's own
// user?.id-vs-public branching for which endpoint to POST to.
const useComments = (previewId: string, useAuthed: boolean) => {
const fetch = useFetch();
const path = useAuthed
? `/posts/${previewId}/comments`
: `/public/posts/${previewId}/comments`;
const load = useCallback(async () => {
return (await fetch(path)).json();
}, [path]);
return useSWR<{ comments: PreviewComment[] }>(path, load);
};
// Backs the @mention/assign picker - only fetched for a logged-in team
// member viewing their own org's preview (the public reviewer never needs,
// or is allowed to see, the team list). A disabled SWR key (null) skips the
// request entirely rather than firing it and discarding the result.
const useCommentTeamMembers = (enabled: boolean) => {
const fetch = useFetch();
const load = useCallback(async () => {
return (await fetch(`/public/posts/${previewId}/comments`)).json();
}, [previewId]);
return useSWR<{ comments: PreviewComment[] }>(
`/public/posts/${previewId}/comments`,
return (await fetch('/posts/comments/team-members')).json();
}, []);
return useSWR<CommentTeamMember[]>(
enabled ? '/posts/comments/team-members' : null,
load
);
};
@ -54,6 +86,7 @@ interface PreviewCommentsContextInterface {
previewId: string;
postIds: string[];
organizationId: string;
postState: string;
comments: PreviewComment[];
isLoading: boolean;
mutate: () => Promise<any>;
@ -63,6 +96,8 @@ interface PreviewCommentsContextInterface {
setActiveThread: (thread: ActiveThread | null) => void;
hoveredThread: string | null;
setHoveredThread: (id: string | null) => void;
teamMembers: CommentTeamMember[];
canMention: boolean;
}
const PreviewCommentsContext = createContext<PreviewCommentsContextInterface>(
@ -73,12 +108,16 @@ export const PreviewCommentsProvider: FC<{
previewId: string;
postIds: string[];
organizationId: string;
postState: string;
children: ReactNode;
}> = ({ previewId, postIds, organizationId, children }) => {
const { data, mutate, isLoading } = useComments(previewId);
}> = ({ previewId, postIds, organizationId, postState, children }) => {
const [pending, setPending] = useState<PendingAnchor | null>(null);
const [activeThread, setActiveThread] = useState<ActiveThread | null>(null);
const [hoveredThread, setHoveredThread] = useState<string | null>(null);
const user = useUser();
const canMention = !!user?.id && user?.orgId === organizationId;
const { data, mutate, isLoading } = useComments(previewId, canMention);
const { data: teamMembers } = useCommentTeamMembers(canMention);
return (
<PreviewCommentsContext.Provider
@ -86,6 +125,7 @@ export const PreviewCommentsProvider: FC<{
previewId,
postIds,
organizationId,
postState,
comments: data?.comments || [],
isLoading,
mutate,
@ -95,6 +135,8 @@ export const PreviewCommentsProvider: FC<{
setActiveThread,
hoveredThread,
setHoveredThread,
teamMembers: teamMembers || [],
canMention,
}}
>
{children}

View File

@ -0,0 +1,93 @@
'use client';
import React, { useCallback } from 'react';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import useSWR from 'swr';
import { Checkbox } from '@gitroom/react/form/checkbox';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
interface ApprovalQueueResponse {
requireApprovalForQueue: boolean;
}
export const useApprovalQueuePreference = () => {
const fetch = useFetch();
const load = useCallback(async () => {
return (await fetch('/settings/approval-queue')).json();
}, []);
return useSWR<ApprovalQueueResponse>('approval-queue-preference', load, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
revalidateOnMount: true,
refreshWhenHidden: false,
refreshWhenOffline: false,
});
};
// Admin-only toggle for Organization.requireApprovalForQueue: once on, a
// USER-level member's schedule/publish-now save is held as a draft awaiting
// an ADMIN/SUPERADMIN approval instead of going straight to the queue (see
// PostsService#createPost). Rendered only for ADMIN/SUPERADMIN callers by
// TeamsComponent - the backend also enforces this via the ADMIN policy on
// POST /settings/approval-queue, so this is a UX nicety, not the real gate.
const ApprovalQueuePreferenceComponent = () => {
const t = useT();
const fetch = useFetch();
const toaster = useToaster();
const { data, isLoading, mutate } = useApprovalQueuePreference();
const toggle = useCallback(async () => {
const newValue = !data?.requireApprovalForQueue;
mutate({ requireApprovalForQueue: newValue });
const response = await fetch('/settings/approval-queue', {
method: 'POST',
body: JSON.stringify({ requireApprovalForQueue: newValue }),
});
if (!response.ok) {
mutate({ requireApprovalForQueue: !newValue });
toaster.show(
t('could_not_update_setting', 'Could not update this setting'),
'warning'
);
return;
}
toaster.show(t('settings_updated', 'Settings updated'), 'success');
}, [data, fetch, mutate, toaster, t]);
if (isLoading) {
return null;
}
return (
<div className="my-[16px] mt-[16px] bg-sixth border-fifth border rounded-[4px] p-[24px] flex flex-col gap-[24px]">
<div className="flex items-center justify-between gap-[24px]">
<div className="flex flex-col flex-1">
<div className="text-[14px]">
{t('require_approval_for_queue', 'Require approval before posts go live')}
</div>
<div className="text-[12px] text-customColor18">
{t(
'require_approval_for_queue_description',
'When on, a schedule or publish-now save by a regular team member is held as a draft until an admin approves it.'
)}
</div>
</div>
<Checkbox
name="requireApprovalForQueue"
disableForm={true}
checked={!!data?.requireApprovalForQueue}
onChange={toggle}
/>
</div>
</div>
);
};
export default ApprovalQueuePreferenceComponent;

View File

@ -0,0 +1,124 @@
'use client';
import React, { useCallback } from 'react';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import useSWR from 'swr';
import { Button } from '@gitroom/react/form/button';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';
interface PendingApprovalPost {
id: string;
content: string;
publishDate: string;
group: string;
integration: {
id: string;
name: string;
picture: string | null;
providerIdentifier: string;
};
createdBy: { id: string; name: string | null; email: string } | null;
}
// ADMIN/SUPERADMIN-only - every post a USER-level member couldn't queue
// directly because the org has Organization.requireApprovalForQueue on
// (see posts.controller.ts GET /posts/pending-approval). Complements the
// per-post approve/reject actions already on the calendar card itself -
// this is the "don't have to go hunting on the calendar" view.
export const PendingApprovalsComponent = () => {
const t = useT();
const fetch = useFetch();
const toaster = useToaster();
const load = useCallback(async () => {
return (await fetch('/posts/pending-approval')).json();
}, []);
const { data, mutate, isLoading } = useSWR<PendingApprovalPost[]>(
'pending-approval-posts',
load,
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
}
);
const decide = useCallback(
(post: PendingApprovalPost, action: 'approve' | 'reject') => async () => {
const response = await fetch(`/posts/${post.id}/${action}-queue`, {
method: 'PUT',
});
if (!response.ok) {
toaster.show(
t(
'could_not_update_post',
'Could not update this post - it may have already been handled'
),
'warning'
);
mutate();
return;
}
toaster.show(
action === 'approve'
? t('post_approved', 'Post approved and queued')
: t('post_rejected', 'Post rejected'),
'success'
);
mutate();
},
[fetch, mutate, toaster, t]
);
if (isLoading || !data?.length) {
return null;
}
return (
<div className="flex flex-col">
<h3 className="text-[20px]">
{t('pending_approvals', 'Pending Approvals')}
</h3>
<div className="text-customColor18 mt-[4px]">
{t(
'pending_approvals_description',
'Posts saved by team members while approval is required, waiting for you'
)}
</div>
<div className="my-[16px] mt-[16px] bg-sixth border-fifth border rounded-[4px] p-[24px] flex flex-col gap-[16px]">
{data.map((post) => (
<div
key={post.id}
className="flex items-center gap-[12px] border-b border-fifth pb-[12px] last:border-0 last:pb-0"
>
<div className="flex-1 flex flex-col">
<div className="text-[12px] text-customColor18">
{post.createdBy?.name || post.createdBy?.email || t('unknown', 'Unknown')}
{' · '}
{newDayjs(post.publishDate).local().format('MMM D, HH:mm')}
{' · '}
{post.integration.name}
</div>
<div className="text-[14px] line-clamp-2">
{post.content || t('no_content', 'no content')}
</div>
</div>
<div className="flex gap-[8px]">
<Button onClick={decide(post, 'approve')}>
{t('approve', 'Approve')}
</Button>
<Button secondary={true} onClick={decide(post, 'reject')}>
{t('reject', 'Reject')}
</Button>
</div>
</div>
))}
</div>
</div>
);
};
export default PendingApprovalsComponent;

View File

@ -17,6 +17,8 @@ import { useToaster } from '@gitroom/react/toaster/toaster';
import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import copy from 'copy-to-clipboard';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import ApprovalQueuePreferenceComponent from '@gitroom/frontend/components/settings/approval-queue-preference.component';
import { PendingApprovalsComponent } from '@gitroom/frontend/components/settings/pending-approvals.component';
const roles = [
{
@ -117,6 +119,7 @@ export const TeamsComponent = () => {
const fetch = useFetch();
const user = useUser();
const modals = useModals();
const toast = useToaster();
const t = useT();
const myLevel = user?.role === 'USER' ? 0 : user?.role === 'ADMIN' ? 1 : 2;
const getLevel = useCallback(
@ -149,6 +152,40 @@ export const TeamsComponent = () => {
revalidateOnReconnect: false,
revalidateIfStale: false,
});
const loadOrganizations = useCallback(async () => {
return await (await fetch('/user/organizations')).json();
}, []);
// Shares the 'organizations' SWR cache key with the organization switcher
// (organization.selector.tsx) instead of fetching the same list twice.
const { data: organizations } = useSWR('organizations', loadOrganizations, {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
});
const canLeave = (organizations?.length || 0) > 1;
const leaveOrganization = useCallback(async () => {
if (
!(await deleteDialog(
t(
'are_you_sure_leave_organization',
'Are you sure you want to leave this organization? You will lose access to it unless invited back.'
)
))
) {
return;
}
const response = await fetch('/settings/team/leave', { method: 'POST' });
if (!response.ok) {
const { message } = await response.json().catch(() => ({} as any));
toast.show(
(Array.isArray(message) ? message[0] : message) ||
t('could_not_leave_organization', 'Could not leave the organization'),
'warning'
);
return;
}
window.location.href = '/';
}, [t]);
const remove = useCallback(
(toRemove: {
user: {
@ -226,12 +263,23 @@ export const TeamsComponent = () => {
</div>
))}
</div>
<div>
<div className="flex gap-[12px]">
<Button onClick={addMember}>
{t('add_another_member', 'Add another member')}
</Button>
{canLeave && (
<Button secondary={true} onClick={leaveOrganization}>
{t('leave_organization', 'Leave organization')}
</Button>
)}
</div>
</div>
{+myLevel >= 1 && (
<>
<ApprovalQueuePreferenceComponent />
<PendingApprovalsComponent />
</>
)}
</div>
);
};

View File

@ -0,0 +1,157 @@
'use client';
import React, { FC, useCallback, useState } from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { Button } from '@gitroom/react/form/button';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
const DELIVERIES_PAGE_SIZE = 25;
interface Delivery {
id: string;
event: string;
postId: string | null;
url: string;
statusCode: number | null;
success: boolean;
attempts: number;
error: string | null;
durationMs: number | null;
createdAt: string;
}
interface DeliveriesResponse {
total: number;
deliveries: Delivery[];
}
const useDeliveries = (webhookId: string, page: number) => {
const fetch = useFetch();
const load = useCallback(async () => {
return (
await fetch(`/webhooks/${webhookId}/deliveries?page=${page}`)
).json();
}, [webhookId, page]);
return useSWR<DeliveriesResponse>(
`webhooks-deliveries-${webhookId}-${page}`,
load
);
};
const statusLabel = (
delivery: Delivery,
t: (key: string, fallback: string) => string
) => {
if (delivery.success) {
return t('delivered', 'Delivered');
}
return t('failed', 'Failed');
};
export const WebhookDeliveries: FC<{ webhookId: string; name: string }> = ({
webhookId,
name,
}) => {
const t = useT();
const toaster = useToaster();
const [page, setPage] = useState(1);
const { data, isLoading, mutate } = useDeliveries(webhookId, page);
const fetch = useFetch();
const redeliver = useCallback(
(deliveryId: string) => async () => {
const result = await (
await fetch(`/webhooks/deliveries/${deliveryId}/redeliver`, {
method: 'POST',
})
).json();
if (result?.success) {
toaster.show(t('delivery_succeeded', 'Delivery succeeded'), 'success');
} else {
toaster.show(
t('delivery_failed_check_the_log', 'Delivery failed, check the log'),
'warning'
);
}
mutate();
},
[mutate]
);
const totalPages = Math.max(
1,
Math.ceil((data?.total || 0) / DELIVERIES_PAGE_SIZE)
);
return (
<div className="flex flex-col gap-[12px] min-w-[600px]">
<div className="text-[14px] opacity-70">
{t(
'recent_delivery_attempts_for',
`Recent delivery attempts for ${name}`,
{ name }
)}
</div>
{!isLoading && !data?.deliveries?.length && (
<div className="text-customColor18">
{t('no_deliveries_yet', 'No deliveries yet.')}
</div>
)}
{!!data?.deliveries?.length && (
<div className="grid grid-cols-[1.2fr,0.8fr,0.6fr,0.6fr,1.6fr,0.8fr] gap-y-[8px] gap-x-[8px] text-[13px]">
<div className="opacity-60">{t('event', 'Event')}</div>
<div className="opacity-60">{t('date', 'Date')}</div>
<div className="opacity-60">{t('status', 'Status')}</div>
<div className="opacity-60">{t('attempts', 'Attempts')}</div>
<div className="opacity-60">{t('error', 'Error')}</div>
<div className="opacity-60">{t('action', 'Action')}</div>
{data.deliveries.map((delivery) => (
<React.Fragment key={delivery.id}>
<div>{delivery.event}</div>
<div>{new Date(delivery.createdAt).toLocaleString()}</div>
<div
className={
delivery.success ? 'text-customColor28' : 'text-red-500'
}
>
{statusLabel(delivery, t)}
{delivery.statusCode ? ` (${delivery.statusCode})` : ''}
</div>
<div>{delivery.attempts}</div>
<div className="break-all opacity-80">
{delivery.error || '—'}
</div>
<div>
<Button secondary onClick={redeliver(delivery.id)}>
{t('redeliver', 'Redeliver')}
</Button>
</div>
</React.Fragment>
))}
</div>
)}
<div className="flex items-center justify-between mt-[8px]">
<div className="text-[13px] opacity-70">
{t('page_of', `Page ${page} of ${totalPages}`, { page, totalPages })}
</div>
<div className="flex gap-[8px]">
<Button
secondary
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
{t('previous', 'Previous')}
</Button>
<Button
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
{t('next', 'Next')}
</Button>
</div>
</div>
</div>
);
};

View File

@ -16,6 +16,8 @@ import { useToaster } from '@gitroom/react/toaster/toaster';
import clsx from 'clsx';
import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { WebhookDeliveries } from '@gitroom/frontend/components/webhooks/webhook.deliveries';
import { CopyButton } from '@gitroom/frontend/components/public-api/public.component';
export const Webhooks: FC = () => {
const fetch = useFetch();
@ -57,6 +59,17 @@ export const Webhooks: FC = () => {
},
[]
);
const showLogs = useCallback(
(data: any) => () => {
modal.openModal({
title: t('delivery_log', 'Delivery log'),
withCloseButton: true,
classNames: { modal: 'w-[100%] max-w-[900px]' },
children: <WebhookDeliveries webhookId={data.id} name={data.name} />,
});
},
[t]
);
return (
<div className="flex flex-col">
@ -72,10 +85,11 @@ export const Webhooks: FC = () => {
<div className="my-[16px] mt-[16px] bg-sixth border-fifth items-center border rounded-[4px] p-[24px] flex gap-[24px]">
<div className="flex flex-col w-full">
{!!data?.length && (
<div className="grid grid-cols-[1fr,1fr,1fr,1fr] w-full gap-y-[10px]">
<div className="grid grid-cols-[1fr,1fr,1fr,1fr,1fr] w-full gap-y-[10px]">
<div>{t('name', 'Name')}</div>
<div>{t('url', 'URL')}</div>
<div>{t('edit', 'Edit')}</div>
<div>{t('logs', 'Logs')}</div>
<div>{t('delete', 'Delete')}</div>
{data?.map((p: any) => (
<Fragment key={p.id}>
@ -88,6 +102,13 @@ export const Webhooks: FC = () => {
</Button>
</div>
</div>
<div className="flex flex-col justify-center">
<div>
<Button secondary onClick={showLogs(p)}>
{t('logs', 'Logs')}
</Button>
</div>
</div>
<div className="flex flex-col justify-center">
<div>
<Button onClick={deleteHook(p)}>
@ -116,6 +137,7 @@ const details = object().shape({
name: string().required(),
url: string().url().required(),
integrations: array(),
events: array(),
});
const getWebhookOptions = (t: (key: string, fallback: string) => string) => [
{
@ -127,6 +149,16 @@ const getWebhookOptions = (t: (key: string, fallback: string) => string) => [
value: 'specific',
},
];
const getWebhookEventOptions = (t: (key: string, fallback: string) => string) => [
{
value: 'post.published',
label: t('event_post_published', 'A post is published successfully'),
},
{
value: 'post.failed',
label: t('event_post_failed', 'A post fails to publish'),
},
];
export const AddOrEditWebhook: FC<{
data?: any;
reload: () => void;
@ -140,15 +172,30 @@ export const AddOrEditWebhook: FC<{
);
const modal = useModals();
const toast = useToaster();
const eventOptions = getWebhookEventOptions(t);
const form = useForm({
resolver: yupResolver(details),
values: {
name: data?.name || '',
url: data?.url || '',
integrations: data?.integrations?.map((p: any) => p.integration) || [],
events: data?.events || [],
},
});
const integrations = form.watch('integrations');
const events = form.watch('events') as string[];
const toggleEvent = useCallback(
(value: string) => () => {
const current: string[] = form.getValues('events') || [];
form.setValue(
'events',
current.includes(value)
? current.filter((e) => e !== value)
: [...current, value]
);
},
[]
);
const integration = useCallback(async () => {
return (await fetch('/integrations/list')).json();
}, []);
@ -172,19 +219,46 @@ export const AddOrEditWebhook: FC<{
refreshWhenHidden: false,
refreshWhenOffline: false,
});
const revealSecret = useCallback(
(secret: string) => {
modal.openModal({
title: t('webhook_signing_secret', 'Webhook signing secret'),
withCloseButton: true,
children: (
<div className="flex flex-col gap-[12px]">
<div className="text-customColor18">
{t(
'webhook_secret_shown_once',
"Copy this now, it won't be shown again. Use it to verify the X-Postiz-Signature header (HMAC SHA-256 of the raw request body) on incoming requests."
)}
</div>
<div className="flex items-center gap-[8px]">
<div className="break-all font-mono text-[12px] bg-sixth p-[8px] rounded flex-1">
{secret}
</div>
<CopyButton text={secret} label={t('secret', 'Secret')} />
</div>
</div>
),
});
},
[t]
);
const callBack = useCallback(
async (values: any) => {
await fetch('/webhooks', {
method: data?.id ? 'PUT' : 'POST',
body: JSON.stringify({
...(data?.id
? {
id: data.id,
}
: {}),
...values,
}),
});
const result = await (
await fetch('/webhooks', {
method: data?.id ? 'PUT' : 'POST',
body: JSON.stringify({
...(data?.id
? {
id: data.id,
}
: {}),
...values,
}),
})
).json();
toast.show(
data?.id
? t('webhook_updated_successfully', 'Webhook updated successfully')
@ -192,10 +266,35 @@ export const AddOrEditWebhook: FC<{
'success'
);
modal.closeAll();
if (result?.secret) {
revealSecret(result.secret);
}
reload();
},
[data, integrations]
[data, integrations, revealSecret]
);
const regenerateSecret = useCallback(async () => {
if (
!(await deleteDialog(
t(
'regenerate_secret_confirm',
'Regenerating invalidates the current signing secret - any system verifying it will need the new one. Continue?'
),
t('yes_regenerate', 'Yes, regenerate'),
t('regenerate_webhook_secret', 'Regenerate webhook secret')
))
) {
return;
}
const result = await (
await fetch(`/webhooks/${data.id}/secret`, { method: 'POST' })
).json();
modal.closeAll();
if (result?.secret) {
revealSecret(result.secret);
}
reload();
}, [data, revealSecret]);
const sendTest = useCallback(async () => {
const url = form.getValues('url');
toast.show(t('webhook_sent', 'Webhook send'), 'success');
@ -280,6 +379,32 @@ export const AddOrEditWebhook: FC<{
isMain={true}
/>
)}
<div className="mt-[16px]">
<div className="mb-[8px]">
{t('events', 'Events')}
</div>
<div className="text-customColor18 text-[12px] mb-[8px]">
{t(
'webhook_events_hint',
'Leave everything unchecked to receive every event.'
)}
</div>
<div className="flex flex-col gap-[6px]">
{eventOptions.map((option) => (
<label
key={option.value}
className="flex items-center gap-[8px] cursor-pointer"
>
<input
type="checkbox"
checked={(events || []).includes(option.value)}
onChange={toggleEvent(option.value)}
/>
<span>{option.label}</span>
</label>
))}
</div>
</div>
<div className="flex gap-[10px]">
<Button
type="submit"
@ -305,6 +430,16 @@ export const AddOrEditWebhook: FC<{
>
{t('send_test', 'Send Test')}
</Button>
{!!data?.id && (
<Button
type="button"
secondary={true}
className="mt-[24px]"
onClick={regenerateSecret}
>
{t('regenerate_secret', 'Regenerate secret')}
</Button>
)}
</div>
</div>
</div>

View File

@ -48,6 +48,9 @@ export async function proxy(request: NextRequest) {
nextUrl.pathname.startsWith('/p/') ||
nextUrl.pathname.startsWith('/provider/') ||
nextUrl.pathname.startsWith('/icons/') ||
// bottom-of-funnel SEO landing pages - must stay reachable by signed-out
// visitors (that's the entire audience searching "X vs Postiz")
nextUrl.pathname.startsWith('/compare/') ||
// the consent screen of MCP / OAuth clients handles signed-out visitors
// itself (sign in and come back, or connect a self-hosted instance)
nextUrl.pathname.startsWith('/oauth/authorize')

View File

@ -0,0 +1,14 @@
import { Injectable } from '@nestjs/common';
import { Activity, ActivityMethod } from 'nestjs-temporal-core';
import { EvergreenService } from '@gitroom/nestjs-libraries/database/prisma/evergreen/evergreen.service';
@Injectable()
@Activity()
export class EvergreenActivity {
constructor(private _evergreenService: EvergreenService) {}
@ActivityMethod()
async recycleDueBatch() {
return this._evergreenService.runDueBatch();
}
}

View File

@ -118,7 +118,7 @@ export class PostActivity {
for (const post of list) {
await this._temporalService.client
.getRawClient()
.workflow.signalWithStart('postWorkflowV112', {
.workflow.signalWithStart('postWorkflowV113', {
workflowId: `post_${post.id}`,
taskQueue: 'main',
signal: 'poke',
@ -492,7 +492,49 @@ export class PostActivity {
@ActivityMethod()
async changeState(id: string, state: State, err?: any, body?: any) {
await this._postService.changeState(id, state, err, body);
const updated = await this._postService.changeState(id, state, err, body);
// Webhooks are best-effort and must never affect the publish outcome -
// same contract as sendWebhooks below, just for the failure path (there
// is no separate "did it fail" call site to hang this off elsewhere).
if (state === State.ERROR && updated?.organizationId && updated?.integrationId) {
try {
const webhooks = (
await this._webhookService.getWebhooks(updated.organizationId)
).filter((f) => {
const inScope =
f.integrations.length === 0 ||
f.integrations.some((i) => i.integration.id === updated.integrationId);
const subscribed = f.events.length === 0 || f.events.includes('post.failed');
return inScope && subscribed;
});
if (webhooks.length) {
const post = await this._postService.getPostByForWebhookId(
id,
updated.integrationId
);
const requestBody = JSON.stringify(post);
await Promise.all(
webhooks.map((webhook) =>
this._webhookService
.sendWithRetry({
webhookId: webhook.id,
url: webhook.url,
secret: webhook.secret,
event: 'post.failed',
postId: id,
requestBody,
dispatcher: getSsrfSafeDispatcher(),
})
.catch(() => {})
)
);
}
} catch (e) {
/**empty**/
}
}
}
@ActivityMethod()
@ -512,10 +554,12 @@ export class PostActivity {
try {
const webhooks = (await this._webhookService.getWebhooks(orgId)).filter(
(f) => {
return (
const inScope =
f.integrations.length === 0 ||
f.integrations.some((i) => i.integration.id === integrationId)
);
f.integrations.some((i) => i.integration.id === integrationId);
const subscribed =
f.events.length === 0 || f.events.includes('post.published');
return inScope && subscribed;
}
);
@ -527,19 +571,21 @@ export class PostActivity {
postId,
integrationId
);
const requestBody = JSON.stringify(post);
await Promise.all(
webhooks.map(async (webhook) => {
try {
// webhook.url is validated at save time, but DNS can change
// between then and now - pin resolution like every other
// user-influenced outbound request.
await fetch(webhook.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(post),
// @ts-ignore — undici option, not in lib.dom fetch types
// user-influenced outbound request. Delivery is signed, retried
// with backoff on transient failures, and logged either way.
await this._webhookService.sendWithRetry({
webhookId: webhook.id,
url: webhook.url,
secret: webhook.secret,
event: 'post.published',
postId,
requestBody,
dispatcher: getSsrfSafeDispatcher(),
});
} catch (e) {

View File

@ -0,0 +1,14 @@
import { Injectable } from '@nestjs/common';
import { Activity, ActivityMethod } from 'nestjs-temporal-core';
import { PostEngagementService } from '@gitroom/nestjs-libraries/database/prisma/post-engagement/post-engagement.service';
@Injectable()
@Activity()
export class PostEngagementActivity {
constructor(private _postEngagementService: PostEngagementService) {}
@ActivityMethod()
async captureEngagementSnapshotBatch() {
return this._postEngagementService.captureBatch();
}
}

View File

@ -8,6 +8,8 @@ import { IntegrationsActivity } from '@gitroom/orchestrator/activities/integrati
import { VideoActivity } from '@gitroom/orchestrator/activities/video.activity';
import { MediaActivity } from '@gitroom/orchestrator/activities/media.activity';
import { ClippingActivity } from '@gitroom/orchestrator/activities/clipping.activity';
import { PostEngagementActivity } from '@gitroom/orchestrator/activities/post.engagement.activity';
import { EvergreenActivity } from '@gitroom/orchestrator/activities/evergreen.activity';
import { VideoModule } from '@gitroom/nestjs-libraries/videos/video.module';
import { HealthController } from '@gitroom/orchestrator/health.controller';
@ -19,6 +21,8 @@ const activities = [
VideoActivity,
MediaActivity,
ClippingActivity,
PostEngagementActivity,
EvergreenActivity,
];
@Module({
imports: [

View File

@ -0,0 +1,38 @@
import { continueAsNew, proxyActivities, sleep, workflowInfo } from '@temporalio/workflow';
import { PostEngagementActivity } from '@gitroom/orchestrator/activities/post.engagement.activity';
// captureEngagementSnapshotBatch processes its candidates sequentially and
// some providers (e.g. LinkedIn - see refreshWait) force a blocking 10s wait
// per token refresh inside checkPostAnalytics, so a full batch (see
// PostEngagementService's batch cap) can legitimately take well over an
// hour. The timeout below is sized for that worst case, not the common case.
const { captureEngagementSnapshotBatch } =
proxyActivities<PostEngagementActivity>({
startToCloseTimeout: '2 hours',
retry: {
maximumAttempts: 3,
backoffCoefficient: 1,
initialInterval: '2 minutes',
},
});
// Daily batch job powering "best time to post" suggestions. Each run
// captures at most PostEngagementService's batch cap worth of post
// analytics (bounded, see captureBatch) instead of calling providers live
// per request. New workflow (no running history on main to preserve), so no
// `patched()` compatibility gate is needed like missingPostWorkflow has.
export async function bestTimeToPostWorkflow() {
let loops = 0;
await captureEngagementSnapshotBatch();
while (true) {
await sleep('24 hours');
// Keep the history small; continueAsNew runs the batch immediately on
// restart so the daily cadence is kept.
if (++loops >= 14 || workflowInfo().historyLength > 1000) {
return await continueAsNew<typeof bestTimeToPostWorkflow>();
}
await captureEngagementSnapshotBatch();
}
}

View File

@ -0,0 +1,34 @@
import { continueAsNew, proxyActivities, sleep, workflowInfo } from '@temporalio/workflow';
import { EvergreenActivity } from '@gitroom/orchestrator/activities/evergreen.activity';
// recycleDueBatch creates at most BATCH_CAP new posts per call (see
// EvergreenService), each going through the same publish-workflow start as
// a normal create - sized generously, not for the common case.
const { recycleDueBatch } = proxyActivities<EvergreenActivity>({
startToCloseTimeout: '30 minutes',
retry: {
maximumAttempts: 3,
backoffCoefficient: 1,
initialInterval: '2 minutes',
},
});
// Daily batch job powering evergreen content recycling (Organization ->
// EvergreenRecycle). Modeled on bestTimeToPostWorkflow's infinite-loop
// pattern. New workflow (no running history on main to preserve), so no
// `patched()` compatibility gate is needed.
export async function evergreenRecycleWorkflow() {
let loops = 0;
await recycleDueBatch();
while (true) {
await sleep('24 hours');
// Keep the history small; continueAsNew runs the batch immediately on
// restart so the daily cadence is kept.
if (++loops >= 14 || workflowInfo().historyLength > 1000) {
return await continueAsNew<typeof evergreenRecycleWorkflow>();
}
await recycleDueBatch();
}
}

View File

@ -10,9 +10,12 @@ export * from './post-workflows/post.workflow.v1.0.9';
export * from './post-workflows/post.workflow.v1.1.0';
export * from './post-workflows/post.workflow.v1.1.1';
export * from './post-workflows/post.workflow.v1.1.2';
export * from './post-workflows/post.workflow.v1.1.3';
export * from './autopost.workflow';
export * from './digest.email.workflow';
export * from './missing.post.workflow';
export * from './best.time.to.post.workflow';
export * from './evergreen.recycle.workflow';
export * from './send.email.workflow';
export * from './refresh.token.workflow';
export * from './streak.workflow';

View File

@ -0,0 +1,738 @@
import { PostActivity } from '@gitroom/orchestrator/activities/post.activity';
import {
ActivityFailure,
ApplicationFailure,
startChild,
proxyActivities,
sleep,
defineSignal,
setHandler,
} from '@temporalio/workflow';
import dayjs from 'dayjs';
import { Integration } from '@prisma/client';
import { capitalize, sortBy } from 'lodash';
import { PostResponse } from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
import {
TimeoutFailure,
TimeoutType,
TypedSearchAttributes,
} from '@temporalio/common';
import { postId as postIdSearchParam } from '@gitroom/nestjs-libraries/temporal/temporal.search.attribute';
// The publishing activities heartbeat every 15s (withHeartbeat sends its first
// heartbeat at the first interval tick, not at entry), so a heartbeat timeout
// whose failure carries no heartbeat details means the server never received
// one: the worker never ran the activity, or it died within its first seconds.
const HEARTBEAT_TIMEOUT = 3 * 60 * 1000;
const proxyTaskQueue = (taskQueue: string) => {
return proxyActivities<PostActivity>({
startToCloseTimeout: '10 minute',
taskQueue,
retry: {
maximumAttempts: 3,
backoffCoefficient: 1,
initialInterval: '2 minutes',
},
});
};
// postComment publishes through providers that can legitimately run long
// (media conversion + upload), so it gets a large time budget. The
// heartbeatTimeout exists to detect an activity that was never started: the
// activity heartbeats every 15s, so no heartbeat at all means the worker never
// ran it and nothing was published. No SDK retries: an
// automatic retry of a heartbeat timeout would run again even when the first
// attempt did publish, duplicating the comment. The workflow decides whether
// a failure is safe to retry (see handleActivityError).
const proxyCommentTaskQueue = (taskQueue: string) => {
return proxyActivities<PostActivity>({
startToCloseTimeout: '30 minute',
heartbeatTimeout: HEARTBEAT_TIMEOUT,
taskQueue,
retry: {
maximumAttempts: 1,
},
});
};
// checkPostStatus is a single read-only status call, so it gets a short timeout
// and fast retries - retrying it can never duplicate a post.
const proxyCheckTaskQueue = (taskQueue: string) => {
return proxyActivities<PostActivity>({
startToCloseTimeout: '2 minute',
taskQueue,
retry: {
maximumAttempts: 3,
backoffCoefficient: 1,
initialInterval: '10 seconds',
},
});
};
// postSocialPending / finalizePost run irreversible publishing mutations, so no
// automatic retries - a retried activity whose previous (timed-out) attempt
// still completed in the background would publish twice. The workflow retries
// deliberately, and treats timeouts as "outcome unknown".
// The heartbeatTimeout exists to detect an activity that was never started:
// both activities heartbeat every 15s, so no heartbeat at all means the
// worker never ran them and nothing was published. The workflow
// decides whether that is safe to retry (see handleActivityError); every
// other timeout still marks the post as unconfirmed.
const proxyMutationTaskQueue = (taskQueue: string) => {
return proxyActivities<PostActivity>({
startToCloseTimeout: '30 minute',
heartbeatTimeout: HEARTBEAT_TIMEOUT,
taskQueue,
retry: {
maximumAttempts: 1,
},
});
};
const {
getPostsList,
getPost,
inAppNotification,
changeState,
updatePost,
sendWebhooks,
isCommentable,
} = proxyActivities<PostActivity>({
startToCloseTimeout: '10 minute',
retry: {
maximumAttempts: 3,
backoffCoefficient: 1,
initialInterval: '2 minutes',
},
});
const poke = defineSignal('poke');
const iterate = Array.from({ length: 5 });
// ~30 minutes at 20s interval (longer than the old in-activity loop, timers are
// free). Multi-item flows (stories, chunked uploads) consume several checks per
// item, so the budget must cover the largest realistic post, not one poll cycle.
const maxPendingChecks = 90;
export async function postWorkflowV113({
taskQueue,
postId,
organizationId,
postNow = false,
}: {
taskQueue: string;
postId: string;
organizationId: string;
postNow?: boolean;
}) {
// Dynamic task queue, for concurrency
const {
getIntegrationById,
refreshTokenWithCause,
internalPlugs,
globalPlugs,
processInternalPlug,
processPlug,
} = proxyTaskQueue(taskQueue);
const { checkPostStatus } = proxyCheckTaskQueue(taskQueue);
const { postComment } = proxyCommentTaskQueue(taskQueue);
const { postSocialPending, finalizePost } = proxyMutationTaskQueue(taskQueue);
let poked = false;
setHandler(poke, () => {
poked = true;
});
// get all the posts and comments to post
const firstPost = await getPost(organizationId, postId);
// in case doesn't exists for some reason, fail it
if (!firstPost) {
await changeState(postId, 'ERROR', 'No Post');
return;
}
if (!postNow && firstPost.state !== 'QUEUE') {
await changeState(firstPost.id, 'ERROR', 'Already posted', [firstPost]);
return;
}
// wait for the scheduled publish date
if (!postNow) {
await sleep(
dayjs(firstPost.publishDate).isBefore(dayjs())
? 0
: dayjs(firstPost.publishDate).diff(dayjs(), 'millisecond')
);
}
// Captured AFTER the scheduling sleep: the repeat-post delay is
// "interval minus time spent publishing", so it must be measured from the
// publish time, not from when the workflow was started. Measuring from the
// workflow start subtracted the whole scheduling wait from the interval
// (a post scheduled further out than its interval repeated immediately).
const startTime = new Date();
const postsListBefore = await getPostsList(organizationId, postId);
const [post] = postsListBefore;
if (!post) {
await changeState(postId, 'ERROR', 'No Post');
return;
}
// Re-check right after the scheduling sleep, before any provider-facing
// activity: the first QUEUE check above only covers the moment the
// workflow started, but the sleep above can run for as long as the post
// is scheduled out. A post reverted to DRAFT, deleted, or otherwise moved
// out of QUEUE during that wait must not still reach the provider (#2275).
if (!postNow && post.state !== 'QUEUE') {
await changeState(post.id, 'ERROR', 'Already posted', postsListBefore);
return;
}
// if refresh is needed from last time, let's inform the user
if (post.integration?.refreshNeeded) {
await inAppNotification(
post.organizationId,
`We couldn't post to ${post.integration?.providerIdentifier} for ${post?.integration?.name}`,
`We couldn't post to ${post.integration?.providerIdentifier} for ${post?.integration?.name} because you need to reconnect it. Please enable it and try again.`,
true,
false,
'info'
);
await changeState(
postsListBefore[0].id,
'ERROR',
'Refresh channel needed',
postsListBefore
);
return;
}
// if it's disabled, inform the user
if (post.integration?.disabled) {
await inAppNotification(
post.organizationId,
`We couldn't post to ${post.integration?.providerIdentifier} for ${post?.integration?.name}`,
`We couldn't post to ${post.integration?.providerIdentifier} for ${post?.integration?.name} because it's disabled. Please enable it and try again.`,
true,
false,
'info'
);
await changeState(
postsListBefore[0].id,
'ERROR',
'Channel disabled',
postsListBefore
);
return;
}
// Do we need to post comment for this social?
const toComment: boolean =
postsListBefore.length === 1
? false
: await isCommentable(post.integration);
const postsList = toComment ? postsListBefore : [postsListBefore[0]];
// list of all the saved results
const postsResults: PostResponse[] = [];
// Every catch block below used to repeat the same failure classification, so
// it is centralized here: detect the failure type, refresh the token when
// needed, and tell the caller what to do.
// 'retry' - the token was refreshed, or the activity never started (heartbeat
// timeout with no heartbeat), run the action again
// 'stop' - the token could not be refreshed
// 'bad-body' - the platform rejected the action
// 'timeout' - the activity timed out, its outcome is unknown
// 'unknown' - anything else (transient errors)
const handleActivityError = async (
err: unknown,
getIntegration?: () => Promise<any>,
heartbeats?: boolean
): Promise<{
type: 'retry' | 'stop' | 'bad-body' | 'timeout' | 'unknown';
message: string;
}> => {
if (
err instanceof ActivityFailure &&
err.cause instanceof TimeoutFailure
) {
// The server copies the last heartbeat details it received into the
// timeout failure. None at all (undefined) means it never received a
// heartbeat: the worker never ran the activity, so nothing was published
// and it is safe to run again. Any details mean the activity ran and
// then stalled, so its outcome is unknown. This relies on withHeartbeat
// always sending a non-empty string ("<activityType>: entered" at least):
// a heartbeat sent with undefined details also leaves the failure
// without details. Only the callers of heartbeating activities opt in;
// no time window, so activity dispatch delay cannot skew the decision.
if (
heartbeats &&
err.cause.timeoutType === TimeoutType.HEARTBEAT &&
!err.cause.lastHeartbeatDetails
) {
return { type: 'retry', message: '' };
}
return { type: 'timeout', message: '' };
}
const cause =
err instanceof ActivityFailure && err.cause instanceof ApplicationFailure
? err.cause
: undefined;
if (cause?.type === 'refresh_token') {
const refresh = await refreshTokenWithCause(
getIntegration ? await getIntegration() : post.integration,
cause.message || ''
);
if (!refresh || !refresh.accessToken) {
return { type: 'stop', message: cause.message || '' };
}
if (!getIntegration) {
post.integration.token = refresh.accessToken;
}
return { type: 'retry', message: cause.message || '' };
}
if (cause?.type === 'bad_body') {
return { type: 'bad-body', message: cause.message || '' };
}
return { type: 'unknown', message: '' };
};
// The platform may have accepted the post but we can't confirm it was
// published - mark the error with a distinct message so the user checks the
// account before reposting manually and duplicating it.
const markUnconfirmed = async (err: any) => {
await changeState(postsList[0].id, 'ERROR', err, postsList);
await inAppNotification(
post.organizationId,
`We couldn't confirm your post on ${capitalize(
post.integration?.providerIdentifier
)}`,
`Your post was sent to ${capitalize(
post.integration?.providerIdentifier
)}, but we couldn't confirm it was published. Please check your ${
post?.integration?.name
} account before posting again to avoid duplicates.`,
true,
false,
'fail'
);
};
// The post/comment was already accepted by the platform but returned as
// "pending": poll the read-only status check with durable timers until it
// completes. Errors are fully handled here (never rethrown), otherwise they
// would bubble to the posting retry loop and re-run the publish.
const resolvePending = async (
pending: PostResponse
): Promise<PostResponse | false> => {
let pendingData = pending.pendingData;
let errorAttempts = 0;
let heartbeats = false;
for (let check = 0; check < maxPendingChecks; check++) {
// only finalizePost heartbeats, so a checkPostStatus failure must never
// be classified as never started
heartbeats = false;
try {
let result = await checkPostStatus(post.integration, pendingData);
// commit the check's state BEFORE finalizePost runs: if finalize dies
// mid-mutation, the next check must see what it had already authorized,
// so providers can detect the interrupted attempt instead of running
// the mutation again
if (result.status !== 'completed') {
pendingData = result.pendingData;
}
// polling is done, run the remaining provider mutations
if (result.status === 'ready') {
heartbeats = true;
result = await finalizePost(post.integration, result.pendingData);
}
if (result.status === 'completed') {
return {
id: pending.id,
postId: result.postId,
releaseURL: result.releaseURL,
status: 'success',
};
}
pendingData = result.pendingData;
// a fully successful iteration proves the platform is reachable: the
// error budget bounds consecutive failures, not blips accumulated over
// a long upload
errorAttempts = 0;
} catch (err) {
const handle = await handleActivityError(err, undefined, heartbeats);
// token refreshed, or finalize never started, check again right away
if (handle.type === 'retry') {
continue;
}
// the token could not be refreshed while checking, but the platform
// already accepted the post - warn about a possible live post
if (handle.type === 'stop') {
await markUnconfirmed(err);
return false;
}
// the platform explicitly failed the post, it was not published
if (handle.type === 'bad-body') {
await changeState(postsList[0].id, 'ERROR', err, postsList);
await inAppNotification(
post.organizationId,
`Error posting on ${post.integration?.providerIdentifier} for ${post?.integration?.name}`,
`An error occurred while posting on ${
post.integration?.providerIdentifier
}${handle.message ? `: ${handle.message}` : ``}`,
true,
false,
'fail'
);
return false;
}
// unknown error on a read-only check, retry a few more times
errorAttempts++;
if (errorAttempts >= iterate.length) {
break;
}
}
// the platform is still processing, wait before the next check
await sleep('20 seconds');
}
// no verdict from the platform after all the checks
await markUnconfirmed('Could not confirm the post status');
return false;
};
// iterate over the posts
for (let i = 0; i < postsList.length; i++) {
const before = postsResults.length;
// once the platform accepted the post, the catch below must never retry
// the publish - retrying after updatePost / notification errors would
// duplicate the post
let posted = false;
let updated = false;
// this is a small trick to repeat an action in case of token refresh
for (const _ of iterate) {
// both publish calls run heartbeating activities, but the timed-out
// status checks below must never be mistaken for never-started
let heartbeats = false;
try {
// first post the main post
if (i === 0) {
heartbeats = true;
postsResults.push(
...(await postSocialPending(post.integration as Integration, [
postsList[i],
]))
);
// then post the comments if any
} else {
if (postsList[i].delay) {
await sleep(60000 * Math.max(0, Number(postsList[i].delay ?? 0)));
}
heartbeats = true;
postsResults.push(
...(await postComment(
postsResults[0].postId,
postsResults.length === 1
? undefined
: postsResults[i - 1].postId,
post.integration,
[postsList[i]]
))
);
}
posted = true;
// the platform accepted the post but is still processing it: resolve
// it here before marking anything, resolvePending handles its own
// errors so a failed status check can never re-run the publish above
if (postsResults[i].status === 'pending') {
let resolved: PostResponse | false = false;
try {
resolved = await resolvePending(postsResults[i]);
} catch (err) {
// never let a pending-resolution error reach the outer catch, it
// would retry the post and duplicate it. Best-effort error state,
// otherwise the post stays in QUEUE and the missing-posts sweep
// would re-publish it.
try {
await markUnconfirmed(err);
} catch (e) {
/**empty**/
}
resolved = false;
}
if (!resolved) {
return false;
}
postsResults[i] = resolved;
}
// mark post as successful
await updatePost(
postsList[i].id,
postsResults[i].postId,
postsResults[i].releaseURL
);
updated = true;
if (i === 0) {
// send notification on a sucessful post
await inAppNotification(
post.integration.organizationId,
`Your post has been published on ${capitalize(
post.integration.providerIdentifier
)}`,
`Your post has been published on ${capitalize(
post.integration.providerIdentifier
)} at ${postsResults[0].releaseURL}`,
true,
true
);
}
// break the current while to move to the next post
break;
} catch (err) {
// the post is already live: never re-run the publish
if (posted) {
if (!updated) {
// still marked QUEUE, record the error so the missing-posts sweep
// doesn't re-publish it
try {
await markUnconfirmed(err);
} catch (e) {
/**empty**/
}
return false;
}
// already marked published, a failed notification shouldn't abort
// the rest of the flow
break;
}
const handle = await handleActivityError(err, undefined, heartbeats);
// token refreshed, or the publish never started, repeat the action
if (handle.type === 'retry') {
continue;
}
// the activity timed out: the platform may still complete the publish
// in the background, so never retry it
if (handle.type === 'timeout') {
try {
await markUnconfirmed(err);
} catch (e) {
/**empty**/
}
return false;
}
// for other errors, change state and inform the user if needed
await changeState(postsList[0].id, 'ERROR', err, postsList);
if (handle.type === 'stop') {
return false;
}
// specific case for bad body errors
if (handle.type === 'bad-body') {
await inAppNotification(
post.organizationId,
`Error posting${i === 0 ? ' ' : ' comments '}on ${
post.integration?.providerIdentifier
} for ${post?.integration?.name}`,
`An error occurred while posting${i === 0 ? ' ' : ' comments '}on ${
post.integration?.providerIdentifier
}${handle.message ? `: ${handle.message}` : ``}`,
true,
false,
'fail'
);
return false;
}
}
}
if (postsResults.length === before) {
// all retries exhausted without success: record it, otherwise the post
// stays in QUEUE with no error and the missing-posts sweep re-publishes
// it. A retried publish may have run without reporting, so treat the
// outcome as unknown.
try {
await markUnconfirmed('Could not publish after several attempts');
} catch (e) {
/**empty**/
}
return false;
}
}
// send webhooks for the post
await sendWebhooks(
postsResults[0].postId,
post.organizationId,
post.integration.id
);
// load internal plugs like repost by other users
const internalPlugsList = await internalPlugs(
post.integration,
JSON.parse(post.settings)
);
// load global plugs, like repost a post if it gets to a certain number of likes
const globalPlugsList = (await globalPlugs(post.integration)).reduce(
(all, current) => {
for (let i = 1; i <= current.totalRuns; i++) {
all.push({
...current,
delay: current.delay * i,
});
}
return all;
},
[]
);
// Check if the post is repeatable
const repeatPost = !post.intervalInDays
? []
: [
{
type: 'repeat-post',
delay:
post.intervalInDays * 24 * 60 * 60 * 1000 -
(new Date().getTime() - startTime.getTime()),
},
];
// Sort all the actions by delay, so we can process them in order
const list = sortBy(
[...internalPlugsList, ...globalPlugsList, ...repeatPost],
'delay'
);
// process all the plugs in order, we are using while because in some cases we need to remove items from the list
while (list.length > 0) {
// get the next to process
const todo = list.shift();
// wait for the delay
await sleep(Math.max(0, Number(todo.delay ?? 0)));
// process internal plug
if (todo.type === 'internal-plug') {
for (const _ of iterate) {
try {
await processInternalPlug({ ...todo, post: postsResults[0].postId });
} catch (err) {
const handle = await handleActivityError(err, () =>
getIntegrationById(organizationId, todo.integration)
);
if (handle.type === 'stop' || handle.type === 'bad-body') {
break;
}
continue;
}
break;
}
}
// process global plug
if (todo.type === 'global') {
for (const _ of iterate) {
try {
const process = await processPlug({
...todo,
postId: postsResults[0].postId,
});
if (process) {
const toDelete = list
.reduce((all, current, index) => {
if (current.plugId === todo.plugId) {
all.push(index);
}
return all;
}, [])
.reverse();
for (const index of toDelete) {
list.splice(index, 1);
}
}
} catch (err) {
const handle = await handleActivityError(err);
if (handle.type === 'stop' || handle.type === 'bad-body') {
break;
}
continue;
}
break;
}
}
// process repeat post in a new workflow, this is important so the other plugs can keep running
if (todo.type === 'repeat-post') {
await startChild(postWorkflowV113, {
parentClosePolicy: 'ABANDON',
args: [
{
taskQueue,
postId,
organizationId,
postNow: true,
},
],
workflowId: `post_${post.id}_${makeId(10)}`,
typedSearchAttributes: new TypedSearchAttributes([
{
key: postIdSearchParam,
value: postId,
},
]),
});
}
}
}

44
jest.standalone.config.js Normal file
View File

@ -0,0 +1,44 @@
// Minimal, self-contained Jest config for the pure-logic unit tests added
// alongside the bulk-schedule and provider-capability work. The repo's
// top-level `pnpm test` goes through `@nx/jest`'s `getJestProjects()`,
// which isn't wired up in this workspace (no nx.json, no per-project jest
// configs), so it can't discover anything. This config targets only the
// `*.standalone.spec.ts` files next to the code they cover and runs with
// plain ts-jest, independent of that broken wiring.
//
// Run with: pnpm exec jest --config jest.standalone.config.js
module.exports = {
displayName: 'standalone',
testEnvironment: 'node',
rootDir: __dirname,
testMatch: ['<rootDir>/**/*.standalone.spec.ts'],
testPathIgnorePatterns: ['<rootDir>/node_modules/'],
transform: {
'^.+\\.tsx?$': [
'ts-jest',
{
tsconfig: {
experimentalDecorators: true,
emitDecoratorMetadata: true,
module: 'commonjs',
target: 'es2020',
esModuleInterop: true,
skipLibCheck: true,
strict: false,
jsx: 'react-jsx',
},
},
],
},
moduleNameMapper: {
'^@gitroom/backend/(.*)$': '<rootDir>/apps/backend/src/$1',
'^@gitroom/frontend/(.*)$': '<rootDir>/apps/frontend/src/$1',
'^@gitroom/helpers/(.*)$': '<rootDir>/libraries/helpers/src/$1',
'^@gitroom/nestjs-libraries/(.*)$':
'<rootDir>/libraries/nestjs-libraries/src/$1',
'^@gitroom/react/(.*)$': '<rootDir>/libraries/react-shared-libraries/src/$1',
'^@gitroom/plugins/(.*)$': '<rootDir>/libraries/plugins/src/$1',
'^@gitroom/orchestrator/(.*)$': '<rootDir>/apps/orchestrator/src/$1',
'^@gitroom/extension/(.*)$': '<rootDir>/apps/extension/src/$1',
},
};

View File

@ -44,7 +44,13 @@ export const countLength = (integrationType: string, text: string): number => {
}
if (integrationType === 'threads') {
return new TextEncoder().encode(text).length;
// Threads counts Unicode codepoints, not UTF-8 bytes or UTF-16 code
// units. TextEncoder().encode(text).length counted bytes (e.g. 2-4 per
// non-ASCII character), and a plain text.length over-counts characters
// outside the BMP (emoji, some CJK) because they are UTF-16 surrogate
// pairs. Array.from splits on codepoints, so each character - ASCII,
// accented, CJK or emoji - counts once.
return Array.from(text).length;
}
return text.length;

View File

@ -7,6 +7,26 @@ export interface Params {
response: Response
) => Promise<boolean>;
}
// Reads a cookie by its exact name, not by substring match.
// `document.cookie.split(';').find((p) => p.includes('auth='))` used to match
// ANY cookie whose string contains "auth=" (e.g. a `_pin_unauth` cookie set by
// another app on the same parent domain), which could log the user straight
// back out. Matching requires the trimmed cookie to start with `${name}=`.
const getCookieValue = (name: string): string | null => {
if (typeof document === 'undefined') {
return null;
}
const prefix = `${name}=`;
const match = document.cookie
.split(';')
.map((part) => part.trim())
.find((part) => part.startsWith(prefix));
return match ? match.slice(prefix.length) : null;
};
export const customFetch = (
params: Params,
auth?: string,
@ -19,29 +39,11 @@ export const customFetch = (
? undefined
: new URL(window.location.href).searchParams.get('loggedAuth');
const newRequestObject = await params?.beforeRequest?.(url, options);
const authNonSecuredCookie =
typeof document === 'undefined'
? null
: document.cookie
.split(';')
.find((p) => p.includes('auth='))
?.split('=')[1];
const authNonSecuredCookie = getCookieValue('auth');
const authNonSecuredOrg =
typeof document === 'undefined'
? null
: document.cookie
.split(';')
.find((p) => p.includes('showorg='))
?.split('=')[1];
const authNonSecuredOrg = getCookieValue('showorg');
const authNonSecuredImpersonate =
typeof document === 'undefined'
? null
: document.cookie
.split(';')
.find((p) => p.includes('impersonate='))
?.split('=')[1];
const authNonSecuredImpersonate = getCookieValue('impersonate');
const fetchRequest = await fetch(params.baseUrl + url, {
...(secured ? { credentials: 'include' } : {}),

View File

@ -26,6 +26,7 @@ const POST_ITEM_KEYS: Record<string, string> = {
intervalInDays: 'iv',
actualDate: 'ad',
creationMethod: 'cm',
pendingApproval: 'pa',
};
const INTEGRATION_KEYS: Record<string, string> = {

View File

@ -1,4 +1,5 @@
import {
ExposeThirdPartyFunction,
ThirdParty,
ThirdPartyAbstract,
} from '@gitroom/nestjs-libraries/3rdparties/thirdparty.interface';
@ -47,12 +48,14 @@ export class HeygenProvider extends ThirdPartyAbstract<{
};
}
@ExposeThirdPartyFunction('Generate a voice-over clip from text')
async generateVoice(apiKey: string, data: { text: string }) {
return {
voice: await this._openaiService.generateVoiceFromText(data.text),
};
}
@ExposeThirdPartyFunction('List available HeyGen voices')
async voices(apiKey: string) {
const {
data: { voices },
@ -69,6 +72,7 @@ export class HeygenProvider extends ThirdPartyAbstract<{
return voices.slice(0, 20);
}
@ExposeThirdPartyFunction('List available HeyGen avatars')
async avatars(apiKey: string) {
const {
data: { avatar_group_list },

View File

@ -1,4 +1,5 @@
import {
ExposeThirdPartyFunction,
ThirdParty,
ThirdPartyAbstract,
} from '@gitroom/nestjs-libraries/3rdparties/thirdparty.interface';
@ -34,6 +35,7 @@ export class ReelFarmProvider extends ThirdPartyAbstract {
};
}
@ExposeThirdPartyFunction('List importable media from Reel.Farm')
async listMedia(
apiKey: string,
data?: { page?: number }

View File

@ -25,6 +25,40 @@ export interface ThirdPartyParams {
installUrl?: () => string | undefined;
}
// Marks a provider method as safe to invoke by name from the generic
// `/third-party/function/:id/:functionName` dispatch endpoint. Mirrors
// `ExposeVideoFunction` in video.interface.ts - without this allowlist,
// that endpoint would let any authenticated org member invoke ANY method
// found on the provider instance (checkConnection, sendData, or any future
// internal helper) just by naming it in the URL.
export function ExposeThirdPartyFunction(description?: string) {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
Reflect.defineMetadata(
'third-party-function',
description || 'true',
descriptor.value
);
};
}
// Returns false only for methods explicitly marked with
// @ExposeThirdPartyFunction - same allowlist shape as
// VideoManager#checkAvailableVideoFunction. Callers must treat `true`
// (not found, not a function, or not marked) as "reject the call". Kept as
// a standalone function (not a class method) so it can be unit-tested
// without pulling in ThirdPartyManager's full Nest DI chain.
export function checkAvailableThirdPartyFunction(method: any) {
const thirdPartyFunction = Reflect.getMetadata(
'third-party-function',
method
);
return !thirdPartyFunction;
}
export function ThirdParty(params: ThirdPartyParams) {
return function (target: any) {
// Apply @Injectable decorator to the target class

View File

@ -0,0 +1,67 @@
import 'reflect-metadata';
import {
checkAvailableThirdPartyFunction,
ExposeThirdPartyFunction,
} from './thirdparty.interface';
// The `/third-party/function/:id/:functionName` endpoint dispatches by a
// URL-supplied method name onto a provider instance. Without an allowlist,
// any authenticated org member could invoke ANY method found on that
// instance (checkConnection, sendData, or a future internal helper) just by
// naming it in the URL - not just the handful of methods the frontend
// actually calls (generateVoice/voices/avatars/listMedia). This mirrors the
// allowlist VideoManager already enforces for its own name-dispatched
// video functions. Tested as the standalone function (not through
// ThirdPartyManager) so this doesn't pull in the real Nest DI chain
// (ThirdPartyService -> ... -> AuthService -> bcrypt's native binding),
// which isn't available in this sandbox - same reasoning as the other
// *.standalone.spec.ts files in this repo.
describe('checkAvailableThirdPartyFunction', () => {
class FakeProvider {
@ExposeThirdPartyFunction('an allowed tool')
exposedMethod() {
return 'exposed';
}
notExposedMethod() {
return 'should never be reachable from the URL';
}
async checkConnection() {
return false as const;
}
async sendData() {
return 'sent';
}
}
const instance = new FakeProvider();
it('allows a method explicitly marked with @ExposeThirdPartyFunction', () => {
expect(
checkAvailableThirdPartyFunction(instance.exposedMethod)
).toBe(false);
});
it('rejects a method that exists but was never exposed', () => {
expect(
checkAvailableThirdPartyFunction(instance.notExposedMethod)
).toBe(true);
});
it('rejects checkConnection/sendData - internal lifecycle methods, never meant for URL dispatch', () => {
expect(
checkAvailableThirdPartyFunction(instance.checkConnection)
).toBe(true);
expect(
checkAvailableThirdPartyFunction(instance.sendData)
).toBe(true);
});
it('rejects an arbitrary inherited/unrelated method such as toString', () => {
expect(
checkAvailableThirdPartyFunction(instance.toString)
).toBe(true);
});
});

View File

@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
import {
checkAvailableThirdPartyFunction,
ThirdPartyAbstract,
ThirdPartyParams,
} from '@gitroom/nestjs-libraries/3rdparties/thirdparty.interface';
@ -35,6 +36,12 @@ export class ThirdPartyManager {
return { ...thirdParty, instance: this._moduleRef.get(thirdParty.target) };
}
// See checkAvailableThirdPartyFunction in thirdparty.interface.ts for the
// allowlist this enforces.
checkAvailableThirdPartyFunction(method: any) {
return checkAvailableThirdPartyFunction(method);
}
deleteIntegration(org: string, id: string) {
return this._thirdPartyService.deleteIntegration(org, id);
}

View File

@ -50,6 +50,10 @@ import { ErrorsRepository } from '@gitroom/nestjs-libraries/database/prisma/erro
import { ErrorsService } from '@gitroom/nestjs-libraries/database/prisma/errors/errors.service';
import { AdminStatsRepository } from '@gitroom/nestjs-libraries/database/prisma/admin-stats/admin-stats.repository';
import { AdminStatsService } from '@gitroom/nestjs-libraries/database/prisma/admin-stats/admin-stats.service';
import { PostEngagementRepository } from '@gitroom/nestjs-libraries/database/prisma/post-engagement/post-engagement.repository';
import { PostEngagementService } from '@gitroom/nestjs-libraries/database/prisma/post-engagement/post-engagement.service';
import { EvergreenRepository } from '@gitroom/nestjs-libraries/database/prisma/evergreen/evergreen.repository';
import { EvergreenService } from '@gitroom/nestjs-libraries/database/prisma/evergreen/evergreen.service';
@Global()
@Module({
@ -109,6 +113,10 @@ import { AdminStatsService } from '@gitroom/nestjs-libraries/database/prisma/adm
ErrorsService,
AdminStatsRepository,
AdminStatsService,
PostEngagementRepository,
PostEngagementService,
EvergreenRepository,
EvergreenService,
],
get exports() {
return this.providers;

View File

@ -0,0 +1,125 @@
import { PrismaRepository } from '@gitroom/nestjs-libraries/database/prisma/prisma.service';
import { Injectable } from '@nestjs/common';
export interface DueEvergreenRecycle {
id: string;
organizationId: string;
postId: string;
intervalDays: number;
maxRecycles: number | null;
totalRecycles: number;
}
@Injectable()
export class EvergreenRepository {
constructor(
private _evergreenRecycle: PrismaRepository<'evergreenRecycle'>
) {}
create(
organizationId: string,
postId: string,
intervalDays: number,
maxRecycles: number | null,
nextRecycleAt: Date
) {
return this._evergreenRecycle.model.evergreenRecycle.create({
data: {
organizationId,
postId,
intervalDays,
maxRecycles,
nextRecycleAt,
},
});
}
getForPost(organizationId: string, postId: string) {
return this._evergreenRecycle.model.evergreenRecycle.findMany({
where: {
organizationId,
postId,
deletedAt: null,
},
orderBy: { createdAt: 'desc' },
});
}
getById(organizationId: string, id: string) {
return this._evergreenRecycle.model.evergreenRecycle.findFirst({
where: {
id,
organizationId,
deletedAt: null,
},
});
}
setActive(id: string, active: boolean) {
return this._evergreenRecycle.model.evergreenRecycle.update({
where: { id },
data: { active },
});
}
delete(id: string) {
return this._evergreenRecycle.model.evergreenRecycle.update({
where: { id },
data: { deletedAt: new Date(), active: false },
});
}
// Bounded by `limit` (the batch job's hard cap on new posts created per
// run, same reasoning as PostEngagementRepository.findSnapshotCandidates).
// Oldest-due-first so a backlog drains in FIFO order.
findDue(limit: number, now: Date): Promise<DueEvergreenRecycle[]> {
return this._evergreenRecycle.model.evergreenRecycle.findMany({
where: {
active: true,
deletedAt: null,
nextRecycleAt: { lte: now },
},
orderBy: { nextRecycleAt: 'asc' },
take: limit,
select: {
id: true,
organizationId: true,
postId: true,
intervalDays: true,
maxRecycles: true,
totalRecycles: true,
},
});
}
// Advances the schedule after a successful recycle. Deactivates once
// maxRecycles is hit so findDue naturally stops returning it (no separate
// "is this entry exhausted" check needed anywhere else).
markRecycled(
id: string,
nextRecycleAt: Date,
totalRecycles: number,
active: boolean
) {
return this._evergreenRecycle.model.evergreenRecycle.update({
where: { id },
data: {
lastRecycledAt: new Date(),
nextRecycleAt,
totalRecycles,
active,
},
});
}
// A run that failed to create the new post (provider/validation error)
// is pushed one interval out instead of retried immediately next run -
// same "don't hot-loop a broken entry" reasoning as the publish retry
// paths elsewhere, without burning through maxRecycles.
pushBack(id: string, nextRecycleAt: Date) {
return this._evergreenRecycle.model.evergreenRecycle.update({
where: { id },
data: { nextRecycleAt },
});
}
}

View File

@ -0,0 +1,176 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import dayjs from 'dayjs';
import { CreationMethod } from '@prisma/client';
import {
EvergreenRepository,
DueEvergreenRecycle,
} from '@gitroom/nestjs-libraries/database/prisma/evergreen/evergreen.repository';
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
import { CreatePostDto } from '@gitroom/nestjs-libraries/dtos/posts/create.post.dto';
import { CreateEvergreenRecycleDto } from '@gitroom/nestjs-libraries/dtos/posts/evergreen.recycle.dto';
// Hard cap on how many posts get created per daily batch run - same
// reasoning as PostEngagementService's getBatchCap: bound the background
// job's write volume regardless of backlog size.
const BATCH_CAP = 25;
export interface RecycleBatchResult {
attempted: number;
recycled: number;
failed: number;
}
@Injectable()
export class EvergreenService {
constructor(
private _evergreenRepository: EvergreenRepository,
private _postsService: PostsService
) {}
async createRecycle(
orgId: string,
postId: string,
dto: CreateEvergreenRecycleDto
) {
const post = await this._postsService.getPostById(postId, orgId);
if (!post) {
throw new NotFoundException('Post not found');
}
if (post.state !== 'PUBLISHED') {
throw new BadRequestException(
'Only already-published posts can be set up for evergreen recycling'
);
}
const nextRecycleAt = dayjs().add(dto.intervalDays, 'day').toDate();
return this._evergreenRepository.create(
orgId,
postId,
dto.intervalDays,
dto.maxRecycles ?? null,
nextRecycleAt
);
}
listForPost(orgId: string, postId: string) {
return this._evergreenRepository.getForPost(orgId, postId);
}
async setActive(orgId: string, id: string, active: boolean) {
const entry = await this._evergreenRepository.getById(orgId, id);
if (!entry) {
throw new NotFoundException('Evergreen recycle entry not found');
}
return this._evergreenRepository.setActive(id, active);
}
async remove(orgId: string, id: string) {
const entry = await this._evergreenRepository.getById(orgId, id);
if (!entry) {
throw new NotFoundException('Evergreen recycle entry not found');
}
return this._evergreenRepository.delete(id);
}
// Called once per scheduled run by evergreenRecycleWorkflow (daily
// cadence). Bounded: at most BATCH_CAP new posts created per run. A
// per-entry failure never aborts the batch - same "schedule what's valid,
// report the rest" spirit as PostsService.bulkSchedule.
async runDueBatch(): Promise<RecycleBatchResult> {
const due = await this._evergreenRepository.findDue(BATCH_CAP, new Date());
let recycled = 0;
let failed = 0;
for (const entry of due) {
try {
await this.recycleOne(entry);
recycled++;
} catch (err) {
failed++;
// Don't hot-loop a broken entry (bad settings, missing media,
// disabled integration) - push it one interval out and let the
// next run try again, same reasoning as a transient provider
// failure anywhere else in this codebase.
await this._evergreenRepository
.pushBack(
entry.id,
dayjs().add(entry.intervalDays, 'day').toDate()
)
.catch(() => {});
}
}
return { attempted: due.length, recycled, failed };
}
private async recycleOne(entry: DueEvergreenRecycle) {
const post = await this._postsService.getPostById(
entry.postId,
entry.organizationId
);
if (!post) {
// Original was deleted - nothing left to recycle from, stop for good.
await this._evergreenRepository.setActive(entry.id, false);
return;
}
const rawPosts = [
{
integration: { id: post.integrationId },
value: [
{
content: post.content,
image: JSON.parse(post.image || '[]'),
},
],
settings: JSON.parse(post.settings || '{}'),
},
];
const validation = await this._postsService.validatePosts(
entry.organizationId,
rawPosts
);
for (const item of validation) {
if (item.emptyContent || !item.valid || item.errors !== true || item.tooLong) {
throw new Error(
'Original post no longer validates for its provider (settings, length, or content changed upstream)'
);
}
}
const mapped = await this._postsService.mapTypeToPost(
{
type: 'schedule',
shortLink: false,
date: dayjs().format('YYYY-MM-DDTHH:mm:00'),
tags: [],
posts: rawPosts,
} as unknown as CreatePostDto,
entry.organizationId
);
const created = await this._postsService.createPost(
entry.organizationId,
mapped,
CreationMethod.RECYCLE
);
if (!created?.length) {
throw new Error('Could not create the recycled post');
}
const totalRecycles = entry.totalRecycles + 1;
const reachedMax =
entry.maxRecycles != null && totalRecycles >= entry.maxRecycles;
const nextRecycleAt = dayjs().add(entry.intervalDays, 'day').toDate();
await this._evergreenRepository.markRecycled(
entry.id,
nextRecycleAt,
totalRecycles,
!reachedMax
);
}
}

View File

@ -0,0 +1,151 @@
// #2233: reconnecting an existing YouTube (or any OAuth) channel via
// "Add Channel" creates a temporary integration holding the fresh
// refreshToken/tokenExpiration, but saveProviderPage() only forwards
// picture/internalId/name/token/profile to updateIntegration(). The old
// pre-existing record survives the reconnect and the temp record (with the
// only copy of the new refresh token) gets soft-deleted, so the refresh
// token is silently dropped and the channel breaks ~1h later when the
// access token expires. updateIntegration() must carry the temp record's
// refreshToken/tokenExpiration onto the surviving record when the caller
// didn't explicitly provide one.
// Avoid pulling in the real UploadFactory -> CloudflareStorage -> `file-type`
// chain, which is ESM-only and isn't transformable under this repo's
// standalone Jest config. IntegrationRepository only needs `.uploadSimple`
// from it, and this test never sets `picture`, so it's never called.
jest.mock('@gitroom/nestjs-libraries/upload/upload.factory', () => ({
UploadFactory: {
createStorage: () => ({ uploadSimple: jest.fn() }),
},
}));
import { IntegrationRepository } from './integration.repository';
describe('IntegrationRepository.updateIntegration', () => {
function makeRepository(overrides: {
existing: any;
tempRecord: any;
}) {
const findUnique = jest
.fn()
// 1st call: look up the pre-existing record by (org, internalId)
.mockResolvedValueOnce(overrides.existing)
// 2nd call (only made when `existing` is found): fetch the temp
// record's refreshToken/tokenExpiration
.mockResolvedValueOnce(overrides.tempRecord);
const update = jest.fn().mockImplementation(({ data }) => ({ data }));
const updateMany = jest.fn().mockResolvedValue({ count: 0 });
const integrationRepo = {
model: {
integration: { findUnique, update },
},
} as any;
const postsRepo = {
model: { post: { updateMany } },
} as any;
const repository = new IntegrationRepository(
integrationRepo,
postsRepo,
{} as any,
{} as any,
{} as any,
{} as any
);
return { repository, findUnique, update, updateMany };
}
it('carries the refresh token and expiration from the temp record onto the surviving record', async () => {
const tokenExpiration = new Date('2026-10-20T00:00:00.000Z');
const { repository, update } = makeRepository({
existing: { id: 'existing-id' },
tempRecord: {
refreshToken: 'fresh-refresh-token',
tokenExpiration,
},
});
await repository.updateIntegration('temp-id', {
picture: undefined,
internalId: 'channel-123',
organizationId: 'org-1',
name: 'My Channel',
inBetweenSteps: false,
token: 'new-access-token',
profile: 'my-channel',
});
// Final update call is the last one made (after the soft-delete update)
const finalUpdateCall = update.mock.calls[update.mock.calls.length - 1][0];
expect(finalUpdateCall.where).toEqual({ id: 'existing-id' });
expect(finalUpdateCall.data.refreshToken).toBe('fresh-refresh-token');
expect(finalUpdateCall.data.tokenExpiration).toBe(tokenExpiration);
});
it('does not overwrite an explicitly provided refreshToken', async () => {
const { repository, update } = makeRepository({
existing: { id: 'existing-id' },
tempRecord: {
refreshToken: 'fresh-refresh-token',
tokenExpiration: new Date(),
},
});
await repository.updateIntegration('temp-id', {
internalId: 'channel-123',
organizationId: 'org-1',
refreshToken: 'explicitly-passed-token',
});
const finalUpdateCall = update.mock.calls[update.mock.calls.length - 1][0];
expect(finalUpdateCall.data.refreshToken).toBe('explicitly-passed-token');
});
it('does nothing extra for a brand-new channel with no existing record', async () => {
const findUnique = jest.fn().mockResolvedValueOnce(null);
const update = jest.fn().mockImplementation(({ data }) => ({ data }));
const updateMany = jest.fn();
const integrationRepo = {
model: { integration: { findUnique, update } },
} as any;
const postsRepo = { model: { post: { updateMany } } } as any;
const repository = new IntegrationRepository(
integrationRepo,
postsRepo,
{} as any,
{} as any,
{} as any,
{} as any
);
await repository.updateIntegration('temp-id', {
internalId: 'channel-123',
organizationId: 'org-1',
token: 'new-access-token',
});
// Only the single lookup for `existing` - no second lookup for a temp
// record, since there's nothing to carry over.
expect(findUnique).toHaveBeenCalledTimes(1);
expect(updateMany).not.toHaveBeenCalled();
});
it('skips the carry-over when the temp record has no refresh token', async () => {
const { repository, update } = makeRepository({
existing: { id: 'existing-id' },
tempRecord: { refreshToken: null, tokenExpiration: null },
});
await repository.updateIntegration('temp-id', {
internalId: 'channel-123',
organizationId: 'org-1',
});
const finalUpdateCall = update.mock.calls[update.mock.calls.length - 1][0];
expect(finalUpdateCall.data.refreshToken).toBeUndefined();
});
});

View File

@ -181,6 +181,27 @@ export class IntegrationRepository {
},
});
// Reconnecting a channel that's already in the org: the OAuth callback
// created a fresh temporary record (`id`) holding the new
// refreshToken/tokenExpiration, but callers like saveProviderPage()
// only pass picture/internalId/name/token/profile in `params` - not
// the refresh token. Below, the temp record gets soft-deleted and
// `params` is applied to the pre-existing record instead, so without
// this, the new refresh token and expiration are discarded and the
// surviving record keeps whatever (possibly stale/invalid) values it
// had before the reconnect. Carry them over from the temp record so
// reconnecting doesn't quietly break token refresh an hour later.
if (existing && existing.id !== id && params.refreshToken === undefined) {
const temp = await this._integration.model.integration.findUnique({
where: { id },
select: { refreshToken: true, tokenExpiration: true },
});
if (temp?.refreshToken) {
params.refreshToken = temp.refreshToken;
params.tokenExpiration = temp.tokenExpiration;
}
}
if (existing) {
await this._posts.model.post.updateMany({
where: {
@ -445,6 +466,9 @@ export class IntegrationRepository {
updateNameAndUrl(id: string, name: string, url: string) {
return this._integration.model.integration.update({
select: {
id: true,
},
where: {
id,
},
@ -517,6 +541,9 @@ export class IntegrationRepository {
}));
return this._integration.model.integration.update({
select: {
id: true,
},
where: {
id,
organizationId: org,
@ -535,6 +562,9 @@ export class IntegrationRepository {
updateIntegrationGroup(org: string, id: string, group: string) {
return this._integration.model.integration.update({
select: {
id: true,
},
where: {
id,
organizationId: org,

View File

@ -38,6 +38,24 @@ export class NotificationService {
);
}
// In-app only, targeted at one member (mention/assignment pings) - no
// email, unlike inAppNotification above which is org-wide and can send
// one. Failures are swallowed by callers (comment creation must not fail
// because a notification couldn't be written).
notifyUser(
organizationId: string,
userId: string,
content: string,
link?: string
) {
return this._notificationRepository.createUserNotification(
organizationId,
userId,
content,
link
);
}
async inAppNotification(
orgId: string,
subject: string,

View File

@ -28,6 +28,7 @@ export class NotificationsRepository {
total: await this._notifications.model.notifications.count({
where: {
organizationId,
OR: [{ userId: null }, { userId }],
createdAt: {
gt: lastReadNotifications!,
},
@ -45,6 +46,23 @@ export class NotificationsRepository {
});
}
// Targets one member instead of the whole org - see Notifications.userId.
async createUserNotification(
organizationId: string,
userId: string,
content: string,
link?: string
) {
await this._notifications.model.notifications.create({
data: {
organizationId,
userId,
content,
link,
},
});
}
async getNotificationsSince(organizationId: string, since: string) {
return this._notifications.model.notifications.findMany({
where: {
@ -115,6 +133,7 @@ export class NotificationsRepository {
take: 10,
where: {
organizationId,
OR: [{ userId: null }, { userId }],
},
select: {
createdAt: true,

View File

@ -501,6 +501,53 @@ export class OrganizationRepository {
});
}
// Used when registration carries a pending org invite: creates the user
// without also spinning up a brand-new organization for them, so a valid
// invite doesn't leave them stuck as SUPERADMIN of a throwaway org (#2199).
async createUser(
body: Omit<CreateOrgUserDto, 'providerToken'> & { providerId?: string },
hasEmail: boolean,
ip: string,
userAgent: string
) {
return this._user.model.user.create({
data: {
activated: body.provider !== 'LOCAL' || !hasEmail,
email: body.email,
password: body.password ? AuthService.hashPassword(body.password) : '',
providerName: body.provider,
providerId: body.providerId || '',
timezone: 0,
ip,
agent: userAgent,
},
});
}
// Fallback for createUser() above: only used if the invite turned out to
// be unusable by the time registration posts (already redeemed, or the
// inviting org hit its seat limit), so the new account still lands
// somewhere instead of having zero organizations.
async createOrgForExistingUser(userId: string, company: string) {
return this._organization.model.organization.create({
data: {
name: company,
apiKey: AuthService.fixedEncryption(makeSecureId(20)),
allowTrial: true,
isTrailing: true,
users: {
create: {
role: Role.SUPERADMIN,
userId,
},
},
},
select: {
id: true,
},
});
}
getOrgByCustomerId(customerId: string) {
return this._organization.model.organization.findFirst({
where: {
@ -578,6 +625,36 @@ export class OrganizationRepository {
});
}
// Own select (id/name/lastName/email/role) instead of widening getTeam's
// shared one - used by the comment @mention/assignment picker and by the
// internal post-approval flow to resolve/validate target team members.
async getTeamMembersForMentions(orgId: string) {
const members = await this._userOrg.model.userOrganization.findMany({
where: {
organizationId: orgId,
disabled: false,
},
select: {
role: true,
user: {
select: {
id: true,
name: true,
lastName: true,
email: true,
},
},
},
});
return members.map((m) => ({
id: m.user.id,
name: [m.user.name, m.user.lastName].filter(Boolean).join(' ').trim() || m.user.email,
email: m.user.email,
role: m.role,
}));
}
getAllUsersOrgs(orgId: string) {
return this._organization.model.organization.findUnique({
where: {
@ -611,6 +688,16 @@ export class OrganizationRepository {
});
}
countSuperAdmins(orgId: string) {
return this._userOrg.model.userOrganization.count({
where: {
organizationId: orgId,
role: Role.SUPERADMIN,
disabled: false,
},
});
}
async deleteTeamMember(orgId: string, userId: string) {
return this._userOrg.model.userOrganization.delete({
where: {
@ -657,4 +744,32 @@ export class OrganizationRepository {
},
});
}
getApprovalForQueueSetting(orgId: string) {
return this._organization.model.organization.findUnique({
where: {
id: orgId,
},
select: {
requireApprovalForQueue: true,
},
});
}
updateApprovalForQueueSetting(
orgId: string,
requireApprovalForQueue: boolean
) {
return this._organization.model.organization.update({
where: {
id: orgId,
},
data: {
requireApprovalForQueue,
},
select: {
requireApprovalForQueue: true,
},
});
}
}

View File

@ -0,0 +1,96 @@
// DELETE /settings/team/:id -> OrganizationService.deleteTeamMember() 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 delete action when the caller's level is strictly *above* the
// target's (`+myLevel > +getLevel(p.role)`, teams.component.tsx), i.e. 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 it with nobody able to
// manage team/billing. The backend check must be at least as strict as the
// UI: block same-level and self removal too.
const getOrgsByUserId = jest.fn();
const deleteTeamMember = jest.fn();
jest.mock(
'@gitroom/nestjs-libraries/database/prisma/organizations/organization.repository',
() => ({
OrganizationRepository: class {
getOrgsByUserId = getOrgsByUserId;
deleteTeamMember = deleteTeamMember;
},
})
);
jest.mock(
'@gitroom/nestjs-libraries/database/prisma/notifications/notification.service',
() => ({ NotificationService: class {} })
);
jest.mock(
'@gitroom/nestjs-libraries/database/prisma/autopost/autopost.service',
() => ({ AutopostService: class {} })
);
jest.mock('@gitroom/helpers/auth/auth.service', () => ({
AuthService: class {},
}));
import { OrganizationService } from './organization.service';
function makeOrg(myRole: 'USER' | 'ADMIN' | 'SUPERADMIN', orgId = 'org-1') {
return {
id: orgId,
// @ts-ignore matches the `// @ts-ignore` read of org.users[0].role in
// deleteTeamMember()
users: [{ role: myRole }],
} as any;
}
describe('OrganizationService.deleteTeamMember', () => {
let service: OrganizationService;
beforeEach(() => {
jest.clearAllMocks();
service = new OrganizationService({} as any, {} as any);
(service as any)._organizationRepository = {
getOrgsByUserId,
deleteTeamMember,
};
});
it('refuses to let the only SUPERADMIN remove themselves', async () => {
const selfUserId = 'user-superadmin';
getOrgsByUserId.mockResolvedValue([
{ id: 'org-1', users: [{ role: 'SUPERADMIN' }] },
]);
await expect(
service.deleteTeamMember(makeOrg('SUPERADMIN'), selfUserId)
).rejects.toThrow();
expect(deleteTeamMember).not.toHaveBeenCalled();
});
it('refuses to let a SUPERADMIN remove another SUPERADMIN', async () => {
getOrgsByUserId.mockResolvedValue([
{ id: 'org-1', users: [{ role: 'SUPERADMIN' }] },
]);
await expect(
service.deleteTeamMember(makeOrg('SUPERADMIN'), 'other-superadmin')
).rejects.toThrow();
expect(deleteTeamMember).not.toHaveBeenCalled();
});
it('still allows a SUPERADMIN to remove a lower-level member', async () => {
getOrgsByUserId.mockResolvedValue([
{ id: 'org-1', users: [{ role: 'ADMIN' }] },
]);
deleteTeamMember.mockResolvedValue({ id: 'deleted' });
await expect(
service.deleteTeamMember(makeOrg('SUPERADMIN'), 'the-admin')
).resolves.toEqual({ id: 'deleted' });
expect(deleteTeamMember).toHaveBeenCalledWith('org-1', 'the-admin');
});
});

View File

@ -0,0 +1,113 @@
// New feature: self-service "leave organization" (POST /settings/team/leave).
// Before this, the only way for a non-owner team member to get out of an
// org they no longer wanted to be part of was deleting their entire Postiz
// account - deleteTeamMember() never allowed removing yourself (correctly,
// after the fix in the same commit series), and there was no other path.
// leaveOrganization() is the self-service counterpart: it must still block
// the two cases that would break the account -
// 1. leaving your only organization (auth middleware always needs at
// least one non-disabled org to fall back into), and
// 2. leaving as the organization's only Super Admin (nobody left able to
// manage the team or billing) -
// but otherwise let a member remove themselves.
const getOrgsByUserId = jest.fn();
const countSuperAdmins = jest.fn();
const deleteTeamMember = jest.fn();
jest.mock(
'@gitroom/nestjs-libraries/database/prisma/organizations/organization.repository',
() => ({
OrganizationRepository: class {
getOrgsByUserId = getOrgsByUserId;
countSuperAdmins = countSuperAdmins;
deleteTeamMember = deleteTeamMember;
},
})
);
jest.mock(
'@gitroom/nestjs-libraries/database/prisma/notifications/notification.service',
() => ({ NotificationService: class {} })
);
jest.mock(
'@gitroom/nestjs-libraries/database/prisma/autopost/autopost.service',
() => ({ AutopostService: class {} })
);
jest.mock('@gitroom/helpers/auth/auth.service', () => ({
AuthService: class {},
}));
import { OrganizationService } from './organization.service';
const USER = { id: 'user-1' } as any;
const ORG = { id: 'org-1' } as any;
describe('OrganizationService.leaveOrganization', () => {
let service: OrganizationService;
beforeEach(() => {
jest.clearAllMocks();
service = new OrganizationService({} as any, {} as any);
(service as any)._organizationRepository = {
getOrgsByUserId,
countSuperAdmins,
deleteTeamMember,
};
});
it('refuses to leave your only organization', async () => {
getOrgsByUserId.mockResolvedValue([
{ id: 'org-1', users: [{ role: 'ADMIN' }] },
]);
await expect(service.leaveOrganization(USER, ORG)).rejects.toThrow();
expect(deleteTeamMember).not.toHaveBeenCalled();
});
it('refuses to leave as the only Super Admin, even with other orgs', async () => {
getOrgsByUserId.mockResolvedValue([
{ id: 'org-1', users: [{ role: 'SUPERADMIN' }] },
{ id: 'org-2', users: [{ role: 'USER' }] },
]);
countSuperAdmins.mockResolvedValue(1);
await expect(service.leaveOrganization(USER, ORG)).rejects.toThrow();
expect(deleteTeamMember).not.toHaveBeenCalled();
});
it('allows a Super Admin to leave when another Super Admin remains', async () => {
getOrgsByUserId.mockResolvedValue([
{ id: 'org-1', users: [{ role: 'SUPERADMIN' }] },
{ id: 'org-2', users: [{ role: 'USER' }] },
]);
countSuperAdmins.mockResolvedValue(2);
deleteTeamMember.mockResolvedValue({ id: 'left' });
await expect(service.leaveOrganization(USER, ORG)).resolves.toEqual({
id: 'left',
});
expect(deleteTeamMember).toHaveBeenCalledWith('org-1', 'user-1');
});
it('allows a plain member with other orgs to leave without checking Super Admin count', async () => {
getOrgsByUserId.mockResolvedValue([
{ id: 'org-1', users: [{ role: 'USER' }] },
{ id: 'org-2', users: [{ role: 'ADMIN' }] },
]);
deleteTeamMember.mockResolvedValue({ id: 'left' });
await expect(service.leaveOrganization(USER, ORG)).resolves.toEqual({
id: 'left',
});
expect(countSuperAdmins).not.toHaveBeenCalled();
});
it('refuses when the user is not actually part of the organization', async () => {
getOrgsByUserId.mockResolvedValue([
{ id: 'org-2', users: [{ role: 'USER' }] },
{ id: 'org-3', users: [{ role: 'USER' }] },
]);
await expect(service.leaveOrganization(USER, ORG)).rejects.toThrow();
expect(deleteTeamMember).not.toHaveBeenCalled();
});
});

View File

@ -30,6 +30,26 @@ export class OrganizationService {
);
}
async createUser(
body: Omit<CreateOrgUserDto, 'providerToken'> & { providerId?: string },
ip: string,
userAgent: string
) {
return this._organizationRepository.createUser(
body,
this._notificationsService.hasEmailProvider(),
ip,
userAgent
);
}
async createOrgForExistingUser(userId: string, company: string) {
return this._organizationRepository.createOrgForExistingUser(
userId,
company
);
}
async getCount() {
return this._organizationRepository.getCount();
}
@ -88,6 +108,10 @@ export class OrganizationService {
return this._organizationRepository.getTeam(orgId);
}
getTeamMembersForMentions(orgId: string) {
return this._organizationRepository.getTeamMembersForMentions(orgId);
}
async setStreak(organizationId: string, type: 'start' | 'end') {
return this._organizationRepository.setStreak(organizationId, type);
}
@ -103,9 +127,16 @@ export class OrganizationService {
async inviteTeamMember(org: Organization, user: User, body: AddTeamMemberDto) {
const timeLimit = dayjs().add(2, 'day').format('YYYY-MM-DD HH:mm:ss');
const id = makeId(5);
// only the invite fields, the body can carry undeclared properties
const url =
process.env.FRONTEND_URL +
`/?org=${AuthService.signJWT({ ...body, orgId: org.id, timeLimit, id })}`;
`/?org=${AuthService.signJWT({
email: body.email,
role: body.role,
orgId: org.id,
timeLimit,
id,
})}`;
if (body.sendEmail) {
const inviter = user.name
? `${user.name} (${user.email})`
@ -188,13 +219,60 @@ export class OrganizationService {
const myLevel = myRole === 'USER' ? 0 : myRole === 'ADMIN' ? 1 : 2;
const userLevel = userRole === 'USER' ? 0 : userRole === 'ADMIN' ? 1 : 2;
if (myLevel < userLevel) {
// The team settings UI only ever offers the delete 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. Enforce the same bound here, not just
// "below": otherwise calling this endpoint directly lets a SUPERADMIN
// remove another SUPERADMIN, or remove themselves - including as the
// organization's only SUPERADMIN, orphaning it with nobody left able
// to manage the team or billing.
if (myLevel <= userLevel) {
throw new Error('You do not have permission to delete this user');
}
return this._organizationRepository.deleteTeamMember(org.id, userId);
}
// Self-service counterpart to deleteTeamMember(): a member removing
// themselves instead of being removed by an admin. The auth middleware
// always needs at least one non-disabled organization for the user to
// fall back to (req.org = organization[0]), and an org can't be left
// without a Super Admin able to manage it afterwards, so both are
// blocked here rather than left to 500 on the next request.
async leaveOrganization(user: User, org: Organization) {
const userOrgs = await this._organizationRepository.getOrgsByUserId(
user.id
);
if (userOrgs.length <= 1) {
throw new HttpException(
'You cannot leave your only organization. Delete it instead if you no longer need it.',
400
);
}
const findOrgToLeave = userOrgs.find((orgUser) => orgUser.id === org.id);
if (!findOrgToLeave) {
throw new HttpException('You are not part of this organization', 400);
}
// @ts-ignore
const myRole = findOrgToLeave.users[0].role;
if (myRole === 'SUPERADMIN') {
const superAdminCount = await this._organizationRepository.countSuperAdmins(
org.id
);
if (superAdminCount <= 1) {
throw new HttpException(
'You are the only Super Admin of this organization. Promote another member to Super Admin or delete the organization before leaving.',
400
);
}
}
return this._organizationRepository.deleteTeamMember(org.id, user.id);
}
disableOrEnableNonSuperAdminUsers(orgId: string, disable: boolean) {
return this._organizationRepository.disableOrEnableNonSuperAdminUsers(
orgId,
@ -212,4 +290,30 @@ export class OrganizationService {
shortlink
);
}
getApprovalForQueueSetting(orgId: string) {
return this._organizationRepository.getApprovalForQueueSetting(orgId);
}
updateApprovalForQueueSetting(
orgId: string,
requireApprovalForQueue: boolean
) {
return this._organizationRepository.updateApprovalForQueueSetting(
orgId,
requireApprovalForQueue
);
}
// Used by PostsService#createPost to decide whether a USER-level member's
// schedule/now save should be held as a pendingApproval draft instead of
// going straight to QUEUE. A tiny wrapper (rather than inlining the
// repository call there) so the "what counts as true" logic - including
// the null-org edge case - lives in one place.
async requiresApprovalForQueue(orgId: string): Promise<boolean> {
const org = await this._organizationRepository.getApprovalForQueueSetting(
orgId
);
return !!org?.requireApprovalForQueue;
}
}

View File

@ -0,0 +1,110 @@
import { PrismaRepository } from '@gitroom/nestjs-libraries/database/prisma/prisma.service';
import { Injectable } from '@nestjs/common';
export interface SnapshotCandidate {
id: string;
organizationId: string;
integrationId: string;
publishDate: Date;
integration: {
providerIdentifier: string;
tokenExpiration: Date | null;
};
}
export interface UpsertSnapshotParams {
postId: string;
organizationId: string;
integrationId: string;
providerIdentifier: string;
publishDate: Date;
dayOfWeek: number;
hourOfDay: number;
engagementScore: number | null;
}
@Injectable()
export class PostEngagementRepository {
constructor(
private _post: PrismaRepository<'post'>,
private _postEngagementSnapshot: PrismaRepository<'postEngagementSnapshot'>
) {}
// Bounded by `limit` (the batch job's hard cap on provider calls per run).
// Oldest-unprocessed-first so a large backlog drains in FIFO order instead
// of starving old posts forever. `postEngagementSnapshot: null` excludes
// any post already attempted - every post is only ever attempted once.
findSnapshotCandidates(
limit: number,
matureBefore: Date,
lookbackAfter: Date
): Promise<SnapshotCandidate[]> {
return this._post.model.post.findMany({
where: {
state: 'PUBLISHED',
deletedAt: null,
releaseId: { not: null },
NOT: { releaseId: 'missing' },
publishDate: {
gte: lookbackAfter,
lte: matureBefore,
},
integration: {
disabled: false,
deletedAt: null,
},
postEngagementSnapshot: null,
},
orderBy: { publishDate: 'asc' },
take: limit,
select: {
id: true,
organizationId: true,
integrationId: true,
publishDate: true,
integration: {
select: {
providerIdentifier: true,
tokenExpiration: true,
},
},
},
});
}
upsertSnapshot(data: UpsertSnapshotParams) {
return this._postEngagementSnapshot.model.postEngagementSnapshot.upsert({
where: { postId: data.postId },
create: {
postId: data.postId,
organizationId: data.organizationId,
integrationId: data.integrationId,
providerIdentifier: data.providerIdentifier,
publishDate: data.publishDate,
dayOfWeek: data.dayOfWeek,
hourOfDay: data.hourOfDay,
engagementScore: data.engagementScore,
},
update: {
dayOfWeek: data.dayOfWeek,
hourOfDay: data.hourOfDay,
engagementScore: data.engagementScore,
},
});
}
// Aggregated server-side (groupBy), never pulls raw rows to the app - the
// query itself is the bound, so this stays cheap no matter how many
// snapshots a channel has accumulated over time.
getBucketsForIntegration(integrationId: string) {
return this._postEngagementSnapshot.model.postEngagementSnapshot.groupBy({
by: ['dayOfWeek', 'hourOfDay'],
where: {
integrationId,
engagementScore: { not: null },
},
_avg: { engagementScore: true },
_count: { _all: true },
});
}
}

View File

@ -0,0 +1,153 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import dayjs from 'dayjs';
import { PostEngagementRepository } from '@gitroom/nestjs-libraries/database/prisma/post-engagement/post-engagement.repository';
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
import {
BestTimeSuggestion,
EngagementBucket,
MATURE_AFTER_DAYS,
MAX_LOOKBACK_DAYS,
SNAPSHOT_ANALYTICS_WINDOW_DAYS,
computeEngagementScore,
getBatchCap,
rankBuckets,
toTimeBucket,
} from '@gitroom/nestjs-libraries/database/prisma/post-engagement/post-engagement.util';
export interface CaptureBatchResult {
attempted: number;
captured: number;
skipped: number;
}
export interface BestTimesResult {
hasData: boolean;
suggestions: BestTimeSuggestion[];
}
@Injectable()
export class PostEngagementService {
constructor(
private _postEngagementRepository: PostEngagementRepository,
private _postsService: PostsService,
private _integrationService: IntegrationService
) {}
// Called once per scheduled run by bestTimeToPostWorkflow (daily cadence).
// Bounded: at most getBatchCap() provider calls.
//
// A post is only ever upserted (permanently excluded from future runs) when
// checkPostAnalytics returns cleanly - including a "no data" result, e.g. no
// postAnalytics capability or an unavailable release, which really is
// permanent. A thrown error (provider timeout/rate-limit/5xx) is treated as
// transient: the post is left as a candidate and retried on a later run,
// instead of a momentary blip permanently excluding it from its channel's
// recommendation. captureBatch is still bounded because the per-run
// candidate count is capped regardless of outcome.
//
// Candidates whose integration token is already expired are skipped
// entirely (no checkPostAnalytics call) rather than forcing a refresh here:
// checkPostAnalytics force-refreshes expired tokens and disconnects the
// channel if that refresh doesn't yield a usable token - a real,
// user-visible action that belongs to the publish/analytics-view flows the
// user actually triggered, not to this background backfill job. Those
// integrations naturally refresh (or get disconnected) through normal
// usage, and become candidates again once the integration is next
// published through or stored with a non-expired token.
async captureBatch(): Promise<CaptureBatchResult> {
const now = dayjs();
const matureBefore = now.subtract(MATURE_AFTER_DAYS, 'day').toDate();
const lookbackAfter = now.subtract(MAX_LOOKBACK_DAYS, 'day').toDate();
const candidates =
await this._postEngagementRepository.findSnapshotCandidates(
getBatchCap(),
matureBefore,
lookbackAfter
);
let captured = 0;
let skipped = 0;
for (const post of candidates) {
if (
post.integration.tokenExpiration &&
dayjs(post.integration.tokenExpiration).isBefore(now)
) {
skipped++;
continue;
}
let analytics: unknown;
try {
analytics = await this._postsService.checkPostAnalytics(
post.organizationId,
post.id,
SNAPSHOT_ANALYTICS_WINDOW_DAYS
);
} catch (err) {
// Transient failure - do not upsert, retry on a later run.
skipped++;
continue;
}
const score = computeEngagementScore(
Array.isArray(analytics) ? analytics : null
);
const { dayOfWeek, hourOfDay } = toTimeBucket(post.publishDate);
try {
await this._postEngagementRepository.upsertSnapshot({
postId: post.id,
organizationId: post.organizationId,
integrationId: post.integrationId,
providerIdentifier: post.integration.providerIdentifier,
publishDate: post.publishDate,
dayOfWeek,
hourOfDay,
engagementScore: score,
});
if (score !== null) {
captured++;
}
} catch (err) {
// Best-effort snapshot persistence - one failed write must not stop
// the rest of the batch. Left as a candidate, will retry later.
}
}
return { attempted: candidates.length, captured, skipped };
}
// Read path for the UI: pure DB aggregation, no live provider calls.
async getBestTimes(
orgId: string,
integrationId: string
): Promise<BestTimesResult> {
const integration = await this._integrationService.getIntegrationById(
orgId,
integrationId
);
if (!integration) {
throw new NotFoundException('Integration not found');
}
const rows = await this._postEngagementRepository.getBucketsForIntegration(
integrationId
);
const buckets: EngagementBucket[] = rows.map((row) => ({
dayOfWeek: row.dayOfWeek,
hourOfDay: row.hourOfDay,
avgEngagement: row._avg.engagementScore ?? 0,
sampleSize: row._count._all,
}));
const suggestions = rankBuckets(buckets);
return {
hasData: suggestions.length > 0,
suggestions,
};
}
}

View File

@ -0,0 +1,175 @@
import {
computeEngagementScore,
toTimeBucket,
rankBuckets,
getBatchCap,
EngagementBucket,
MIN_SAMPLE_SIZE_FOR_SUGGESTION,
} from './post-engagement.util';
import { AnalyticsData } from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
describe('computeEngagementScore', () => {
it('sums the latest value of every metric series', () => {
const data: AnalyticsData[] = [
{
label: 'Impressions',
percentageChange: 0,
data: [{ total: '100', date: '2026-10-01' }],
},
{
label: 'Likes',
percentageChange: 0,
data: [{ total: '20', date: '2026-10-01' }],
},
];
expect(computeEngagementScore(data)).toBe(120);
});
it('uses only the most recent point of a multi-point series', () => {
const data: AnalyticsData[] = [
{
label: 'Impressions',
percentageChange: 0,
data: [
{ total: '10', date: '2026-10-01' },
{ total: '50', date: '2026-10-02' },
],
},
];
expect(computeEngagementScore(data)).toBe(50);
});
it('ignores series with no usable numeric value', () => {
const data: AnalyticsData[] = [
{
label: 'Impressions',
percentageChange: 0,
data: [{ total: 'not-a-number', date: '2026-10-01' }],
},
{
label: 'Likes',
percentageChange: 0,
data: [{ total: '5', date: '2026-10-01' }],
},
];
expect(computeEngagementScore(data)).toBe(5);
});
it('returns null for an empty array (no usable metrics)', () => {
expect(computeEngagementScore([])).toBeNull();
});
it('returns null for the {missing: true} shape', () => {
expect(computeEngagementScore({ missing: true })).toBeNull();
});
it('returns null for null/undefined input', () => {
expect(computeEngagementScore(null)).toBeNull();
expect(computeEngagementScore(undefined)).toBeNull();
});
it('returns null when every series has an empty data array', () => {
const data: AnalyticsData[] = [
{ label: 'Impressions', percentageChange: 0, data: [] },
];
expect(computeEngagementScore(data)).toBeNull();
});
});
describe('toTimeBucket', () => {
it('derives UTC day-of-week and hour-of-day from a publish date', () => {
// 2026-10-22 is a Thursday
expect(toTimeBucket('2026-10-22T14:30:00.000Z')).toEqual({
dayOfWeek: 4,
hourOfDay: 14,
});
});
it('is based on UTC, not the host machine timezone', () => {
// 23:30 UTC on a Sunday must stay day 0, hour 23, regardless of local TZ
expect(toTimeBucket('2026-10-25T23:30:00.000Z')).toEqual({
dayOfWeek: 0,
hourOfDay: 23,
});
});
it('accepts a Date instance as well as a string', () => {
expect(toTimeBucket(new Date('2026-10-22T00:00:00.000Z'))).toEqual({
dayOfWeek: 4,
hourOfDay: 0,
});
});
});
describe('rankBuckets', () => {
const bucket = (
dayOfWeek: number,
hourOfDay: number,
avgEngagement: number,
sampleSize: number
): EngagementBucket => ({ dayOfWeek, hourOfDay, avgEngagement, sampleSize });
it('sorts by average engagement descending', () => {
const buckets = [
bucket(1, 9, 10, 5),
bucket(2, 10, 50, 5),
bucket(3, 11, 30, 5),
];
expect(rankBuckets(buckets).map((b) => b.avgEngagement)).toEqual([
50, 30, 10,
]);
});
it('drops buckets below the minimum sample size so one lucky post cannot drive a suggestion', () => {
const buckets = [
bucket(1, 9, 1000, 1),
bucket(2, 10, 20, MIN_SAMPLE_SIZE_FOR_SUGGESTION),
];
const ranked = rankBuckets(buckets);
expect(ranked).toHaveLength(1);
expect(ranked[0].hourOfDay).toBe(10);
});
it('caps the result at topN', () => {
const buckets = Array.from({ length: 10 }, (_, i) =>
bucket(i % 7, i, i, MIN_SAMPLE_SIZE_FOR_SUGGESTION)
);
expect(rankBuckets(buckets, 3)).toHaveLength(3);
});
it('returns an empty array when nothing meets the sample-size threshold', () => {
const buckets = [bucket(1, 9, 1000, 1), bucket(2, 10, 500, 2)];
expect(rankBuckets(buckets)).toEqual([]);
});
});
describe('getBatchCap', () => {
const originalEnv = process.env.BEST_TIME_SNAPSHOT_BATCH_SIZE;
afterEach(() => {
process.env.BEST_TIME_SNAPSHOT_BATCH_SIZE = originalEnv;
});
it('falls back to the default when unset', () => {
delete process.env.BEST_TIME_SNAPSHOT_BATCH_SIZE;
expect(getBatchCap()).toBe(300);
});
it('honors a positive override', () => {
process.env.BEST_TIME_SNAPSHOT_BATCH_SIZE = '50';
expect(getBatchCap()).toBe(50);
});
it('falls back to the default for an invalid override, so the batch job is never accidentally unbounded', () => {
process.env.BEST_TIME_SNAPSHOT_BATCH_SIZE = '-5';
expect(getBatchCap()).toBe(300);
process.env.BEST_TIME_SNAPSHOT_BATCH_SIZE = 'not-a-number';
expect(getBatchCap()).toBe(300);
});
});

View File

@ -0,0 +1,96 @@
import { AnalyticsData } from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
// Pure helpers for the best-time-to-post aggregation, kept free of NestJS/DB
// imports so they stay cheap to unit test (see
// post-engagement.service.standalone.spec.ts). All orchestration (DI,
// Prisma, provider calls) lives in post-engagement.service.ts.
export interface TimeBucket {
dayOfWeek: number; // 0 (Sunday) - 6 (Saturday), UTC
hourOfDay: number; // 0 - 23, UTC
}
export interface EngagementBucket extends TimeBucket {
avgEngagement: number;
sampleSize: number;
}
export type BestTimeSuggestion = EngagementBucket;
// A bucket needs at least this many real snapshots before it is suggested,
// so a single lucky/unlucky post never drives a recommendation.
export const MIN_SAMPLE_SIZE_FOR_SUGGESTION = 3;
export const MAX_SUGGESTIONS = 5;
// A post needs this many days to accrue realistic engagement before it is
// snapshotted - capturing right after publish would understate it.
export const MATURE_AFTER_DAYS = 3;
// Only posts published within this window are candidates at all, so the
// recommendation reflects recent audience behaviour, not years-old history.
export const MAX_LOOKBACK_DAYS = 60;
// How many days of post-level analytics to request per capture. The post
// analytics providers return current cumulative totals regardless of this
// window, so any small value works; kept consistent with the UI's default.
export const SNAPSHOT_ANALYTICS_WINDOW_DAYS = 7;
// Hard cap on provider analytics calls per batch run, across the whole
// platform - this is what makes the job bounded instead of the unbounded
// "call every post live" design that was deliberately rejected. Every
// candidate post is attempted at most once ever (see captureBatch), so a
// backlog drains at this rate per run and steady-state load stays flat.
const DEFAULT_BATCH_CAP = 300;
export function getBatchCap(): number {
const fromEnv = Number(process.env.BEST_TIME_SNAPSHOT_BATCH_SIZE);
return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : DEFAULT_BATCH_CAP;
}
// Sums the latest reported value of every metric series a provider returns
// (impressions, likes, clicks, ...). Deliberately generic - it must not
// special-case any platform's label names.
export function computeEngagementScore(
data: AnalyticsData[] | { missing: true } | null | undefined
): number | null {
if (!data || !Array.isArray(data) || data.length === 0) {
return null;
}
let total = 0;
let sawValue = false;
for (const entry of data) {
const points = entry?.data;
if (!Array.isArray(points) || points.length === 0) {
continue;
}
const latest = points[points.length - 1];
const value = Number(latest?.total);
if (!Number.isFinite(value)) {
continue;
}
total += value;
sawValue = true;
}
return sawValue ? total : null;
}
export function toTimeBucket(publishDate: Date | string): TimeBucket {
const date = new Date(publishDate);
return {
dayOfWeek: date.getUTCDay(),
hourOfDay: date.getUTCHours(),
};
}
export function rankBuckets(
buckets: EngagementBucket[],
topN: number = MAX_SUGGESTIONS,
minSampleSize: number = MIN_SAMPLE_SIZE_FOR_SUGGESTION
): BestTimeSuggestion[] {
return [...buckets]
.filter((bucket) => bucket.sampleSize >= minSampleSize)
.sort((a, b) => b.avgEngagement - a.avgEngagement)
.slice(0, topN);
}

View File

@ -202,6 +202,7 @@ export class PostsRepository {
intervalInDays: true,
group: true,
creationMethod: true,
pendingApproval: true,
settings: true,
tags: {
where: {
@ -327,6 +328,7 @@ export class PostsRepository {
intervalInDays: true,
group: true,
creationMethod: true,
pendingApproval: true,
tags: {
where: {
tag: {
@ -359,6 +361,46 @@ export class PostsRepository {
};
}
// Backs the ADMIN/SUPERADMIN-only "Pending Approvals" list (settings/team
// page) - every DRAFT a USER-level member couldn't queue directly because
// the org has Organization.requireApprovalForQueue on. Scoped to
// pendingApproval (not just "every draft"), so normal, never-submitted
// drafts never show up here.
getPendingApprovalPosts(orgId: string) {
return this._post.model.post.findMany({
where: {
organizationId: orgId,
deletedAt: null,
pendingApproval: true,
state: State.DRAFT,
},
orderBy: {
publishDate: 'asc',
},
select: {
id: true,
content: true,
publishDate: true,
group: true,
integration: {
select: {
id: true,
providerIdentifier: true,
name: true,
picture: true,
},
},
createdBy: {
select: {
id: true,
name: true,
email: true,
},
},
},
});
}
async deletePost(orgId: string, group: string) {
await this._post.model.post.updateMany({
where: {
@ -515,6 +557,14 @@ export class PostsRepository {
},
data: {
state,
// Every path that calls changeState is an intentional, final state
// transition (schedule/approve, republish, mark published/errored),
// so any pendingApproval flag left over from the USER-level
// approval gate (see Organization.requireApprovalForQueue) is
// always stale by the time we get here - clear it. A pending post
// never reaches this method any other way, since createPost skips
// starting its workflow while pendingApproval is true.
pendingApproval: false,
...(err
? { error: typeof err === 'string' ? err : JSON.stringify(err) }
: {}),
@ -617,7 +667,15 @@ export class PostsRepository {
keepGroup = false,
// Shared by the posts saved together for several channels, so opening one
// of them in the editor brings the others.
batchId?: string
batchId?: string,
// WEB-dashboard only (see PostsService#createPost) - who saved this post,
// stamped on create so an approver can be notified of who submitted it.
createdByUserId?: string,
// true when a USER-level member tried to schedule/publish-now while the
// org has Organization.requireApprovalForQueue on - holds the post as a
// DRAFT with pendingApproval set instead of the state `state` would
// otherwise produce. See PostsService#createPost/#approvePendingQueuePost.
pendingApproval = false
) {
const posts: Post[] = [];
const uuid = uuidv4();
@ -679,11 +737,17 @@ export class PostsRepository {
intervalInDays: inter ? +inter : null,
approvedSubmitForOrder: APPROVED_SUBMIT_FOR_ORDER.NO,
...(type === 'create' ? { creationMethod } : {}),
...(type === 'create' && createdByUserId
? { createdBy: { connect: { id: createdByUserId } } }
: {}),
...(state === 'update'
? {}
: pendingApproval
? { state: 'DRAFT' as const, pendingApproval: true }
: {
state:
state === 'draft' ? ('DRAFT' as const) : ('QUEUE' as const),
pendingApproval: false,
}),
image: JSON.stringify(value.image),
settings: JSON.stringify(body.settings),
@ -1010,6 +1074,13 @@ export class PostsRepository {
lastName: true,
},
},
assignedTo: {
select: {
id: true,
name: true,
lastName: true,
},
},
},
orderBy: {
createdAt: 'asc',
@ -1134,6 +1205,9 @@ export class PostsRepository {
anchorStart?: number;
anchorEnd?: number;
anchorQuote?: string;
isApproval?: boolean;
mentionedUserIds?: string[];
assignedToId?: string;
} = {}
) {
return this._comments.model.comments.create({
@ -1147,10 +1221,20 @@ export class PostsRepository {
anchorStart: extra.anchorStart ?? null,
anchorEnd: extra.anchorEnd ?? null,
anchorQuote: extra.anchorQuote ?? null,
isApproval: extra.isApproval ?? false,
mentionedUserIds: extra.mentionedUserIds ?? [],
assignedToId: extra.assignedToId ?? null,
},
});
}
async setCommentAssignee(orgId: string, commentId: string, assignedToId: string | null) {
return this._comments.model.comments.update({
where: { id: commentId },
data: { assignedToId },
});
}
async getPostByForWebhookId(postId: string, integrationId: string) {
const select = {
id: true,

View File

@ -1,11 +1,20 @@
import {
BadRequestException,
HttpException,
Injectable,
NotFoundException,
ValidationPipe,
} from '@nestjs/common';
import { PostsRepository } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.repository';
import { CreatePostDto } from '@gitroom/nestjs-libraries/dtos/posts/create.post.dto';
import {
BulkScheduleDto,
BulkScheduleRowResult,
} from '@gitroom/nestjs-libraries/dtos/posts/bulk.schedule.dto';
import {
providerNeedsSettings,
simpleTextProviders,
} from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/all.providers.settings';
import dayjs from 'dayjs';
import { IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
import {
@ -55,8 +64,14 @@ import { validate } from 'class-validator';
import { plainToInstance } from 'class-transformer';
import { stripHtmlValidation } from '@gitroom/helpers/utils/strip.html.validation';
import { postContentPlainText } from '@gitroom/helpers/utils/sanitize.post.content';
import { CreatePublicCommentDto } from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
import {
ApprovePostDto,
CreatePublicCommentDto,
} from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
import { countLength } from '@gitroom/helpers/utils/count.length';
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
import { Role } from '@prisma/client';
type PostWithConditionals = Post & {
integration?: Integration;
@ -74,7 +89,9 @@ export class PostsService {
private _shortLinkService: ShortLinkService,
private _openaiService: OpenaiService,
private _temporalService: TemporalService,
private _refreshIntegrationService: RefreshIntegrationService
private _refreshIntegrationService: RefreshIntegrationService,
private _organizationService: OrganizationService,
private _notificationService: NotificationService
) {}
searchForMissingThreeHoursPosts() {
@ -936,7 +953,7 @@ export class PostsService {
try {
await this._temporalService.client
.getRawClient()
?.workflow.start('postWorkflowV112', {
?.workflow.start('postWorkflowV113', {
workflowId: `post_${postId}`,
taskQueue: 'main',
workflowIdConflictPolicy: 'TERMINATE_EXISTING',
@ -1116,10 +1133,24 @@ export class PostsService {
orgId: string,
body: CreatePostDto,
creationMethod: CreationMethod,
keepGroup = false
keepGroup = false,
// WEB dashboard only (see PostsController#createPost) - every other
// creation path (API, MCP, autopost, bulk CSV, evergreen, clipping)
// never passes this, so they're entirely unaffected by the approval
// gate below, same as before this field existed.
createdBy?: { userId: string; role: Role }
): Promise<any[]> {
const postList = [];
const batchId = uuidv4();
// A USER-level team member trying to schedule/publish-now is held as a
// pendingApproval draft instead, when the org has that gate on (see
// Organization.requireApprovalForQueue). ADMIN/SUPERADMIN callers skip
// this entirely. See approvePendingQueuePost/rejectPendingQueuePost
// below for the other half of this flow.
const needsApproval =
createdBy?.role === Role.USER &&
(body.type === 'schedule' || body.type === 'now') &&
(await this._organizationService.requiresApprovalForQueue(orgId));
for (const post of body.posts) {
if (
(body.type === 'schedule' || body.type === 'now') &&
@ -1162,7 +1193,9 @@ export class PostsService {
creationMethod,
body.inter,
keepGroup,
batchId
batchId,
createdBy?.userId,
needsApproval
);
if (!posts?.length) {
@ -1187,12 +1220,136 @@ export class PostsService {
postList.push({
postId: posts[0].id,
integration: post.integration.id,
// Lets PostsController#createPost's caller (the dashboard's save
// flow) show "submitted for approval" instead of "scheduled" -
// additive, every existing consumer of this array already ignores
// unknown keys.
pendingApproval: posts[0].state === 'DRAFT' && needsApproval,
});
}
return postList;
}
// Bulk CSV scheduling: each row goes through the exact same
// validatePosts -> mapTypeToPost -> createPost pipeline as a single post
// created from the web UI (see PostsController#createPost), just looped.
// A bad row never aborts the batch — every row gets its own result so the
// caller can show which ones scheduled and which didn't, same spirit as
// Buffer's bulk upload ("schedule what's valid, report the rest").
async bulkSchedule(
orgId: string,
body: BulkScheduleDto
): Promise<BulkScheduleRowResult[]> {
const integration = await this._integrationService.getIntegrationById(
orgId,
body.integration.id
);
if (!integration) {
throw new BadRequestException(
`Integration with id ${body.integration.id} not found`
);
}
const providerIdentifier = integration.providerIdentifier;
if (providerNeedsSettings(providerIdentifier)) {
throw new BadRequestException(
`Bulk CSV scheduling only supports simple text platforms right now (${simpleTextProviders().join(
', '
)}). "${providerIdentifier}" needs extra settings that can't be filled from a spreadsheet yet.`
);
}
const results: BulkScheduleRowResult[] = [];
for (let row = 0; row < body.posts.length; row++) {
try {
const postId = await this.createPostFromBulkRow(
orgId,
body.integration.id,
providerIdentifier,
body.posts[row].date,
body.posts[row].content,
body.shortLink ?? false
);
results.push({ row, success: true, postId });
} catch (err) {
results.push({
row,
success: false,
error:
err instanceof HttpException
? err.message
: 'Could not schedule this row',
});
}
}
return results;
}
private async createPostFromBulkRow(
orgId: string,
integrationId: string,
providerIdentifier: string,
date: string,
content: string,
shortLink: boolean
): Promise<string> {
const rawPosts = [
{
integration: { id: integrationId },
value: [
{ content, image: [] as Array<{ path: string; thumbnail?: string }> },
],
settings: { __type: providerIdentifier },
},
];
const validation = await this.validatePosts(orgId, rawPosts);
for (const item of validation) {
if (item.emptyContent) {
throw new BadRequestException(
'Your post should have at least one character or one image.'
);
}
if (!item.valid) {
throw new BadRequestException(
item.settingsError || 'Please fix your settings'
);
}
if (item.errors !== true) {
throw new BadRequestException(item.errors as string);
}
if (item.tooLong) {
throw new BadRequestException('Post is too long, please fix it');
}
}
const mapped = await this.mapTypeToPost(
{
type: 'schedule',
shortLink,
date,
tags: [],
posts: rawPosts,
} as unknown as CreatePostDto,
orgId
);
const created = await this.createPost(
orgId,
mapped,
CreationMethod.BULK_CSV
);
if (!created?.length) {
throw new BadRequestException('Could not schedule this post');
}
return created[0].postId;
}
// Update ONLY the provider settings of a not-yet-published post (scheduled or
// draft). The passed keys are merged into the existing settings; content and
// publish date stay as they are, so the running publish workflow is left
@ -1373,6 +1530,67 @@ export class PostsService {
return { id, state };
}
// ADMIN/SUPERADMIN-only list backing the "Pending Approvals" view
// (settings/team page) - see Organization.requireApprovalForQueue.
async getPendingApprovalPosts(orgId: string) {
return this._postRepository.getPendingApprovalPosts(orgId);
}
// ADMIN/SUPERADMIN-only counterpart to the USER-level gate in createPost.
// Reuses changePostStatus - the exact path the internal "schedule"
// button and the public-preview approvePublicPost already go through -
// so the real publish workflow actually starts, instead of a bare
// changeState that would only flip the DB row.
async approvePendingQueuePost(orgId: string, postId: string) {
const post = await this._postRepository.getPostById(postId, orgId);
if (!post || post.state !== 'DRAFT' || !post.pendingApproval) {
throw new NotFoundException(
'No pending-approval post found with this id'
);
}
const updated = await this.changePostStatus(orgId, postId, 'schedule');
if (post.createdByUserId) {
await this._notificationService
.notifyUser(
orgId,
post.createdByUserId,
'Your post was approved and is now queued to publish.'
)
.catch(() => {});
}
return updated;
}
// Leaves the post exactly as the USER-level member left it - a normal,
// still-editable draft - just no longer pendingApproval. changeState
// always clears the flag (see posts.repository.ts), so this never starts
// the publish workflow the way changePostStatus/approvePendingQueuePost do.
async rejectPendingQueuePost(orgId: string, postId: string) {
const post = await this._postRepository.getPostById(postId, orgId);
if (!post || post.state !== 'DRAFT' || !post.pendingApproval) {
throw new NotFoundException(
'No pending-approval post found with this id'
);
}
await this._postRepository.changeState(postId, 'DRAFT');
if (post.createdByUserId) {
await this._notificationService
.notifyUser(
orgId,
post.createdByUserId,
'Your post was rejected and remains a draft.'
)
.catch(() => {});
}
return { id: postId, state: 'DRAFT' as State };
}
async changeDate(
orgId: string,
id: string,
@ -1570,11 +1788,20 @@ export class PostsService {
return date.clone().add(num, 'minutes').format('YYYY-MM-DDTHH:mm:00');
}
async getComments(previewId: string) {
// `viewerOrgId` is only ever set by the authenticated internal route
// (PostsController) - the fully public, no-auth preview route
// (PublicController) never passes it. Mentions/assignment reveal internal
// team member identities, so they're only included once we know the
// caller is logged in as a member of the org that actually owns the
// post; an external reviewer on the public link gets every other field
// unchanged but never sees who's internally mentioned/assigned.
async getComments(previewId: string, viewerOrgId?: string) {
const posts = await this.getPostsRecursively(previewId, false);
const comments = await this._postRepository.getCommentsForPosts(
posts.map((p) => p.id)
);
const includeInternal =
!!viewerOrgId && posts.some((p) => p.organizationId === viewerOrgId);
return comments.map((comment) => ({
id: comment.id,
@ -1585,6 +1812,7 @@ export class PostsService {
anchorEnd: comment.anchorEnd,
anchorQuote: comment.anchorQuote,
resolvedAt: comment.resolvedAt,
isApproval: comment.isApproval,
createdAt: comment.createdAt,
name: comment.userId
? [comment.user?.name, comment.user?.lastName]
@ -1592,6 +1820,15 @@ export class PostsService {
.join(' ')
.trim() || null
: comment.displayName,
mentionedUserIds: includeInternal ? comment.mentionedUserIds : [],
assignedToId: includeInternal ? comment.assignedToId : null,
assignedToName:
includeInternal && comment.assignedTo
? [comment.assignedTo.name, comment.assignedTo.lastName]
.filter(Boolean)
.join(' ')
.trim() || null
: null,
}));
}
@ -1656,7 +1893,45 @@ export class PostsService {
}
}
return this._postRepository.createComment(
// Mentions/assignment only ever come from an authenticated team member
// (userId set) - the public no-auth preview link can never set them,
// even if a crafted request body includes them (DTO validation alone
// isn't a trust boundary here).
let mentionedUserIds: string[] | undefined;
let assignedToId: string | null | undefined;
if (userId) {
if (body.assignedToId && body.parentId) {
throw new BadRequestException('Replies cannot be assigned');
}
if (body.mentions?.length || body.assignedToId) {
const teamMembers = await this._organizationService.getTeamMembersForMentions(
post.organizationId
);
const teamMemberIds = new Set(teamMembers.map((member) => member.id));
if (body.mentions?.length) {
const unknown = body.mentions.filter((id) => !teamMemberIds.has(id));
if (unknown.length) {
throw new BadRequestException(
'One or more mentioned users are not members of this organization'
);
}
mentionedUserIds = Array.from(new Set(body.mentions));
}
if (body.assignedToId) {
if (!teamMemberIds.has(body.assignedToId)) {
throw new BadRequestException(
'Assigned user is not a member of this organization'
);
}
assignedToId = body.assignedToId;
}
}
}
const createdComment = await this._postRepository.createComment(
post.organizationId,
userId,
post.id,
@ -1667,8 +1942,124 @@ export class PostsService {
anchorStart: hasStart ? body.anchorStart : undefined,
anchorEnd: hasStart ? body.anchorEnd : undefined,
anchorQuote: hasStart ? body.anchorQuote : undefined,
mentionedUserIds,
assignedToId,
}
);
await this.notifyMentionedAndAssigned(
post.organizationId,
userId,
mentionedUserIds,
assignedToId
);
return createdComment;
}
// Best-effort in-app pings for @mentions and a new assignment on a
// comment - never lets a notification failure take down comment
// creation, same contract as the webhook/email sends elsewhere.
private async notifyMentionedAndAssigned(
organizationId: string,
authorUserId: string | null,
mentionedUserIds?: string[],
assignedToId?: string | null
) {
const targets = new Set<string>();
for (const id of mentionedUserIds || []) {
if (id !== authorUserId) {
targets.add(id);
}
}
await Promise.all(
Array.from(targets).map((userId) =>
this._notificationService
.notifyUser(
organizationId,
userId,
'You were mentioned in a comment on a post.'
)
.catch(() => {})
)
);
if (assignedToId && assignedToId !== authorUserId) {
await this._notificationService
.notifyUser(
organizationId,
assignedToId,
'A comment was assigned to you on a post.'
)
.catch(() => {});
}
}
// Lets the client who was sent the public preview link approve a draft
// directly, without logging in. Mirrors createPublicComment's identity
// checks (name + recaptcha), then does exactly what the "schedule" button
// already does internally: flips the post from DRAFT to QUEUE so the
// existing publish workflow picks it up. Only drafts can be approved, so
// this never touches a post that's already queued/published/erroring.
async approvePublicPost(
previewId: string,
body: ApprovePostDto,
userId: string | null,
ip: string
) {
const posts = await this.getPostsRecursively(previewId, false);
if (!posts.length) {
throw new NotFoundException('Post not found');
}
const post = body.postId
? posts.find((p) => p.id === body.postId)
: posts[0];
if (!post) {
throw new BadRequestException('Post does not belong to this preview');
}
if (post.state !== State.DRAFT) {
throw new BadRequestException(
'Only drafts awaiting approval can be approved'
);
}
let displayName: string | undefined;
if (!userId) {
if (!body.displayName?.trim()) {
throw new BadRequestException('Name is required');
}
displayName = body.displayName.trim();
await this.verifyRecaptcha(body.recaptchaToken, ip);
}
await this._postRepository.createComment(
post.organizationId,
userId,
post.id,
displayName
? `${displayName} approved this post for publishing.`
: 'Approved this post for publishing.',
{
displayName,
isApproval: true,
}
);
// Reuse the exact same path the internal "schedule" button goes
// through (changePostStatus), not a hand-rolled changeState call — it's
// the one that also starts the Temporal workflow that actually
// publishes the post. A bare changeState(QUEUE) would flip the DB row
// but never schedule the real publish.
const updated = await this.changePostStatus(
post.organizationId,
post.id,
'schedule'
);
return { success: true, state: updated.state };
}
private async verifyRecaptcha(token: string | undefined, ip: string) {
@ -1712,6 +2103,55 @@ export class PostsService {
);
}
// Changes (or clears, with an empty/undefined assignedToId) who a root
// comment is directed at. Same org/root-only restrictions as
// resolveComment above.
async assignComment(
orgId: string,
commentId: string,
assignedToId: string | undefined,
actingUserId: string
) {
const comment = await this._postRepository.getCommentById(commentId);
if (!comment || comment.post.organizationId !== orgId) {
throw new NotFoundException('Comment not found');
}
if (comment.parentId) {
throw new BadRequestException('Only root comments can be assigned');
}
let resolvedAssignedToId: string | null = null;
if (assignedToId) {
const teamMembers = await this._organizationService.getTeamMembersForMentions(
orgId
);
if (!teamMembers.some((member) => member.id === assignedToId)) {
throw new BadRequestException(
'Assigned user is not a member of this organization'
);
}
resolvedAssignedToId = assignedToId;
}
const updated = await this._postRepository.setCommentAssignee(
orgId,
commentId,
resolvedAssignedToId
);
if (resolvedAssignedToId && resolvedAssignedToId !== actingUserId) {
await this._notificationService
.notifyUser(
orgId,
resolvedAssignedToId,
'A comment was assigned to you on a post.'
)
.catch(() => {});
}
return updated;
}
// A comment anchored to a span of text keeps its quote but loses the
// highlight once the span no longer reads the same on the new content.
async detachStaleAnchors(posts: { id: string; content: string }[]) {

View File

@ -9,42 +9,49 @@ datasource db {
}
model Organization {
id String @id @default(uuid())
name String
description String?
apiKey String?
paymentId String?
streakSince DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
allowTrial Boolean @default(false)
isTrailing Boolean @default(false)
shortlink ShortLinkPreference @default(ASK)
autoPost AutoPost[]
Comments Comments[]
credits Credits[]
clippings Clipping[]
customers Customer[]
errors Errors[]
github GitHub[]
Integration Integration[]
media Media[]
buyerOrganization MessagesGroup[]
notifications Notifications[]
plugs Plugs[]
post Post[] @relation("organization")
submittedPost Post[] @relation("submittedForOrg")
sets Sets[]
signatures Signatures[]
subscription Subscription?
tags Tags[]
thirdParty ThirdParty[]
usedCodes UsedCodes[]
users UserOrganization[]
webhooks Webhooks[]
oauthApp OAuthApp[]
oauthAuthorizations OAuthAuthorization[]
id String @id @default(uuid())
name String
description String?
apiKey String?
paymentId String?
streakSince DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
allowTrial Boolean @default(false)
isTrailing Boolean @default(false)
shortlink ShortLinkPreference @default(ASK)
// When true, a USER-level team member's posts are held as a draft
// (Post.pendingApproval) instead of going straight to QUEUE - an
// ADMIN/SUPERADMIN must approve them first. Additive, defaults false so
// every existing organization keeps today's behavior unchanged.
requireApprovalForQueue Boolean @default(false)
evergreenRecycles EvergreenRecycle[]
autoPost AutoPost[]
Comments Comments[]
credits Credits[]
clippings Clipping[]
customers Customer[]
errors Errors[]
github GitHub[]
Integration Integration[]
media Media[]
buyerOrganization MessagesGroup[]
notifications Notifications[]
plugs Plugs[]
post Post[] @relation("organization")
submittedPost Post[] @relation("submittedForOrg")
sets Sets[]
signatures Signatures[]
subscription Subscription?
tags Tags[]
thirdParty ThirdParty[]
usedCodes UsedCodes[]
users UserOrganization[]
webhooks Webhooks[]
oauthApp OAuthApp[]
oauthAuthorizations OAuthAuthorization[]
postEngagementSnapshots PostEngagementSnapshot[]
@@index([apiKey])
@@index([streakSince])
@ -117,6 +124,9 @@ model User {
sendFailureEmails Boolean @default(true)
sendStreakEmails Boolean @default(true)
oauthAuthorizations OAuthAuthorization[]
assignedComments Comments[] @relation("CommentAssignee")
notifications Notifications[]
createdPosts Post[] @relation("PostCreatedBy")
@@unique([email, providerName])
@@index([lastReadNotifications])
@ -365,36 +375,37 @@ model Customer {
}
model Integration {
id String @id @default(cuid())
internalId String
organizationId String
name String
customName String?
picture String?
providerIdentifier String
type String
token String
disabled Boolean @default(false)
tokenExpiration DateTime?
refreshToken String?
profile String?
deletedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime? @updatedAt
inBetweenSteps Boolean @default(false)
refreshNeeded Boolean @default(false)
postingTimes String @default("[{\"time\":120}, {\"time\":400}, {\"time\":700}]")
customInstanceDetails String?
customerId String?
rootInternalId String?
additionalSettings String? @default("[]")
exisingPlugData ExisingPlugData[]
customer Customer? @relation(fields: [customerId], references: [id])
organization Organization @relation(fields: [organizationId], references: [id])
webhooks IntegrationsWebhooks[]
orderItems OrderItems[]
plugs Plugs[]
posts Post[]
id String @id @default(cuid())
internalId String
organizationId String
name String
customName String?
picture String?
providerIdentifier String
type String
token String
disabled Boolean @default(false)
tokenExpiration DateTime?
refreshToken String?
profile String?
deletedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime? @updatedAt
inBetweenSteps Boolean @default(false)
refreshNeeded Boolean @default(false)
postingTimes String @default("[{\"time\":120}, {\"time\":400}, {\"time\":700}]")
customInstanceDetails String?
customerId String?
rootInternalId String?
additionalSettings String? @default("[]")
exisingPlugData ExisingPlugData[]
customer Customer? @relation(fields: [customerId], references: [id])
organization Organization @relation(fields: [organizationId], references: [id])
webhooks IntegrationsWebhooks[]
orderItems OrderItems[]
plugs Plugs[]
posts Post[]
postEngagementSnapshots PostEngagementSnapshot[]
@@unique([organizationId, internalId])
@@index([rootInternalId])
@ -436,12 +447,25 @@ model Comments {
anchorEnd Int?
anchorQuote String?
resolvedAt DateTime?
// Marks the system comment created when a draft is approved from the
// public preview link, so the client/calendar can show an "Approved" trail
// without a separate table. Additive, defaults false for all existing rows.
isApproval Boolean @default(false)
// Resolved user ids picked from the org's team list by the comment author
// (not parsed from free text), so a mention always resolves to a real
// member. Additive, defaults to [] for every existing row.
mentionedUserIds String[] @default([])
// Directs a root comment to one team member for action. Only ever set on
// a root comment (same restriction as resolvedAt) by an authenticated
// team member - the public preview page cannot assign.
assignedToId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
organization Organization @relation(fields: [organizationId], references: [id])
post Post @relation(fields: [postId], references: [id])
user User? @relation(fields: [userId], references: [id])
assignedTo User? @relation("CommentAssignee", fields: [assignedToId], references: [id])
parent Comments? @relation("CommentReplies", fields: [parentId], references: [id])
replies Comments[] @relation("CommentReplies")
@ -452,6 +476,7 @@ model Comments {
@@index([parentId])
@@index([resolvedAt])
@@index([deletedAt])
@@index([assignedToId])
}
model Post {
@ -478,6 +503,18 @@ model Post {
lastMessageId String?
intervalInDays Int?
error String?
// Set on a DRAFT created by a USER-level member while the org has
// requireApprovalForQueue on (see Organization.requireApprovalForQueue).
// Cleared the moment an ADMIN/SUPERADMIN approves (-> QUEUE) or rejects
// (stays DRAFT, cleared so it reads as a normal draft again). Additive,
// defaults false for every existing row.
pendingApproval Boolean @default(false)
// Who saved this post (WEB dashboard only - API/MCP/agent/autopost/bulk
// CSV/evergreen never set it, same additive-optional spirit as every
// other actor column here). Lets an ADMIN/SUPERADMIN approving or
// rejecting a pendingApproval post know, and notify, who submitted it.
// Additive, nullable, defaults null for every existing row.
createdByUserId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
@ -491,7 +528,10 @@ model Post {
childrenPost Post[] @relation("parentPostId")
submittedForOrder Orders? @relation(fields: [submittedForOrderId], references: [id])
submittedForOrganization Organization? @relation("submittedForOrg", fields: [submittedForOrganizationId], references: [id])
createdBy User? @relation("PostCreatedBy", fields: [createdByUserId], references: [id])
tags TagsPosts[]
postEngagementSnapshot PostEngagementSnapshot?
evergreenRecycles EvergreenRecycle[]
@@index([group])
@@index([batchId])
@ -509,6 +549,42 @@ model Post {
@@index([updatedAt])
@@index([releaseURL])
@@index([integrationId])
@@index([pendingApproval])
@@index([createdByUserId])
}
// One row per Post, captured at most once (postId is unique, upserted in
// place) by the bounded daily best-time-to-post batch job - see
// PostEngagementService.captureBatch. This caps total rows at the number of
// posts ever published and caps provider analytics calls to a hard batch
// limit per run, instead of calling providers live on every page view.
// engagementScore is null when the platform returned no usable metrics (no
// postAnalytics capability, or an unavailable/pending release discovered at
// capture time) - those rows exist only to mark the post as permanently
// attempted so it is never re-queued, and are excluded from the aggregation
// in PostEngagementRepository. A transient failure (provider timeout, rate
// limit) does NOT create a row - see captureBatch - so the post stays a
// candidate and is retried on a later run.
// No deletedAt: unlike user-owned content, every row here is derived and
// cheaply re-derivable, so there is nothing to soft-delete/restore.
model PostEngagementSnapshot {
id String @id @default(cuid())
organizationId String
integrationId String
postId String @unique
providerIdentifier String
publishDate DateTime
dayOfWeek Int
hourOfDay Int
engagementScore Float?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
organization Organization @relation(fields: [organizationId], references: [id])
integration Integration @relation(fields: [integrationId], references: [id])
post Post @relation(fields: [postId], references: [id])
@@index([integrationId, dayOfWeek, hourOfDay])
@@index([organizationId])
}
model Notifications {
@ -516,14 +592,20 @@ model Notifications {
organizationId String
content String
link String?
// Targets one member (a mention/assignment/approval ping) instead of the
// whole org. Null keeps today's behavior (visible to every member).
// Additive - every existing row is null and stays org-wide.
userId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
organization Organization @relation(fields: [organizationId], references: [id])
user User? @relation(fields: [userId], references: [id])
@@index([createdAt])
@@index([organizationId])
@@index([deletedAt])
@@index([userId])
}
model MessagesGroup {
@ -663,16 +745,41 @@ model Webhooks {
name String
organizationId String
url String
secret String?
// Event types this webhook wants delivered - see WEBHOOK_EVENT_TYPES.
// Empty means "all events", so every existing webhook keeps firing on
// every event it already fired on (post.published) without a migration.
events String[] @default([])
deletedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
integrations IntegrationsWebhooks[]
deliveries WebhookDelivery[]
organization Organization @relation(fields: [organizationId], references: [id])
@@index([organizationId])
@@index([deletedAt])
}
model WebhookDelivery {
id String @id @default(uuid())
webhookId String
webhook Webhooks @relation(fields: [webhookId], references: [id])
event String @default("post.published")
postId String?
url String
requestBody String
statusCode Int?
success Boolean @default(false)
attempts Int @default(1)
error String?
durationMs Int?
createdAt DateTime @default(now())
@@index([webhookId])
@@index([webhookId, createdAt])
}
model AutoPost {
id String @id @default(uuid())
organizationId String
@ -694,6 +801,35 @@ model AutoPost {
@@index([deletedAt])
}
// Content recycling / evergreen queue: periodically re-publishes a
// still-good post as a brand-new Post (own id/group, own Comments thread),
// so republishing never touches the original's history or stats. Picked up
// by the bounded daily evergreenRecycleWorkflow batch - see
// EvergreenService.getDue.
model EvergreenRecycle {
id String @id @default(uuid())
organizationId String
postId String
active Boolean @default(true)
intervalDays Int
// Caps total republishes so an evergreen entry doesn't run forever by
// accident; null means unlimited.
maxRecycles Int?
totalRecycles Int @default(0)
lastRecycledAt DateTime?
nextRecycleAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
organization Organization @relation(fields: [organizationId], references: [id])
post Post @relation(fields: [postId], references: [id])
@@index([organizationId])
@@index([postId])
@@index([active, nextRecycleAt])
@@index([deletedAt])
}
model Sets {
id String @id @default(uuid())
organizationId String
@ -1817,6 +1953,8 @@ enum CreationMethod {
API
AUTOPOST
CLI
BULK_CSV
RECYCLE
}
enum ShortLinkPreference {

View File

@ -2,10 +2,16 @@ import { PrismaRepository } from '@gitroom/nestjs-libraries/database/prisma/pris
import { Injectable } from '@nestjs/common';
import { WebhooksDto } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
import { v4 as uuidv4 } from 'uuid';
import { randomBytes } from 'crypto';
const DELIVERIES_PAGE_SIZE = 25;
@Injectable()
export class WebhooksRepository {
constructor(private _webhooks: PrismaRepository<'webhooks'>) {}
constructor(
private _webhooks: PrismaRepository<'webhooks'>,
private _webhookDeliveries: PrismaRepository<'webhookDelivery'>
) {}
getTotal(orgId: string) {
return this._webhooks.model.webhooks.count({
@ -22,7 +28,14 @@ export class WebhooksRepository {
organizationId: orgId,
deletedAt: null,
},
include: {
select: {
id: true,
name: true,
url: true,
secret: true,
events: true,
createdAt: true,
updatedAt: true,
integrations: {
select: {
integration: {
@ -51,19 +64,31 @@ export class WebhooksRepository {
}
async createWebhook(orgId: string, body: WebhooksDto) {
const webhookId = body.id || uuidv4();
const existing = body.id
? await this._webhooks.model.webhooks.findFirst({
where: { id: webhookId, organizationId: orgId },
select: { id: true },
})
: null;
const { id } = await this._webhooks.model.webhooks.upsert({
where: {
id: body.id || uuidv4(),
id: webhookId,
organizationId: orgId,
},
create: {
id: webhookId,
organizationId: orgId,
url: body.url,
name: body.name,
events: body.events || [],
secret: randomBytes(32).toString('hex'),
},
update: {
url: body.url,
name: body.name,
events: body.events || [],
},
});
@ -82,6 +107,103 @@ export class WebhooksRepository {
},
});
return { id };
// Only surface the signing secret the moment it's generated (new webhook).
// Existing webhooks keep their secret private; use regenerateSecret to rotate it.
if (existing) {
return { id };
}
const created = await this._webhooks.model.webhooks.findFirst({
where: { id, organizationId: orgId },
select: { id: true, secret: true },
});
return { id, secret: created?.secret };
}
async regenerateSecret(orgId: string, id: string) {
const secret = randomBytes(32).toString('hex');
await this._webhooks.model.webhooks.update({
where: {
id,
organizationId: orgId,
},
data: { secret },
});
return { secret };
}
async getWebhookForOrg(orgId: string, id: string) {
return this._webhooks.model.webhooks.findFirst({
where: {
id,
organizationId: orgId,
deletedAt: null,
},
});
}
async getDeliveries(orgId: string, webhookId: string, page = 1) {
const webhook = await this.getWebhookForOrg(orgId, webhookId);
if (!webhook) {
return { total: 0, deliveries: [] };
}
const [total, deliveries] = await Promise.all([
this._webhookDeliveries.model.webhookDelivery.count({
where: { webhookId },
}),
this._webhookDeliveries.model.webhookDelivery.findMany({
where: { webhookId },
orderBy: { createdAt: 'desc' },
skip: (Math.max(page, 1) - 1) * DELIVERIES_PAGE_SIZE,
take: DELIVERIES_PAGE_SIZE,
select: {
id: true,
event: true,
postId: true,
url: true,
statusCode: true,
success: true,
attempts: true,
error: true,
durationMs: true,
createdAt: true,
},
}),
]);
return { total, deliveries };
}
async getDeliveryForRedelivery(orgId: string, deliveryId: string) {
const delivery = await this._webhookDeliveries.model.webhookDelivery.findFirst({
where: { id: deliveryId },
include: { webhook: true },
});
if (!delivery || delivery.webhook.organizationId !== orgId || delivery.webhook.deletedAt) {
return null;
}
return delivery;
}
createDelivery(data: {
webhookId: string;
event: string;
postId?: string;
url: string;
requestBody: string;
statusCode?: number;
success: boolean;
attempts: number;
error?: string;
durationMs: number;
}) {
return this._webhookDeliveries.model.webhookDelivery.create({
data,
});
}
}

View File

@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { WebhooksRepository } from '@gitroom/nestjs-libraries/database/prisma/webhooks/webhooks.repository';
import { WebhooksDto } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
import { createHmac, timingSafeEqual } from 'crypto';
@Injectable()
export class WebhooksService {
@ -10,15 +11,152 @@ export class WebhooksService {
return this._webhooksRepository.getTotal(orgId);
}
// Includes the raw signing secret - for internal use (delivery) only.
// Controllers must use getWebhooksForDisplay instead.
getWebhooks(orgId: string) {
return this._webhooksRepository.getWebhooks(orgId);
}
async getWebhooksForDisplay(orgId: string) {
const webhooks = await this._webhooksRepository.getWebhooks(orgId);
// The signing secret is only ever surfaced right after it's (re)generated;
// the list view only needs to know whether one exists.
return webhooks.map(({ secret, ...webhook }) => ({
...webhook,
hasSecret: !!secret,
}));
}
createWebhook(orgId: string, body: WebhooksDto) {
return this._webhooksRepository.createWebhook(orgId, body);
}
regenerateSecret(orgId: string, id: string) {
return this._webhooksRepository.regenerateSecret(orgId, id);
}
deleteWebhook(orgId: string, id: string) {
return this._webhooksRepository.deleteWebhook(orgId, id);
}
async getDeliveries(orgId: string, webhookId: string, page = 1) {
return this._webhooksRepository.getDeliveries(orgId, webhookId, page);
}
async redeliver(orgId: string, deliveryId: string) {
const delivery = await this._webhooksRepository.getDeliveryForRedelivery(
orgId,
deliveryId
);
if (!delivery) {
return null;
}
return this.sendWithRetry({
webhookId: delivery.webhookId,
url: delivery.webhook.url,
secret: delivery.webhook.secret,
event: delivery.event,
postId: delivery.postId || undefined,
requestBody: delivery.requestBody,
});
}
/**
* Signs and delivers a webhook payload, retrying transient failures with
* backoff, and always persists the outcome to the delivery log.
*/
async sendWithRetry(params: {
webhookId: string;
url: string;
secret?: string | null;
event: string;
postId?: string;
requestBody: string;
dispatcher?: unknown;
maxAttempts?: number;
}) {
const { webhookId, url, secret, event, postId, requestBody, dispatcher } =
params;
const maxAttempts = params.maxAttempts ?? 3;
const started = Date.now();
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'X-Postiz-Event': event,
};
if (secret) {
headers['X-Postiz-Signature'] = this.sign(secret, requestBody);
}
let lastStatusCode: number | undefined;
let lastError: string | undefined;
let success = false;
let attempt = 0;
for (attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const response = await fetch(url, {
method: 'POST',
headers,
body: requestBody,
// @ts-ignore — undici dispatcher option, not in lib.dom fetch types
...(dispatcher ? { dispatcher } : {}),
});
lastStatusCode = response.status;
// 2xx = delivered. 4xx (other than 429) is a client-side rejection
// that a retry won't fix, so don't burn attempts on it.
if (response.status >= 200 && response.status < 300) {
success = true;
break;
}
if (
response.status < 500 &&
response.status !== 429 &&
response.status !== 408
) {
lastError = `Received HTTP ${response.status}`;
break;
}
lastError = `Received HTTP ${response.status}`;
} catch (err) {
lastError = err instanceof Error ? err.message : 'Unknown delivery error';
}
if (attempt < maxAttempts) {
await new Promise((resolve) =>
setTimeout(resolve, 500 * Math.pow(3, attempt - 1))
);
}
}
await this._webhooksRepository.createDelivery({
webhookId,
event,
postId,
url,
requestBody,
statusCode: lastStatusCode,
success,
attempts: Math.min(attempt, maxAttempts),
error: success ? undefined : lastError,
durationMs: Date.now() - started,
});
return { success, statusCode: lastStatusCode, attempts: attempt };
}
sign(secret: string, body: string): string {
return `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`;
}
verifySignature(secret: string, body: string, signature: string): boolean {
const expected = Buffer.from(this.sign(secret, body));
const provided = Buffer.from(signature);
if (expected.length !== provided.length) {
return false;
}
return timingSafeEqual(expected, provided);
}
}

View File

@ -1,4 +1,6 @@
import {
ArrayMaxSize,
IsArray,
IsBoolean,
IsInt,
IsOptional,
@ -48,9 +50,48 @@ export class CreatePublicCommentDto extends AddCommentDto {
@IsOptional()
@IsString()
recaptchaToken?: string;
// Resolved team-member user ids picked from a mention picker - only
// honored when the comment is created by an authenticated team member
// (userId set), never from the public no-auth preview link. See
// PostsService.createPublicComment.
@IsOptional()
@IsArray()
@ArrayMaxSize(20)
@IsString({ each: true })
mentions?: string[];
// Directs this root comment to one team member. Same authenticated-only
// restriction as mentions above.
@IsOptional()
@IsString()
assignedToId?: string;
}
export class ResolveCommentDto {
@IsBoolean()
resolved: boolean;
}
export class AssignCommentDto {
// Empty string/undefined clears the assignment.
@IsOptional()
@IsString()
assignedToId?: string;
}
export class ApprovePostDto {
@IsOptional()
@IsString()
postId?: string;
@IsOptional()
@IsString()
@MinLength(1)
@MaxLength(80)
displayName?: string;
@IsOptional()
@IsString()
recaptchaToken?: string;
}

View File

@ -0,0 +1,46 @@
import {
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsDefined,
IsString,
} from 'class-validator';
// Caps match the dashboard's own bulk-schedule limit (BulkScheduleDto) -
// same "don't let one request block the event loop for minutes" reasoning.
const MAX_BULK_CREATE = 25;
const MAX_BULK_IDS = 50;
// Each entry is the exact same shape the single `POST /posts` body takes
// (type/date/tags/posts[]) - validated per-item downstream by the same
// validatePosts/mapTypeToPost pipeline the single endpoint uses, not
// re-specified here, so the two never drift.
export class BulkCreatePostsDto {
@IsDefined()
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(MAX_BULK_CREATE)
posts: any[];
}
export class BulkPostIdsDto {
@IsDefined()
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(MAX_BULK_IDS)
@IsString({ each: true })
ids: string[];
}
export interface BulkCreateResult {
index: number;
success: boolean;
postId?: string;
error?: string;
}
export interface BulkDeleteResult {
id: string;
success: boolean;
error?: string;
}

View File

@ -0,0 +1,60 @@
import {
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsBoolean,
IsDateString,
IsDefined,
IsOptional,
IsString,
Validate,
ValidateNested,
} from 'class-validator';
import { Transform, Type } from 'class-transformer';
import { ValidContent } from '@gitroom/helpers/utils/valid.images';
import { sanitizePostContent } from '@gitroom/helpers/utils/sanitize.post.content';
import { Integration } from '@gitroom/nestjs-libraries/dtos/posts/create.post.dto';
// Bulk CSV scheduling only supports a bare date + content per row (no media,
// no per-provider settings), the same intentional scope Buffer's own bulk
// upload ships with. See providerNeedsSettings() for which providers can
// actually accept that.
export class BulkScheduleRowDto {
@IsDefined()
@IsDateString()
date: string;
@IsDefined()
@IsString()
@Validate(ValidContent)
@Transform(({ value }) => sanitizePostContent(value))
content: string;
}
const MAX_ROWS_PER_UPLOAD = 100;
export class BulkScheduleDto {
@IsDefined()
@Type(() => Integration)
@ValidateNested()
integration: Integration;
@IsOptional()
@IsBoolean()
shortLink?: boolean;
@IsDefined()
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(MAX_ROWS_PER_UPLOAD)
@Type(() => BulkScheduleRowDto)
@ValidateNested({ each: true })
posts: BulkScheduleRowDto[];
}
export interface BulkScheduleRowResult {
row: number;
success: boolean;
postId?: string;
error?: string;
}

View File

@ -0,0 +1,28 @@
import {
IsBoolean,
IsInt,
IsOptional,
Max,
Min,
} from 'class-validator';
export class CreateEvergreenRecycleDto {
// How many days after the last recycle (or after creation, for the first
// run) before this post is republished again.
@IsInt()
@Min(1)
@Max(365)
intervalDays: number;
// Unlimited if omitted - see Organization.EvergreenRecycle.maxRecycles.
@IsOptional()
@IsInt()
@Min(1)
@Max(1000)
maxRecycles?: number;
}
export class UpdateEvergreenRecycleDto {
@IsBoolean()
active: boolean;
}

View File

@ -0,0 +1,42 @@
import {
providerNeedsSettings,
simpleTextProviders,
} from './all.providers.settings';
describe('providerNeedsSettings', () => {
it('returns false for providers backed by EmptySettings (no extra config)', () => {
expect(providerNeedsSettings('threads')).toBe(false);
expect(providerNeedsSettings('mastodon')).toBe(false);
expect(providerNeedsSettings('bluesky')).toBe(false);
expect(providerNeedsSettings('telegram')).toBe(false);
expect(providerNeedsSettings('nostr')).toBe(false);
expect(providerNeedsSettings('vk')).toBe(false);
});
it('returns true for providers with a real settings DTO', () => {
expect(providerNeedsSettings('reddit')).toBe(true);
expect(providerNeedsSettings('pinterest')).toBe(true);
expect(providerNeedsSettings('youtube')).toBe(true);
expect(providerNeedsSettings('facebook')).toBe(true);
});
it('returns false for an unknown provider identifier', () => {
expect(providerNeedsSettings('not-a-real-provider')).toBe(false);
});
});
describe('simpleTextProviders', () => {
it('lists exactly the providers that need no extra settings', () => {
const list = simpleTextProviders();
expect(list.sort()).toEqual(
['threads', 'mastodon', 'bluesky', 'telegram', 'nostr', 'vk'].sort()
);
});
it('never includes a provider that needs real settings', () => {
const list = simpleTextProviders();
expect(list).not.toContain('reddit');
expect(list).not.toContain('pinterest');
expect(list).not.toContain('facebook');
});
});

View File

@ -114,3 +114,20 @@ export class EmptySettings {
})
__type: string;
}
// A provider "needs settings" when `allProviders()` (called without a
// fallback) lists a real settings DTO for it; providers backed by
// `EmptySettings` (threads, mastodon, bluesky, telegram, nostr, vk) don't
// need anything beyond `__type`. Bulk CSV import only has a bare
// date/content per row, so it can only safely target those providers —
// this is the single, generic, data-driven source of truth for that check,
// never a hardcoded per-provider branch.
export const providerNeedsSettings = (providerIdentifier: string): boolean => {
return allProviders().some((p) => p.name === providerIdentifier);
};
export const simpleTextProviders = (): string[] => {
return allProviders(EmptySettings)
.map((p) => p.name)
.filter((name) => !providerNeedsSettings(name));
};

View File

@ -0,0 +1,6 @@
import { IsBoolean } from 'class-validator';
export class ApprovalForQueueDto {
@IsBoolean()
requireApprovalForQueue: boolean;
}

View File

@ -0,0 +1,95 @@
import http from 'node:http';
import { getSsrfSafeAxios } from './ssrf.safe.dispatcher';
// #2220: AxiosError carries the full request config - including
// Authorization/Cookie/etc headers - on error.config and in
// error.toJSON(). getSsrfSafeAxios() is the shared instance every social
// provider uses for outbound calls (Moltbook and friends), so a generic
// redaction there protects every provider, not just the one that happened
// to get reported. These tests hit a closed local port (no real network)
// and assert the thrown AxiosError never carries the secret header value.
describe('getSsrfSafeAxios error redaction', () => {
async function findClosedPort(): Promise<number> {
const server = http.createServer();
await new Promise<void>((resolve) => server.listen(0, resolve));
const port = (server.address() as { port: number }).port;
await new Promise<void>((resolve) => server.close(() => resolve()));
return port; // now closed - connecting to it fails fast with ECONNREFUSED
}
it('redacts the Authorization header on a request failure', async () => {
expect.assertions(2);
const port = await findClosedPort();
const axiosInstance = getSsrfSafeAxios();
try {
await axiosInstance.get(`http://127.0.0.1:${port}/posts`, {
headers: { Authorization: 'Bearer super-secret-moltbook-key' },
});
} catch (err: any) {
expect(err.config?.headers?.Authorization).toBe('[redacted]');
// AxiosError#toJSON() is the standard shape error loggers/Sentry/activity
// failure records serialize - its `config.headers` must be redacted too.
const asJson = err.toJSON ? err.toJSON() : err;
expect(asJson.config?.headers?.Authorization).toBe('[redacted]');
}
});
it('redacts Cookie and X-Api-Key headers too, case-insensitively', async () => {
expect.assertions(2);
const port = await findClosedPort();
const axiosInstance = getSsrfSafeAxios();
try {
await axiosInstance.get(`http://127.0.0.1:${port}/posts`, {
headers: {
cookie: 'session=super-secret-session',
'X-Api-Key': 'super-secret-api-key',
},
});
} catch (err: any) {
expect(err.config?.headers?.cookie).toBe('[redacted]');
expect(err.config?.headers?.['X-Api-Key']).toBe('[redacted]');
}
});
it('leaves non-sensitive headers untouched', async () => {
expect.assertions(1);
const port = await findClosedPort();
const axiosInstance = getSsrfSafeAxios();
try {
await axiosInstance.get(`http://127.0.0.1:${port}/posts`, {
headers: { 'Content-Type': 'application/json' },
});
} catch (err: any) {
expect(err.config?.headers?.['Content-Type']).toBe('application/json');
}
});
describe('with DISABLE_SSRF_PROTECTION=true (self-hosted private-network opt-out)', () => {
const original = process.env.DISABLE_SSRF_PROTECTION;
beforeEach(() => {
process.env.DISABLE_SSRF_PROTECTION = 'true';
});
afterEach(() => {
process.env.DISABLE_SSRF_PROTECTION = original;
});
it('still redacts the Authorization header on the plain axios fallback', async () => {
expect.assertions(1);
const port = await findClosedPort();
const axiosInstance = getSsrfSafeAxios();
try {
await axiosInstance.get(`http://127.0.0.1:${port}/posts`, {
headers: { Authorization: 'Bearer super-secret-moltbook-key' },
});
} catch (err: any) {
expect(err.config?.headers?.Authorization).toBe('[redacted]');
}
});
});
});

View File

@ -61,6 +61,55 @@ const ssrfSafeAxios = axios.create({
} as https.AgentOptions),
});
// A separate plain instance (not the module-level `axios` default) so the
// error-redaction interceptor below is scoped to callers of
// getSsrfSafeAxios(), not every unrelated `axios` import in the codebase.
const plainAxios = axios.create();
// Every provider authenticates these outbound calls with a header
// (Authorization: Bearer <token>, Cookie, X-Api-Key, ...). AxiosError keeps
// the full request config - headers included - on `error.config` and in
// `error.toJSON()`. Any call site that forgets to catch-and-sanitize before
// the error reaches a log, Sentry, or an activity failure record leaks that
// credential in plaintext (see #2220, the Moltbook API key leak). Redacting
// here, on the shared axios instances every provider gets from
// getSsrfSafeAxios(), closes the leak generically instead of relying on each
// provider's call sites to remember to do it themselves.
const SENSITIVE_HEADER_NAMES = new Set([
'authorization',
'cookie',
'set-cookie',
'proxy-authorization',
'x-api-key',
'api-key',
'x-auth-token',
]);
function redactSensitiveHeaders(headers: unknown): void {
if (!headers || typeof headers !== 'object') return;
for (const key of Object.keys(headers as Record<string, unknown>)) {
if (SENSITIVE_HEADER_NAMES.has(key.toLowerCase())) {
(headers as Record<string, unknown>)[key] = '[redacted]';
}
}
}
// Mutates error.config.headers in place rather than cloning: nothing in this
// codebase retries a request by reusing a failed call's error.config (every
// retry path - this.fetch, runStreamedUpload - rebuilds its own headers from
// scratch), so this is safe today. If that ever changes, a retry reusing
// error.config would send the literal string '[redacted]' instead of the
// real credential - don't build retry logic on top of a caught error's config.
function redactAxiosError(error: unknown) {
if (error && typeof error === 'object') {
redactSensitiveHeaders((error as { config?: { headers?: unknown } }).config?.headers);
}
return Promise.reject(error);
}
ssrfSafeAxios.interceptors.response.use(undefined, redactAxiosError);
plainAxios.interceptors.response.use(undefined, redactAxiosError);
// Self-hosters legitimately connect Postiz to WordPress/Mastodon/Lemmy/Listmonk
// instances that live on a private network (e.g. the same Docker network or VPC).
// Setting DISABLE_SSRF_PROTECTION=true opts those deployments out of the IP
@ -72,5 +121,7 @@ export function getSsrfSafeDispatcher(): Agent | undefined {
}
export function getSsrfSafeAxios(): AxiosInstance {
return process.env.DISABLE_SSRF_PROTECTION === 'true' ? axios : ssrfSafeAxios;
return process.env.DISABLE_SSRF_PROTECTION === 'true'
? plainAxios
: ssrfSafeAxios;
}

View File

@ -1,7 +1,21 @@
import { IsDefined, IsOptional, IsString, IsUrl } from 'class-validator';
import {
IsArray,
IsDefined,
IsIn,
IsNumberString,
IsOptional,
IsString,
IsUrl,
} from 'class-validator';
import { Type } from 'class-transformer';
import { IsSafeWebhookUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
// Every event a webhook can subscribe to. A webhook with an empty `events`
// array (the default - every webhook created before this list existed)
// still gets everything, see WebhooksService / sendWithRetry callers.
export const WEBHOOK_EVENT_TYPES = ['post.published', 'post.failed'] as const;
export type WebhookEventType = (typeof WEBHOOK_EVENT_TYPES)[number];
export class WebhooksIntegrationDto {
@IsString()
@IsDefined()
@ -27,6 +41,12 @@ export class WebhooksDto {
@Type(() => WebhooksIntegrationDto)
@IsDefined()
integrations: WebhooksIntegrationDto[];
// Empty/omitted = every event (backward compatible default).
@IsOptional()
@IsArray()
@IsIn(WEBHOOK_EVENT_TYPES, { each: true })
events?: WebhookEventType[];
}
export class OnlyURL {
@ -40,6 +60,12 @@ export class OnlyURL {
url: string;
}
export class DeliveriesPageDto {
@IsOptional()
@IsNumberString()
page?: string;
}
export class UpdateDto {
@IsString()
@IsDefined()
@ -61,4 +87,9 @@ export class UpdateDto {
@Type(() => WebhooksIntegrationDto)
@IsDefined()
integrations: WebhooksIntegrationDto[];
@IsOptional()
@IsArray()
@IsIn(WEBHOOK_EVENT_TYPES, { each: true })
events?: WebhookEventType[];
}

View File

@ -20,6 +20,7 @@ import { ThreadsProvider } from '@gitroom/nestjs-libraries/integrations/social/t
import { DiscordProvider } from '@gitroom/nestjs-libraries/integrations/social/discord.provider';
import { SlackProvider } from '@gitroom/nestjs-libraries/integrations/social/slack.provider';
import { MastodonProvider } from '@gitroom/nestjs-libraries/integrations/social/mastodon.provider';
import { MastodonCustomProvider } from '@gitroom/nestjs-libraries/integrations/social/mastodon.custom.provider';
import { BlueskyProvider } from '@gitroom/nestjs-libraries/integrations/social/bluesky.provider';
import { LemmyProvider } from '@gitroom/nestjs-libraries/integrations/social/lemmy.provider';
import { InstagramStandaloneProvider } from '@gitroom/nestjs-libraries/integrations/social/instagram.standalone.provider';
@ -75,7 +76,7 @@ export const socialIntegrationList: Array<SocialAbstract & SocialProvider> = [
new SkoolProvider(),
new MeweProvider(),
new TumblrProvider(),
// new MastodonCustomProvider(),
new MastodonCustomProvider(),
];
@Injectable()

View File

@ -156,6 +156,22 @@ export abstract class SocialAbstract {
abstract identifier: string;
maxConcurrentJob = 1;
/**
* Env vars this provider needs (client id/secret, api key, etc) to be
* usable at all. Empty for providers that never need app-level
* credentials (self-hosted instance URL, wallet-based auth, ...).
* Checked generically by missingEnvVars() so a provider with unset
* credentials never gets an OAuth URL built with an empty/`undefined`
* client id (#2238). A provider whose "is this configured" check isn't a
* plain AND of fixed names (for example one that falls back to another
* provider's credentials) overrides missingEnvVars() directly instead.
*/
requiredEnvVars: string[] = [];
missingEnvVars(): string[] {
return this.requiredEnvVars.filter((name) => !process.env[name]);
}
public handleErrors(
body: string,
status: number

View File

@ -14,6 +14,7 @@ import FormDataUpload from 'form-data';
export class DiscordProvider extends SocialAbstract implements SocialProvider {
override maxConcurrentJob = 5; // Discord has generous rate limits for webhook posting
identifier = 'discord';
override requiredEnvVars = ['DISCORD_CLIENT_ID', 'DISCORD_CLIENT_SECRET'];
name = 'Discord';
isBetweenSteps = false;
editor = 'markdown' as const;

View File

@ -20,6 +20,7 @@ import { Tool } from '@gitroom/nestjs-libraries/integrations/tool.decorator';
export class DribbbleProvider extends SocialAbstract implements SocialProvider {
override maxConcurrentJob = 3; // Dribbble has moderate API limits
identifier = 'dribbble';
override requiredEnvVars = ['DRIBBBLE_CLIENT_ID', 'DRIBBBLE_CLIENT_SECRET'];
name = 'Dribbble';
isBetweenSteps = false;
scopes = ['public', 'upload'];

Some files were not shown because too many files have changed in this diff Show More