Commit Graph

458 Commits

Author SHA1 Message Date
Arnas Donauskas
c3dde01229
chore: add Meta trademark / non-affiliation disclaimer to public footers
Per Meta's brand-use guidance for third-party products, sites that
reference WhatsApp must include a clear non-affiliation disclaimer in
the footer. Adds the standard line:

  "WhatsApp® is a registered trademark of Meta Platforms, Inc.
   Hostinger is not affiliated with, endorsed by, or sponsored by
   Meta Platforms, Inc."

Placed in:
- src/components/landing/footer.tsx — marketing footer (every public
  landing page).
- src/components/docs/shell.tsx — public docs pages had no footer at
  all; added a slim one carrying the same disclaimer.

Out of scope:
- Authed dashboard pages don't have a footer (full-screen workspace
  layout). The trademark-fair-use risk is concentrated on public
  surfaces — crawlers, visitors who haven't signed up, social shares.
  Skipping the dashboard keeps the workspace layout intact and the
  disclaimer where it does the most work.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 12:15:08 +03:00
Arnas Donauskas
e46844d527
chore: add WhatsApp® on first mention across user-facing surfaces
Per Meta's brand-use guidance for third-party products, the registered
trademark symbol (®) should appear on the FIRST mention of "WhatsApp"
on each user-facing page. Subsequent mentions on the same page are
left plain.

Surfaces touched (one-per-page first mention):
- Landing hero badge ("Built on the official WhatsApp® Business API").
- src/lib/seo/site-config.ts: SITE_TAGLINE and SITE_DESCRIPTION
  (rendered into <title> and <meta description> on every page).
- src/app/opengraph-image.tsx: hero text in social-share image.
- Settings, Inbox connection banner, Automations page subtitle.
- README.md tagline.
- All public docs pages (docs/README.md, docs/whatsapp-setup.md,
  docs/getting-started.md, docs/supabase-setup.md,
  docs/environment-variables.md, docs/deployment-hostinger.md,
  docs/automations-and-cron.md, docs/architecture.md,
  docs/troubleshooting.md).

Out of scope: SITE_KEYWORDS (the meta-keywords array isn't
user-rendered text — putting ® on every keyword would look broken in
the meta tag).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 12:13:26 +03:00
Arnas Donauskas
77dfa4f165
chore: switch accent palette to Hostinger violet, drop emerald green
The legal brief on third-party trademark use says: avoid the WhatsApp
teal/green palette and any visual treatment that could read as a
WhatsApp/Meta product. Emerald-500 was used as the primary brand colour
across hero, CTAs, sidebar, charts, badges, and the favicon — close
enough in hue to WhatsApp's signature green to muddy the line.

Swapping to Tailwind violet (which matches the Hostinger brand purple
#7c3aed) makes the visual identity unambiguously ours.

Scope:
- Mechanical Tailwind class swap: emerald-* → violet-* across src/.
- src/app/globals.css: --primary, --ring, --sidebar-primary, --sidebar-ring,
  --chart-1 oklch tokens swapped from emerald (oklch 0.696 0.17 162) to
  Hostinger-aligned violet (oklch 0.526 0.247 293).
- src/app/icon.tsx: favicon background #10b981 → #7c3aed.
- src/app/opengraph-image.tsx: badge bg, accent text, gradient.
- src/components/landing/hero.tsx + cta-banner.tsx: radial-gradient hex.
- src/components/landing/mock/analytics-mock.tsx: marketing chart line.
- src/components/dashboard/conversations-chart.tsx + response-time-chart.tsx:
  "Outgoing" series colour. Distinguishable from "Incoming" blue at a
  glance; we can revisit the chart pair later for stronger colourblind
  contrast (separate concern).
- README.md: license badge colour parameter.

Out of scope:
- src/components/settings/tag-manager.tsx still offers "Emerald" as one
  of the user-pickable contact-tag colours alongside Blue / Yellow / Red
  / etc. — that's a user data choice, not a brand mark.

Contrast check: white text on #7c3aed measures ~4.78:1 (WCAG AA passing
for normal body text). Violet-400 (#a78bfa) on slate-950 measures ~10:1
for accent text, well clear of AA.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 11:57:12 +03:00
Arnas Donauskas
faee4eea44
chore: rename product to "CRM Template for WhatsApp"
Drops the "WaCRM" branded name across user-facing surfaces in favour
of a descriptive name. Branded names that imply WhatsApp ownership or
sponsorship are a trademark fair-use risk; a relationship-based name
("CRM Template for WhatsApp") sidesteps that.

Scope:
- Brand text in nav, sidebar, footer, docs shell, mock window chrome.
- SITE_NAME / SITE_DESCRIPTION / legalName in src/lib/seo/site-config.ts.
- README, CONTRIBUTING, docs/, .github/ templates and policies.
- package.json description.
- Auth pages, settings copy, FAQ, code comments.

Out of scope (intentionally — these are infra renames the project
owner should drive separately so links and the package lockfile stay
consistent):
- The github.com/ArnasDon/wacrm repo URL.
- The wacrm.tech domain / homepage field.
- The package.json "name" field.
- The Hostinger application name and Meta system-user name in deploy
  docs (existing-deployment instructions).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 11:52:11 +03:00
Arnas Donauskas
ea0af2fe3e
Merge pull request #82 from ArnasDon/chore/fix-lint-backlog
ci: clear lint error backlog, drop continue-on-error on lint step
2026-04-21 09:43:15 +03:00
Arnas Donauskas
047b981821
ci: clear lint error backlog, drop continue-on-error on lint step
Fixes the 14 pre-existing lint errors surfaced by React 19's new
hook rules so CI can enforce lint on every PR instead of tolerating
failures. The errors split roughly into three camps:

1) react-hooks/refs — "Cannot access refs during render"
   4 occurrences of the "latest ref" pattern that assigned
   `ref.current = x` during render. Moved each assignment into a
   `useEffect(() => { ref.current = x })` — the canonical React-19
   pattern. Consumers only read `.current` inside async callbacks
   that run after commit, so the very slight delay to the update is
   fine.
   Touched: src/hooks/use-realtime.ts (onMessageRef,
   onConversationRef), src/components/inbox/message-thread.tsx
   (onMessagesLoadedRef), src/components/inbox/conversation-list.tsx
   (onConversationsLoadedRef).

2) react-hooks/set-state-in-effect — genuine issues
   - contacts/page.tsx: the `setPage(0)` on search change moved from
     a useEffect into the `onChange` handler of the search input,
     which is the cleaner pattern anyway.
   - settings/page.tsx: the local `tab` state + sync effect were
     removed entirely; the URL query param is now the single source
     of truth, and the `onChange` handler just calls
     `router.replace(...)`. Simpler and fixes the lint error.

3) react-hooks/set-state-in-effect — false positives for
   load-on-mount and prop-driven sync
   Suppressed per-call (or per-block for effects with many setters)
   with explanatory comments. These effects use setters inside
   async Supabase-query callbacks, not synchronously in the effect
   body, so the cascade the rule warns about doesn't apply. Files:
   contacts/page.tsx, pipelines/page.tsx, pipelines/deal-form.tsx,
   pipelines/pipeline-settings.tsx,
   components/inbox/contact-sidebar.tsx.

4) react-hooks/preserve-manual-memoization — one useCallback
   Rule complained that the inferred dep was `contact` but the
   source dep list was `[contact?.phone]`. Broadened the manual dep
   to `[contact]` to match — callback behaviour is unchanged (it
   still only reads `contact?.phone`), and the React Compiler can
   now preserve the memoization.

And:
  - .github/workflows/ci.yml: dropped `continue-on-error: true` on
    the lint step. Lint now blocks merge on any new error.

Verified: `npm run lint` → 0 errors (24 warnings remain; all
pre-existing unused-import / missing-dep / <img> warnings that don't
fail CI). `npm run typecheck` clean. Landing, /docs, /login, and
/settings redirects all still respond correctly from the dev server.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 22:28:35 +03:00
Arnas Donauskas
93158f4b82
Merge pull request #81 from ArnasDon/docs/readme-arch-alt-hosts
docs: README polish + architecture
2026-04-20 21:52:48 +03:00
Arnas Donauskas
a9df9cd3bf
docs: drop alternative-hosts page, keep Hostinger as the only path
The template is about shipping on Hostinger. Offering Vercel / Railway
/ raw VPS / Docker alongside it blurs that story and creates support
surface for hosts we don't actually test against.

- Delete docs/deployment-alternatives.md.
- README Deploy list drops the "Alternative hosts" bullet.
- docs/README.md reading-order drops step 6 and renumbers.
- docs/architecture.md drops its trailing "Next step" pointer to
  the removed page.
- src/lib/docs/content.ts drops the deployment-alternatives entry;
  remaining pages renumbered to 5..8.

Verified: /docs sidebar now lists 8 pages,
/docs/deployment-alternatives → 404.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 21:51:10 +03:00
Arnas Donauskas
7cd0f46369
docs: README polish + architecture + alt hosts
Finishes the template-readiness sequence. All docs — nothing runtime.

README.md
  Rewrites the landing page of the repo to actually sell what it is
  to someone finding the repo cold on GitHub search.
  - Shields.io badges: MIT, CI status, Next.js 16, Supabase, GitHub
    stars.
  - "What you get out of the box" bullet list — inbox, contacts,
    pipelines, broadcasts, automations, dashboard, account
    management — so the feature surface is visible before the reader
    scrolls.
  - "Why fork this?" section: full ownership, full customisation,
    zero ops to start, real security primitives. Frames WaCRM as a
    template, not an SDK.
  - Docs section reorganised into Setup / Deploy / Reference to
    match the in-app /docs viewer and docs/README.md.
  - Contributing section rewrites the stale "Pull requests welcome"
    line to match the fork-first framing from PR #73.

docs/architecture.md  (new)
  One-page tour for forkers: stack table, full folder layout,
  two ASCII request-lifecycle diagrams (inbound webhook + outbound
  send), security primitives rundown, and a "where to change things"
  index that maps common customisation tasks to source files. This
  is the thing I wish I'd had the first time I opened a forked
  template.

docs/deployment-alternatives.md  (new)
  Short blocks for Vercel, Railway, raw VPS, and Docker. Each covers
  env-var setup, cron strategy (Vercel cron without custom headers
  is a footgun worth calling out), and trade-offs. Keeps Hostinger
  as the primary recommendation — this page is for people whose
  constraints rule it out.

docs/README.md
  - Reading order grouped as Setup / Deploy / Reference, adding the
    two new pages.
  - Stack-at-a-glance updated: encryption is AES-256-GCM, not CBC
    (the PR #71 change that earlier docs hadn't caught up to).

src/lib/docs/content.ts
  Registers the two new markdown files in the ORDER map so they
  appear in the in-app /docs sidebar under the Reference section,
  with prev/next pagination wiring.

Verified: /docs, /docs/architecture, /docs/deployment-alternatives,
and /docs/getting-started all return 200 from the dev server.
Sidebar shows 9 pages grouped Setup / Deploy / Reference with the
new entries. Typecheck clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 21:43:42 +03:00
dependabot[bot]
59be9c740b
chore(deps): bump @base-ui/react from 1.4.0 to 1.4.1
Bumps [@base-ui/react](https://github.com/mui/base-ui/tree/HEAD/packages/react) from 1.4.0 to 1.4.1.
- [Release notes](https://github.com/mui/base-ui/releases)
- [Changelog](https://github.com/mui/base-ui/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mui/base-ui/commits/v1.4.1/packages/react)

---
updated-dependencies:
- dependency-name: "@base-ui/react"
  dependency-version: 1.4.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-20 18:36:41 +00:00
dependabot[bot]
869222aef3
chore(deps-dev): bump typescript from 5.9.3 to 6.0.3
Bumps [typescript](https://github.com/microsoft/TypeScript) from 5.9.3 to 6.0.3.
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Commits](https://github.com/microsoft/TypeScript/compare/v5.9.3...v6.0.3)

---
updated-dependencies:
- dependency-name: typescript
  dependency-version: 6.0.3
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-20 18:36:29 +00:00
dependabot[bot]
46bf366660
chore(deps-dev): bump @types/node from 20.19.39 to 25.6.0
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 20.19.39 to 25.6.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.6.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-20 18:36:19 +00:00
dependabot[bot]
ee7f7a8916
chore(deps): bump actions/setup-node from 4 to 6
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4 to 6.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-20 18:35:36 +00:00
dependabot[bot]
d8b6b86525
chore(deps): bump actions/checkout from 4 to 6
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-20 18:35:35 +00:00
Arnas Donauskas
9c25971c27
Merge pull request #73 from ArnasDon/chore/contributor-experience
chore: fork-first contributor docs + housekeeping
2026-04-20 21:34:52 +03:00
Arnas Donauskas
45574ec7ee
chore: reframe contributor docs fork-first
WaCRM is a template — users are expected to fork and customise their
own deployment, not to send feature work back upstream. The previous
CONTRIBUTING.md read like a standard collaborative-project onboarding
guide and set the wrong expectation.

Reframed docs:

- CONTRIBUTING.md is now "Using WaCRM". Opens with "fork it and make
  it yours", covers forking + keeping-in-sync commands, explains
  which PRs do tend to land (security, correctness, docs, small
  nits) vs. which belong in a fork (new features, stack swaps,
  opinionated refactors). Keeps the filename so GitHub's built-in
  "Contributing guidelines" link still surfaces it.

- .github/ISSUE_TEMPLATE/feature_request.yml: the intro block now
  tells the forker up front that feature requests usually become
  "build it in your fork", and describes the narrow cases where an
  upstream request is useful.

- .github/ISSUE_TEMPLATE/config.yml: adds a third contact link
  pointing at CONTRIBUTING.md so people see the fork-first framing
  before filing.

- .github/pull_request_template.md: prepends a heads-up that most
  changes belong in the forker's own repo, with a pointer to
  CONTRIBUTING.md.

Nothing else in the PR changes — CoC, Dependabot, EditorConfig,
Prettier configs, issue bug_report.yml, and the package.json changes
are orthogonal to the fork-first framing and stay as-is.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 21:31:50 +03:00
Arnas Donauskas
3799c224d8
chore: contributor experience — CoC, templates, Dependabot, editor configs
Nine paperwork files + one devDep. All support work for a repo that's
about to be public; zero runtime behaviour change.

- CONTRIBUTING.md at root. Dev loop, script reference, PR style, code
  style, review process. Short on prose, long on specifics.
- .github/CODE_OF_CONDUCT.md adopts Contributor Covenant 2.1 by
  reference (no inlined text). Points reports to the maintainer's
  email and GitHub's private flow.
- .github/ISSUE_TEMPLATE/ — structured YAML forms for bug and feature
  reports, plus config.yml that disables blank issues and surfaces
  the security-disclosure + docs links. The bug form asks for
  version, runtime, and logs up front so triage doesn't start with
  a round of "where is it running?".
- .github/pull_request_template.md — short checklist; nudges toward
  typecheck / lint / build before submit without being long enough
  to skip.
- .github/dependabot.yml — weekly npm + github-actions scans,
  grouped so Supabase / @types / dev-only patches batch into single
  PRs instead of six per week. Next / React / Tailwind / eslint-
  config-next are ignored so majors stay manual.
- .editorconfig — LF, UTF-8, 2 spaces, final newline, strip trailing
  whitespace (except in Markdown where trailing spaces are line
  breaks).
- .prettierrc — single quotes + trailing-comma es5, matches the
  plurality quote style in the codebase (336 single vs 236 double
  in imports). Tailwind plugin sorts class names.
- .prettierignore — node_modules, build output, lockfile, migrations.
- package.json adds "format" / "format:check" scripts and pins
  prettier + prettier-plugin-tailwindcss as devDeps.
- package-lock.json refreshed for the new devDeps.

Important: existing source files are NOT reformatted in this PR. 153
files would change if we ran `npm run format`, which would balloon
the diff and make review impossible. The reformat pass is a separate,
deliberate PR.

Typecheck clean; `npx prettier --check` on the new config files
passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 21:16:21 +03:00
Arnas Donauskas
1965075ea2
Merge pull request #72 from ArnasDon/chore/oss-metadata
chore: OSS metadata + LICENSE + SECURITY + complete env example
2026-04-20 20:45:03 +03:00
Arnas Donauskas
bce345ed03
chore: OSS metadata + LICENSE + SECURITY + complete env example
Prep work so the repo is ready to be public. None of this is runtime
code; it's the governance a forker expects on day one.

- LICENSE: MIT at repo root. README already claimed MIT; this makes
  GitHub actually recognise it and show the license badge.

- .github/SECURITY.md: private disclosure path via GitHub Security
  Advisories or email. Spells out scope, safe harbour, and what the
  reporter should expect — so a researcher finds it before they try
  to file a public issue.

- .env.local.example: fleshed out with the three vars it was missing
  — META_APP_SECRET (required, from PR 1), NEXT_PUBLIC_SITE_URL
  (recommended), and AUTOMATION_CRON_SECRET (optional). Grouped as
  Required / Recommended / Optional with a one-line comment per
  entry. Includes the openssl/node generators for the secrets.

- package.json: description, repository, bugs, homepage, keywords,
  license, author, engines.node >=20. No runtime impact; feeds npm
  registry metadata, GitHub's repo sidebar, and prevents forkers from
  silently installing on Node <20 (Next 16's floor).

Typecheck clean; npm install run to refresh the lockfile for the
package.json metadata additions (no dependency changes).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 20:41:14 +03:00
Arnas Donauskas
d6a4677e6c
Merge pull request #71 from ArnasDon/security/encrypt-aes-gcm
security: switch WhatsApp token encryption from AES-CBC to AES-GCM
2026-04-20 20:32:24 +03:00
Arnas Donauskas
e570e1a8f2
security: switch WhatsApp token encryption from AES-CBC to AES-GCM
CBC without a MAC is unauthenticated — anyone who can write rows to
whatsapp_config can flip bits in the stored access_token or
verify_token without the decrypt throwing. You'd silently get garbled
bytes; worst case, if the mutation happens to produce a valid token,
messages go out under a spoofed account. GCM appends a 16-byte
authentication tag; any tampering fails the decrypt.

## What changed

src/lib/whatsapp/encryption.ts
  - encrypt() now emits AES-256-GCM ciphertexts with a 12-byte IV,
    formatted as `<iv>:<ciphertext>:<authTag>` (three colons).
  - decrypt() auto-detects format by splitting on `:`:
      3 parts → GCM, validated via auth tag.
      2 parts → legacy CBC, read-only compatibility path.
    Callers are unchanged; same signature, same return type.
  - isLegacyFormat() exposes the format check so hot paths can
    opportunistically upgrade old rows.
  - IV length is validated on decrypt (12 for GCM, 16 for CBC) to
    fail fast on corrupted input.

## Self-healing existing rows

Two call sites opportunistically upgrade a legacy row to GCM after a
successful decrypt — fire-and-forget, no latency impact on the request
path, idempotent under concurrent writes.

  - src/app/api/whatsapp/send/route.ts (hot path)
      After decrypting access_token, if it was CBC, we schedule an
      UPDATE that writes a fresh GCM ciphertext back to the same row.
      The first send after deploy upgrades the token; subsequent
      sends are no-ops because isLegacyFormat returns false.

  - src/app/api/whatsapp/webhook/route.ts (subscribe handshake)
      When a config's verify_token matches the inbound
      hub.verify_token, we upgrade it in place if it was legacy.
      Runs during Meta's webhook re-subscription events, which
      happen on config changes and periodic refreshes.

No schema migration required — the DB column holds whatever string
encrypt() produces. Operators who want to force an upgrade for a
particular user can clear and re-save the WhatsApp settings form.

## Verified (tsx smoke test)
  - GCM roundtrip works (plaintext in → same plaintext out).
  - Legacy CBC decrypt works on 2-part format.
  - isLegacyFormat distinguishes new/legacy correctly.
  - Bit-flipped GCM ciphertext throws on decrypt.
  - Forged auth tag throws on decrypt.
  - Same plaintext produces different ciphertexts across calls
    (IV randomness).

## Rollback

Revert this file. Existing GCM rows would then fail to decrypt
because the previous encrypt.ts has no branch for the 3-part format.
Safer rollback: keep the decrypt branches, revert only the encrypt()
body to CBC — but since GCM roundtrips cleanly and the PR's bug
surface is small (pure crypto utility), a straight revert should only
matter if a forker had time between merging this PR and reverting to
accumulate GCM rows.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 20:25:48 +03:00
Arnas Donauskas
7182abe7d8
Merge pull request #70 from ArnasDon/fix/inbox-messages-stale-after-deeplink
fix(inbox): don't drop messages when ?c= URL param updates
2026-04-20 20:04:32 +03:00
Arnas Donauskas
6cceb81c46
fix(inbox): don't drop messages when ?c= URL param updates
Reports: clicking a conversation sometimes left the message thread
stuck on "No messages yet" until the user hit browser refresh.

Root cause — a three-way race kicked off by any click on a conversation
in the list:

1. handleSelectConversation runs:
      setActiveConversation(B)
      setMessages([])
      router.replace("/inbox?c=B")

2. The URL change flips `deepLinkConvId` (from useSearchParams).
   handleConversationsLoaded is a useCallback with
   [deepLinkConvId], so its identity changes. That cascades into
   ConversationList, whose fetchConversations useCallback has
   [onConversationsLoaded], whose useEffect has [fetchConversations] —
   so the list refetches conversations purely because the URL changed.

3. When the refetch lands, handleConversationsLoaded runs its deep-link
   auto-select branch. autoSelectedForDeepLinkRef still points at its
   previous value (null, or the previous deep-link), so the guard
   `ref !== deepLinkConvId` passes and the branch re-applies B:
      setActiveConversation(B)     // no-op, same id
      setMessages([])              // BLOWS AWAY the messages
                                   // MessageThread just fetched

4. MessageThread's fetch effect only re-runs when conversationId
   changes. B is still B. It does not refetch. Messages stuck at [].

A hard reload unsticks things because state starts from scratch and
the initial deep-link flow is the only path that runs the auto-select.

Three defense-in-depth fixes:

- handleSelectConversation now writes the clicked id into
  autoSelectedForDeepLinkRef BEFORE the router.replace, so by the
  time any downstream refetch lands, the auto-select branch sees
  ref === deepLinkConvId and skips.

- handleConversationsLoaded early-returns if the deep-linked
  conversation is already the active one. This is redundant with
  the ref update above but protects against any other code path
  we don't foresee triggering a refetch.

- ConversationList's fetch is now driven by a plain useEffect with
  [] deps, using a ref for the latest onConversationsLoaded
  callback. URL changes no longer cause a conversations refetch.
  Matches the same stabilisation pattern used in
  src/hooks/use-auth.tsx and src/components/inbox/message-thread.tsx.

Verified: typecheck passes; lint count unchanged (37 pre-existing
problems, zero added). Couldn't exercise the rendered /inbox from the
preview sandbox — it's auth-gated and no test credentials are
available. Please confirm in the authenticated inbox:
  - Click back and forth between two conversations with different
    message histories; messages should populate every time.
  - Open /inbox?c=<id> directly; thread opens with messages.
  - Switch conversations after a deep-link landing; still works.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 20:01:59 +03:00
Arnas Donauskas
460b5bf259
Merge pull request #69 from ArnasDon/security/rate-limit-send-broadcast
security: rate-limit send and broadcast per user
2026-04-20 19:51:01 +03:00
Arnas Donauskas
1f295a831a
security: rate-limit send and broadcast per user
A fork running WaCRM publicly had no server-side guard on the
WhatsApp send endpoints — a compromised session or an aggressive UI
loop could call /api/whatsapp/send or /broadcast as fast as the
network allowed and blow through Meta's per-number quota (or worse,
get the number suspended).

This PR adds a minimal in-memory fixed-window rate limiter keyed by
user id.

Budgets (tuned for a template default — forkers can edit):
  - /api/whatsapp/send      60 per minute per user  (1/s sustained)
  - /api/whatsapp/broadcast  5 per minute per user  (campaign dispatch
                                                    rate, not fan-out)

Behaviour:
  - Check runs right after the Supabase auth check; unauthenticated
    calls 401 as before and never consume a bucket entry.
  - When a user exceeds the budget the route returns 429 with
    Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining,
    X-RateLimit-Reset headers.
  - Send and broadcast buckets are independent; two users are
    independent.

Design trade-off:
  The limiter lives in a process-local Map. On a single Hostinger
  Managed Node.js instance — the template's default deployment —
  that's the whole limit. On a horizontally-scaled deploy (multiple
  regions, serverless fan-out) each instance has its own Map and the
  effective rate is N * limit. Swap src/lib/rate-limit.ts for a
  Redis/Upstash/Durable-Objects backend if you scale past one
  instance; keep the checkRateLimit return shape and the call sites
  don't move.

Memory is self-cleaning: a 1-in-1000 opportunistic sweep drops
expired keys without a background timer, so the Map stays bounded
without running anything outside the request path.

Smoke test (tsx):
  - 7 broadcasts → 5 ok, 2 denied.
  - Different user → independent bucket.
  - Same user, different route → independent bucket.
  - Retry-after = 60s.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 19:48:30 +03:00
Arnas Donauskas
185df34500
Merge pull request #68 from ArnasDon/fix/composer-alignment
fix(inbox): align composer send and template buttons with the textarea
2026-04-20 19:37:28 +03:00
Arnas Donauskas
a90ae1d991
fix(inbox): align composer send and template buttons with the textarea
The \"Type '/' for quick replies\" hint used to live inside the
textarea's flex-1 column. With items-end on the parent row, the
column's height grew by the hint's line box and the buttons aligned
to *that* bottom — sitting one row below the textarea on screen.

Move the hint out to a sibling of the flex row. The row now only
measures the textarea, items-end aligns the buttons level with the
textarea's bottom, and the hint drops neatly below with a pl-11
indent so it stays aligned under the textarea's left edge
(w-9 button + gap-2 = 44px).

Verified structurally via source; the /inbox route itself requires
auth so the preview couldn't exercise the rendered UI. Typecheck
clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 19:35:06 +03:00
Arnas Donauskas
1707aeafb6
Merge pull request #67 from ArnasDon/security/baseline-headers
security: baseline response headers (CSP report-only + OWASP set)
2026-04-20 19:27:11 +03:00
Arnas Donauskas
f199b7a7ed
security: baseline response headers (CSP report-only + OWASP set)
Adds a catch-all rule in next.config.ts that merges a set of baseline
security headers into every response — served alongside the existing
Cache-Control rules, not instead of them.

Enforced today:
  - Strict-Transport-Security: 2yr, includeSubDomains, preload-eligible.
    No-op on http://localhost.
  - X-Content-Type-Options: nosniff
  - X-Frame-Options: DENY  (same defense as frame-ancestors below, but
    older browsers only read this one)
  - Referrer-Policy: strict-origin-when-cross-origin
  - Permissions-Policy: deny camera/mic/geolocation/payment/usb. We
    don't use any of those APIs; closing them off prevents a supply-
    chain compromise or a forgotten plugin from silently enabling them.

Report-only:
  - Content-Security-Policy-Report-Only with a pragmatic allowlist:
      default-src 'self'
      script-src  'self' 'unsafe-inline' 'unsafe-eval'
      style-src   'self' 'unsafe-inline'
      img-src     'self' data: blob: https:
      font-src    'self' data:
      connect-src 'self' https://*.supabase.co wss://*.supabase.co
      frame-ancestors 'none'
      base-uri    'self'
      form-action 'self'
    'unsafe-inline' / 'unsafe-eval' are there because Next's inline
    hydration script + dev-mode require them; nonce-based CSP is a
    later project. Violations appear in the browser console but
    nothing is blocked until we flip the header name to
    `Content-Security-Policy`.

Verified against the running dev server:
  - /, /docs, /login, /api/whatsapp/webhook, /_next/static/* all
    return the six headers.
  - No CSP violations on / or /docs in the browser console.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 19:24:41 +03:00
Arnas Donauskas
fa257e0bd0
Merge pull request #66 from ArnasDon/ci/pr-checks
ci: typecheck + build on every PR
2026-04-20 19:17:30 +03:00
Arnas Donauskas
2f88498080
ci: typecheck + build on every PR
Adds .github/workflows/ci.yml running lint, typecheck, and build on
pull_request + push to main. Node 20 (matches the engines we'll pin
in the metadata PR), npm cache keyed on package-lock.json,
concurrency cancel so force-pushes don't queue runs.

Also adds a `typecheck` script to package.json — `tsc --noEmit`. Next
runs its own typecheck during `build`, but exposing it as a script
means editors and pre-commit hooks can invoke it cheaply, and CI can
surface type errors separately from build errors.

Build passes with dummy env vars (tested locally with .env.local
moved aside); NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY,
and ENCRYPTION_KEY are set to placeholder values inside the workflow.

Lint is wired up but marked continue-on-error for now: the repo has
14 pre-existing errors from React 19's new react-hooks/set-state-in-
effect rule, across 8 files, that are out of scope for this PR. They
still show up in the CI logs so regressions are visible; a follow-up
PR will fix them and drop the non-blocking flag.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 19:09:32 +03:00
Arnas Donauskas
8309b2a95b
Merge pull request #65 from ArnasDon/fix/webhook-fail-closed
fix(webhook): require META_APP_SECRET, fail closed
2026-04-20 18:56:28 +03:00
Arnas Donauskas
be7edfd180
fix(webhook): require META_APP_SECRET, fail closed
The webhook signature verifier used to fall open with a warning log
when META_APP_SECRET was unset — a deliberate soft-rollout choice that
is unsafe for a public template. A forker who forgets the env var
would be running a fully spoofable webhook: anyone knowing the URL
could POST fabricated status updates and drift broadcast counts.

Now:
- `verifyMetaWebhookSignature` returns false when the secret is missing
  and logs at error level, so the route responds 401 to every POST
  until the operator configures it.
- Docs mark META_APP_SECRET as **required**:
  - docs/environment-variables.md lists it under Required, not
    Recommended.
  - docs/whatsapp-setup.md §6 is now "Signature verification (required)".
  - docs/troubleshooting.md updated accordingly.
- .env.local.example lists the var with guidance on where to find it.

Also fixes a pre-existing gitignore bug: `.env*` was swallowing
`.env.local.example`, which meant forkers running
`cp .env.local.example .env.local` from the getting-started guide
hit "no such file". Added a negation for `*.example`.

Upgrade note for existing deploys: set META_APP_SECRET (Meta → App
Settings → Basic → App Secret) before updating, or inbound webhooks
will 401 until it's configured.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 18:54:52 +03:00
Arnas Donauskas
0b8377d2f1
Merge pull request #64 from ArnasDon/feat/profile-management
feat(settings): user profile management
2026-04-20 17:43:27 +03:00
Arnas Donauskas
72a5e4cf70
feat(settings): user profile management
Adds a profile tab to /settings with the five things every B2B SaaS
user expects:

- Display name — edits profiles.full_name.
- Avatar — upload / replace / remove, stored in a new `avatars`
  Supabase Storage bucket with RLS scoped to the owner's folder.
  Migration 008_profile_avatars_storage.sql creates the bucket (public
  read, 2 MB cap, image mimes only) and the four storage.objects
  policies.
- Email — goes through supabase.auth.updateUser({ email }), which
  confirms to both the old and new addresses. UI surfaces a "check
  both inboxes" banner after save.
- Password — three-field form with a current-password gate implemented
  via a throwaway signInWithPassword() before calling updateUser.
- Active sessions — one-click "sign out of all devices" using
  supabase.auth.signOut({ scope: 'global' }), with a confirm dialog.

Plus read-only role, joined date, and user id for operator debugging.

The header avatar and sidebar user row are now both dropdown menus
linking to /settings?tab=profile and /settings?tab=whatsapp; the
settings page reads ?tab= to land on the right tab. useAuth gets a
refreshProfile() callback so the header/sidebar update immediately
after a save without a full reload.

Deferred (separate work): account deletion, 2FA, phone/timezone.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 17:40:39 +03:00
Arnas Donauskas
c2839e6305
Merge pull request #63 from ArnasDon/fix/drop-default-favicon
fix(landing): use WaCRM favicon, drop Next.js default
2026-04-20 09:18:30 +03:00
Arnas Donauskas
fe14d4894f
fix(landing): drop hardcoded shortcut-icon pointing at removed favicon
layout.tsx still had `icons.shortcut: ["/favicon.ico"]`, which kept
emitting the default Next.js favicon link in <head> even after the
file was deleted. icon.tsx is the single source now.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 08:59:24 +03:00
Arnas Donauskas
27479e3ebd
fix(landing): drop leftover next.js favicon.ico
We already have src/app/icon.tsx generating the WaCRM emerald mark,
but the default create-next-app favicon.ico was still in src/app/
so Next.js kept emitting <link rel="shortcut icon" href="/favicon.ico">
in <head>. Browsers prefer the ICO, so tabs still showed the default
Vercel triangle on the landing page.

Removing favicon.ico leaves icon.tsx as the sole source, which is
what the comment in that file already claimed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 08:58:02 +03:00
Arnas Donauskas
f7d576190a
Merge pull request #62 from ArnasDon/chore/require-code-owner-review
chore: require Arnas as reviewer on every PR
2026-04-19 22:22:46 +03:00
Arnas Donauskas
5f3486bb36
chore: require Arnas as reviewer on every PR (CODEOWNERS)
Adds a CODEOWNERS file mapping every path to @ArnasDon so GitHub
auto-requests his review on every PR. Pair with a branch-protection
rule on main that requires Code Owner approval to make review
mandatory before merge.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:09:10 +03:00
Arnas Donauskas
c28e4caa32
Merge pull request #61 from ArnasDon/feat/docs-viewer
feat(docs): in-app docs viewer at /docs
2026-04-19 21:52:27 +03:00
Arnas Donauskas
45fd2a9845
feat(docs): in-app docs viewer at /docs
Renders every file in docs/*.md as a proper documentation site styled
like Stripe / Vercel / Linear docs: sticky header, grouped left sidebar
(Setup / Deploy / Operate), dark prose with inline code pills, syntax
-ready code blocks, responsive table styling, and prev/next pagination.

- src/lib/docs/content.ts — parses md with marked and decorates the
  HTML with Tailwind utility classes via post-processing regex. Also
  rewrites inter-doc `./other.md` links to `/docs/other` and extracts
  an h2/h3 TOC for future use.
- src/app/docs/layout.tsx + src/components/docs/shell.tsx — shared
  frame with docs-scoped header (GitHub, Home, Get started), collapsing
  sidebar on mobile.
- src/app/docs/page.tsx — grouped index cards per section.
- src/app/docs/[slug]/page.tsx — individual doc + prev/next nav.
- Adds "Docs" to landing nav, footer, and a "Read the full
  documentation" CTA under the open-source cards.
- Adds `marked` dependency.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 21:28:36 +03:00
Arnas Donauskas
9fc3eb772b
Merge pull request #60 from ArnasDon/fix/hostinger-managed-nodejs
fix(hostinger): recommend Managed Node.js Hosting, not VPS
2026-04-19 21:03:44 +03:00
Arnas Donauskas
029a20e407
fix(hostinger): recommend Managed Node.js Hosting, not VPS
Swaps the Hostinger recommendation on the landing page and throughout the
docs from VPS to Managed Node.js Hosting
(https://www.hostinger.com/web-apps-hosting).

The deploy walkthrough is rewritten around hPanel's Node.js app flow
(Git-based deploy, env vars panel, AutoSSL, cron via Advanced → Cron Jobs)
instead of a raw Ubuntu VPS with nginx + PM2 + certbot. VPS stays
mentioned at the bottom of the deploy page as an alternative when a
user actually needs one (background workers, custom binaries, etc.).

Also touched:
  - docs/README.md, environment-variables.md, automations-and-cron.md,
    troubleshooting.md to drop VPS-specific assumptions.
  - footer link URL.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 21:02:10 +03:00
Arnas Donauskas
f18adf3b47
Merge pull request #59 from ArnasDon/docs/full-setup-guide
docs: end-to-end self-host setup guide
2026-04-19 20:55:45 +03:00
Arnas Donauskas
02d008b51b
Merge pull request #58 from ArnasDon/feat/landing-open-source-section
feat(landing): open-source + Hostinger deploy section
2026-04-19 20:53:24 +03:00
Arnas Donauskas
7148c209a0
docs: end-to-end self-host setup guide
Adds docs/ with a reading-order flow that covers:
  - getting started (fork, install, run locally)
  - supabase setup + migrations
  - whatsapp business api + webhook wiring
  - environment variable reference
  - hostinger vps deploy walkthrough
  - automations cron scheduling
  - troubleshooting for the common issues

Rewrites the top-level README as a pointer into docs/ instead of the
create-next-app boilerplate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 20:52:08 +03:00
Arnas Donauskas
dd65e532a1
feat(landing): open-source + Hostinger deploy section
Adds a #self-host landing section with two cards — one linking to
the GitHub repo (fork / clone) and one recommending Hostinger VPS
for deploying the template. Also surfaces the GitHub link from the
nav (desktop icon + mobile drawer) and the footer.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 20:45:00 +03:00
Arnas Donauskas
5a2d11ea64
Merge pull request #57 from ArnasDon/fix/broadcasts-table-responsive
feat(mobile): tiered columns on the broadcasts table
2026-04-19 12:59:34 +03:00
Arnas Donauskas
9173e8e4aa
Merge pull request #51 from ArnasDon/feat/mobile-automation-builder
feat(mobile): automation builder fits + flows on narrow screens
2026-04-19 12:58:11 +03:00