Why this matters
An advertising dashboard is only as truthful as its connections to the outside world. If a merchant shop drops a webhook during a brief restart, net revenue quietly drifts away from reality; if an attacker posts a forged order webhook and your endpoint skips raw-body signature verification, fake sales poison both the ledger and ad bidding; and if a web crawler scanning public storefront HTML runs in the same process as your database or encryption vault, one Server-Side Request Forgery bug exposes every customer token.
Integrations are also where real-world friction lives: external platforms enforce strict rate limits, rotate or expire OAuth tokens, gate customer PII behind multi-week partner reviews and retry timed-out deliveries under new headers. This lesson walks through how the repository connects storefronts, verifies and replays webhooks, polls with overlap cursors, enforces rate budgets, closes the CRM conversion loop inside one database transaction, isolates the SEO crawler and keeps account connections healthy.
The ideas
What a connector is and the Release 1 storefront plan (OD-06)
A connector is the translation layer between one external platform and the product canonical data model. Every storefront speaks its own dialect—GraphQL versus REST, Turkish comma decimals versus dot decimals, positive refund adjustments versus negative line strings—so isolating that dialect inside an adapter lets every downstream ledger, margin calculation and attribution report read one uniform order shape (CanonicalUnifiedOrder).
Two hard connector rules apply before a single line of business data moves:
- API version pinning: Every connector declares an exact dated or major revision (such as
2026-10for Shopify,v27.0for Meta Graph API orv26for Google Ads) and rejects floating aliases such aslatestorunstableso a provider cannot break response shapes silently overnight. - Accepted is not done: Receiving
HTTP 202 Acceptedon a bulk export or messaging call proves only that the provider received the request. Orders and deliveries are marked reconciled only after per-record verification or a confirmation status webhook succeeds, and an expired bulk link (HTTP 410) is recorded as unreconciled rather than zero rows.
Owner decision OD-06 (docs/OWNER-DECISIONS.md) sets a realistic Release 1 storefront scope tailored to Turkey commerce ecosystem without letting slower foreign review queues hold back Day-1 launch:
| Storefront / rail | Release plan (OD-06) | Technical interface | Honest status today |
|---|---|---|---|
| ikas | Day 1 native connector | Admin GraphQL v2 + OAuth 2.0 + HMAC webhooks + 15-min overlap polling | Built and verified locally; live partner credentials pending (issue 4) |
| WooCommerce | Day 1 lightweight PHP plugin | HPOS-compatible WordPress plugin (packages/connectors/woocommerce-plugin) capturing click IDs + signed order webhooks | Built and verified locally; no live merchant installs yet |
| Universal JS Snippet | Day 1 universal rail | First-party snippet capturing _fbp, _fbc, gclid, ttclid, _ttp on custom, IdeaSoft, T-Soft and Ticimax sites | Built and verified locally; awaits live domain (OD-01) |
| Ticimax | Day 1 webhook bridge | Merchant admin-panel webhook bridge + Turkish currency parser (avoids legacy SOAP) | Built and verified locally; official Solution Partner app is Release 2 |
| Shopify | Parallel review, unlock on approval | GraphQL 2026-10, Base64 HMAC webhooks, 3 mandatory compliance webhooks behind a rollout gate | Built and verified locally; customer PII forced null until Shopify protected customer data review passes |
| IdeaSoft and T-Soft | Release 2 native apps (Day 1 via snippet) | Order normalisers already written for canonical mapping | Normalisers built; native App Store listings deferred to Release 2 |
Inbound webhooks versus cursor polling: hybrid sync
A webhook is an automated HTTP POST sent by a shop or payment provider the moment an order or refund happens. Because anyone on the internet can send an HTTP request to a webhook URL, every inbound delivery passes four non-negotiable gates before JSON is ever parsed into an order:
- Webhook signature over verbatim raw bytes: Using HMAC-SHA256 (Lesson 05), the server hashes the exact incoming
Buffer—never re-serialised JSON—and compares it withcrypto.timingSafeEqualagainst the provider header (X-Hub-Signature-256,X-Shopify-Hmac-Sha256,x-ikas-signatureorX-IYZ-SIGNATURE-V3). - Size cap and replay window: Payloads above
1 MiB(1,048,576bytes) are dropped immediately, and timestamped requests outside plus or minus300seconds (5 minutes) are rejected withtimestamp_out_of_window. - Deduplication via raw ingest envelopes and the webhook identity triad: Every verified delivery is hashed with SHA-256 and recorded in
raw_ingest_envelopesfor 14 days (capped at 30 days for KVKK minimisation). Crucially, the triad separatesdelivery_id(changes on every provider retry), businessevent_id(stable for the underlying order or refund) andsubscription_id(which webhook registration fired). Deduplicating on business event and payload hash prevents double-counting when a shop retries a slow response under a freshdelivery_id. - Dead letters and single-flight webhook replay: Envelopes that fail parsing or persistence retry under deterministic exponential backoff up to 5 attempts before entering
quarantined_dlq. Once the bug clears, an owner or admin replays onlysignatureVerified === trueenvelopes under a per-workspace single-flight lock so concurrent replays never double-count kuruş totals—and consent-denied or erased contacts are never replayed.
Even with perfect webhook handling, webhooks alone are fragile: ikas, for example, stops retrying a failed delivery after just 3 attempts. That is why the product treats every webhook as a fast wake-up hint and pairs it with scheduled polling from a persistent sync cursor—a pattern called hybrid sync:
Storefront event (order paid / partial refund)
|
+--> [Fast path] Inbound webhook -> raw-body HMAC + 300s replay window
| -> raw_ingest_envelopes dedup -> wake-up hint
|
+--> [Safety net] Scheduled 15-min poll from sync_cursors
-> rewind by 5-min overlap lookback -> fetch authoritative API
-> normalize to integer kurus BigInt -> durable PG ack
-> advance sync_cursor ONLY after ack succeeds (else hold cursor)Notice two critical details in that diagram. First, every poll rewinds the cursor by a 5-minute overlap lookback (300,000 ms on ikas) so orders committed late or stamped with minor clock skew never slip into the gap between polls; idempotent deduplication silently absorbs duplicates. Second, the cursor advances strictly after PostgreSQL acknowledges durable writes (ack_failed_cursor_held on failure), and any repeatedly failing tenant stream enters per-tenant quarantine so healthy tenants continue syncing undisturbed.
Rate budgets, schedules and exact kuruş reconciliation
External APIs enforce very different quotas: Meta reports percentage usage in X-Business-Use-Case-Usage headers, Shopify deducts GraphQL complexity points from a leaky bucket (100 to 1,000 points per second by plan), and ikas enforces short sliding burst windows (40 calls per 10 seconds). Rather than waiting for HTTP 429 bans, a shared rate budget orders every job under three strict priorities:
conversion_events(rank 100): Consented Meta CAPI and Google Data Manager dispatches go first.order_sync(rank 50): Live storefront order and refund syncs come second.catalog_backfill(rank 10): Heavy historical imports yield whenever quota tightens.
Proactive throttling begins slowing lower-priority jobs at 75 percent utilisation on Meta and ikas (and reserves 25 percent of Shopify bucket points away from catalog backfills), parking Meta low-priority work at 95 percent and capping any provider Retry-After header at 60 seconds so an absurd header can never trigger a timer overflow or stall a worker.
Once orders land, the normaliser converts every amount into exact integer kuruş (BigInt)—rejecting IEEE-754 binary floats, rejecting refunds larger than their original order (OVER_REFUND_FORBIDDEN) and keeping unknown product COGS as null rather than zero. Refunds are recorded strictly as append-only rows in order_adjustments, and order reconciliation compares storefront net totals against workspace ledger totals down to the kuruş (drift_kurus) so missing or duplicated orders show up immediately.
Turning an order or deal into feedback: the closed-loop CRM (R7)
As Lesson 07 explains, ad platforms optimise poorly when they only see anonymous clicks or unverified lead forms. A closed-loop CRM links every storefront order and every clinic or WhatsApp lead to a CRM deal (crm_deals) and tracks it across strict deal stages: lead, qualified, appointment_booked, proposal, won, lost and refunded.
Here is where Lesson 03 transactional outbox mechanics protect accuracy and KVKK law simultaneously. When an owner or analyst advances a deal to qualified or won, the server updates crm_deals and inserts pre-hashed conversion payloads into conversion_feedback_queue inside the exact same PostgreSQL FORCE RLS transaction, using a deterministic idempotency key (such as deal:<deal_id>:won:meta_capi_messaging, essential because Meta messaging events have no automatic deduplication). Before the INSERT can commit, PostgreSQL runs trigger enforce_conversion_feedback_consent():
- If the linked contact has
erased_at IS NOT NULL, the trigger aborts immediately—no erased person ever enters the dispatch queue. - If
consent_marketingorconsent_ad_user_datais missing for the destination, feedback is blocked at the database boundary rather than trusting application code alone.
Because the stage update and queue insert share one transaction, a process crash right after clicking "Won" can never leave the deal marked won without its consented conversion queued, nor queue a conversion for a rolled-back update.
The isolated SEO worker (apps/seo-worker, T5 and R8)
Auditing a merchant website requires fetching arbitrary public HTML, /robots.txt and /sitemap.xml over the public internet. Putting that crawler inside the main API or database worker would turn any SSRF or parser flaw into a breach of every tenant database row and OAuth token (T5 in the threat model).
The SEO worker therefore runs in its own isolated Zone 3 process guarded by four walls:
- Zero secrets at startup:
env-guard.tsinspectsprocess.envbefore accepting any job and crashes cleanly withFORBIDDEN_ENV_SECRETifDATABASE_URL,VAULT_*,POSTGRES_*,IYZICO_*,META_APP_SECRET,GOOGLE_ADS_DEVELOPER_TOKEN,SHOPIFY_*orIKAS_CLIENT_SECRETis present. Even a total process compromise yields zero credentials. - Connect-time DNS resolution and IP pinning:
ssrf-guard.tspermits onlyhttp:/https:on ports80and443, resolves DNS at connect time, rejects every private/loopback/link-local/CGNAT/IMDS CIDR (127.0.0.0/8,10.0.0.0/8,169.254.0.0/16,172.16.0.0/12,192.168.0.0/16, IPv6 equivalents and.internal/.localhostnames), pins the exact validated IP on the TCP socket to defeat DNS rebinding, repeats that check on every redirect hop (MAX_REDIRECT_HOPS = 5), caps body size at5 MiBand enforces a 10-second timeout. - Actionable 5-task cap (
R8) and zero fabrication: Each SEO audit checksnoindex,<title>, meta description, canonical URL,H1,lang="tr", mobile viewport, JSON-LD (LocalBusiness/Product), tracking tags (Meta Pixel, Google tag,track.<domain>) and CrUX field speed (falling back honestly topsi_lab_fallbackwhen low-traffic sites lack CrUX). It ranks issues deterministically and caps output at strictly at most five priority SEO tasks (MAX_PRIORITIZED_TASKS = 5). Metrics that require a paid third-party index—search_volume,keyword_difficultyandbacklinks_count—stay strictlynullwithpaid_data_required: true, never guessed or filled with0. - Byte-verified SEO patches: Writing an approved
ikasSEO fix touches only five allow-listed fields (pageTitle,description,slug,canonicals,disableIndex), refuses any payload namingcontent, contentData,blogContent, prices, stocks or publish dates (IKAS_EDITOR_CONTENT_FORBIDDEN), binds the approved copy to a SHA-256revision_hashand verifies UTF-8 bytes withBuffer.equalson read-back so a visual page-builder layout is never wiped.
Account connections, health checks and least-privilege token refresh
An account connection links a workspace to a business own Meta or Google account via OAuth—never by asking for a password—and stores tokens encrypted inside vault.oauth_connections. Keeping those connections alive safely requires three separate jobs:
- Cached connection health: On demand,
ConnectionHealthServicecalls Metadebug_tokenor Googletokeninfoplus account listing, caches healthy answers for 5 minutes and failures for 1 minute (preventing hammering a broken provider), surfaces missing scopes and returnsnull(rendered as a dash) for anything unknown—with zero token material ever returned or logged. - Least-privilege token refresh: Every 15 minutes, the dedicated dispatch process (
apps/api/src/dispatch-main.ts) claims dueoauth_refreshablerows expiring within 24 hours usingFOR UPDATE SKIP LOCKED, exchanges Google refresh tokens or still-valid 60-day Meta long-lived tokens, skips non-expiring Meta system-user tokens (bisu_non_expiring), enforces a 30-minute re-attempt floor and flips unrecoverable connections to needs reauthorisation (needs_reauth) so Screen 4 prompts the owner to reconnect cleanly. - Revoke and crypto-shred: When an owner disconnects an account,
revoke.tsmakes a bounded best-effort provider revoke call (10-second timeout) and always marks the rowrevokedand cryptographically shreds all encrypted token columns locally regardless of whether the provider answered.
How this repository does it
Every file below is verified on disk inside this repository. Note the honest boundary between built local verification and external partner activation.
Not built yet
| Layer | Key repository files | What is built and verified locally |
|---|---|---|
| Webhook auth & normalisation | packages/connectors/src/hmac-verifiers.ts, packages/connectors/src/webhook-normalizer.ts, packages/connectors/src/kimi-v8-guards.ts, apps/api/src/routes/ingest-webhooks.ts | Constant-time raw-body HMAC (Meta, Shopify, ikas, iyzico V3, edge collector), 300-second replay window, 1 MiB cap, identity triad, float & over-refund refusal, 14-day raw_ingest_envelopes |
| Replay, polling & rate budgets | packages/connectors/src/replay-queue.ts, packages/connectors/src/ikas-sync.ts, packages/connectors/src/shopify-adapter.ts, packages/connectors/src/ticimax-adapter.ts, packages/connectors/src/sync-orchestrator.ts, packages/connectors/src/rate-budget.ts, packages/connectors/src/bulk-job-and-manifest.ts | Single-flight DLQ replay (max 5 attempts), 15-min poll with 5-min overlap, Shopify 2026-10 cost throttling & Level 2 rollout gate, Ticimax webhook bridge, priority rate governor (100/50/10), pinned manifests & JSONL reconciliation |
| WooCommerce plugin & snippet | packages/connectors/woocommerce-plugin (PHP file {product}-signals.php) | HPOS-compatible order-meta click capture and signed order webhook sender |
| Delivery health & reconciliation | apps/api/src/routes/developer-webhook-delivery-health.ts, apps/api/src/routes/connectors-order-reconcile.ts | Read-only 5-channel BigInt health matrix (98% HMAC floor, 2%/10% DLQ thresholds, idle dashes) and exact kuruş order reconciliation |
| Closed-loop CRM | packages/db/src/repositories/signals-crm-repo.ts, apps/api/src/routes/crm-create-deal.ts, apps/api/src/routes/connections-crm.ts, docs/schema.sql | Atomic updateCrmDealStageAndEnqueueFeedback, enforce_conversion_feedback_consent() SQL trigger, 409 CONTACT_ERASED check, linear-time PII screen |
| Isolated SEO worker | apps/seo-worker/src/env-guard.ts, apps/seo-worker/src/ssrf-guard.ts, apps/seo-worker/src/live-crawler.ts, apps/seo-worker/src/auditor.ts, apps/seo-worker/src/crux-fallback.ts, apps/seo-worker/src/ikas-seo-patch-policy.ts | Startup secret ban, connect-time DNS/IP-pinned safeFetch, 5-task R8 auditor, CrUX-to-PSI fallback, contentData-safe SHA-256 read-back patching, zero-fabrication paid-data checks |
| OAuth health, refresh & revoke | apps/api/src/connections/health.ts, apps/api/src/connections/refresh.ts, apps/api/src/connections/revoke.ts, apps/api/src/connections/oauth/fake-provider.ts, apps/api/src/dispatch-main.ts | 5-min/1-min cached health, 15-min FOR UPDATE SKIP LOCKED token refresh in vault-isolated dispatch process, unconditional local crypto-shredding on revoke, double production block on test-only fake provider |
What went wrong once
1. The test-only fake provider that production refuses twice (CS-39)
To exercise full Meta and Google OAuth connect, health, refresh, revocation and conversion dispatch end-to-end without live credentials, Wave 47 introduced OAUTH_FAKE_PROVIDER_BASE inside apps/api/src/connections/oauth/fake-provider.ts. It rewrites only four allow-listed HTTPS hosts (graph.facebook.com, oauth2.googleapis.com, googleads.googleapis.com, datamanager.googleapis.com) to a local loopback stub.
A test transport that redirects provider calls to localhost would be catastrophic if an environment variable accidentally leaked into production: every OAuth handshake and CAPI dispatch would silently talk to nothing or a spoofed local port. Because a single config check is easy to miss during a refactor, production enforces two independent boot-time locks—inside runtime config loading and again inside both server.ts and apps/api/src/dispatch-main.ts—immediately zeroising the vault KEK and exiting with OAUTH_FAKE_PROVIDER_FORBIDDEN if OAUTH_FAKE_PROVIDER_BASE is ever set in production.
2. Why token refresh moved out of the general worker (CS-47)
Earlier designs considered running OAuth token refresh inside the API process or the general background worker (apps/api/src/worker-main.ts). During Wave 48 hardening, that architecture failed the least-privilege test: giving the general worker VAULT_DATABASE_URL and the vault master KEK meant every routine background job suddenly sat inside the vault blast radius. Token refresh and signal dispatch were split into one dedicated, least-privilege process—apps/api/src/dispatch-main.ts—using FOR UPDATE SKIP LOCKED so horizontal replicas never double-refresh a token while worker-main.ts stays completely vault-less.
3. Connections held in memory and partial revocation (CS-40)
Early prototype routes stored connected accounts inside an in-process JavaScript Map, which vanished on every server restart and could not coordinate across processes. Moving connections into PostgreSQL vault.oauth_connections fixed durability, and pairing revoke with unconditional cryptographic shredding across all four encrypted token columns in apps/api/src/connections/revoke.ts ensured that even if Meta or Google times out during disconnect, the local ciphertext is destroyed permanently.
4. Strict ingest rejecting one extra collector field (CS-08)
In Wave 45 end-to-end testing, the edge collector forwarded an extra phone_country_code_hash key alongside standard hashed user fields. Because apps/api/src/routes/ingest-webhooks.ts enforces closed Zod .strict() schemas on hashedUserData, ingest refused those batches with HTTP 400, silently dropping events until the collector payload and ingest schema were locked to the exact same key set. Closed schemas catch contract drift immediately—and prove why producer and consumer tests must run together.
Try it yourself
All four steps below run offline and read-only from the repository root without touching ports 3000, 4000 or 5432 or calling external APIs.
Step 1: Run the connector test suite
Verify raw-body HMAC signatures, webhook normalisation, over-refund refusal, rate budgets, single-flight replay, ikas overlap polling, Shopify Level 2 gates and OAuth clients:
cd packages/connectors
npm testStep 2: Run the isolated SEO worker test suite
Verify startup secret refusal (env-guard.ts), DNS-rebinding and private-CIDR SSRF blocks (ssrf-guard.ts), the 5-task auditor (R8), CrUX/PSI fallback and ikas contentData SHA-256 read-back protection:
cd apps/seo-worker
npm testStep 3: Inspect the Zone 3 secret ban and SSRF CIDR protections
See the exact forbidden credential variables and private network ranges enforced before the crawler ever opens a socket:
grep -nE "FORBIDDEN_EXACT_ENV_VARS|FORBIDDEN_ENV_PREFIXES|FORBIDDEN_ENV_SECRET" apps/seo-worker/src/env-guard.ts
grep -nE "MAX_REDIRECT_HOPS|MAX_RESPONSE_BYTES|169, 254|blocked_ssrf" apps/seo-worker/src/ssrf-guard.tsStep 4: Inspect atomic CRM feedback queuing and the double fake-provider production lock
Confirm that updating crm_deals and inserting into conversion_feedback_queue happen inside one withTenantTransaction call, and that dispatch-main.ts refuses OAUTH_FAKE_PROVIDER_BASE in production:
grep -nE "updateCrmDealStageAndEnqueueFeedback|INSERT INTO public\.conversion_feedback_queue|ON CONFLICT" packages/db/src/repositories/signals-crm-repo.ts
grep -nE "OAUTH_FAKE_PROVIDER_FORBIDDEN|FOR UPDATE SKIP LOCKED|DISPATCH_LIVE_ACKNOWLEDGEMENT" apps/api/src/dispatch-main.tsCheck yourself
0 / 6A storefront times out waiting for your webhook response and resends the exact same paid order 20 seconds later with a brand-new delivery_id header. Why is the order not counted twice?
Why does the product run scheduled 15-minute polling with a 5-minute overlap lookback even when ikas webhooks are verified and working?
An attacker submits a storefront URL to the SEO auditor that redirects (HTTP 301) to http://169.254.169.254/latest/meta-data/ to steal cloud metadata or database secrets. Which two layers stop the attack?
Why does updateCrmDealStageAndEnqueueFeedback update crm_deals and insert into conversion_feedback_queue inside one PostgreSQL transaction rather than calling Meta directly inside the HTTP route?
Why does ikas-seo-patch-policy.ts refuse a patch that includes contentData and check read-back bytes with SHA-256?
Why was scheduled OAuth token refresh moved into apps/api/src/dispatch-main.ts using FOR UPDATE SKIP LOCKED instead of running inside apps/api/src/worker-main.ts?
Words to know
36Go deeper
- Operational runbooks & decisions:
Webhook delivery, HMAC & dead-letter runbook,docs/OWNER-DECISIONS.md(OD-06,OD-21, issue 4) anddocs/THREAT-MODEL.md(T5). - Archived wave-by-wave notes:
archived lesson 09,archived lesson 10,archived lesson 25andarchived lesson 29. - External platform documentation: ikas Developer Portal, Shopify GraphQL Rate Limits, Shopify Protected Customer Data, Meta Graph API Rate Limiting, Google Search Central Crawling & Indexing and MDN HTTP 429 & Retry-After.