GetClaps
Ücretsiz DenetimFiyatlandırmaSözlükAkademi
  1. Ana sayfa
  2. /Akademi
  3. /L10 · Integrations: storefronts, webhooks, sync, the CRM loop, the SEO crawler

Ana sayfa / Akademi / L10 · Integrations: storefronts, webhooks, sync, the CRM loop, the SEO crawler

L10Bölüm C · Ürün motorlarıOrtaKod doğrulama tarihi: 2026-12-04

Integrations: storefronts, webhooks, sync, the CRM loop, the SEO crawler

How connectors authenticate webhooks, sync orders safely, close the CRM conversion loop, isolate the SEO crawler, and refresh tokens.

20 dk·3944 kelime·6 soru·36 terim·docs/lessons/10-integrations.md
Ön koşul:L03 · Data: PostgreSQL, tenants, exact money, and doing things exactly onceL05 · Cryptography and secrets: hashing, HMAC, encryption and the vaultL07 · Measurement: events, consent, Meta CAPI, Google Data Manager and KPI math
Tüm derslere dön
●

Ders içerikleri İngilizce yayınlanır (OD-23)

Sayfa çerçevesi Türkçe ve İngilizce olarak sunulur. Teknik ders metinleri, kod örnekleri ve kendini sına soruları doğrudan ortak kaynak dosyalarından İngilizce okunur; hukuk ve ürün terimlerinde Türkçe karşılıklar yer alır.

0%
▲Yanıtlanan sorular
0 / 6
—
○Doğruluk oranı
Henüz yanıt yok

Bu dersteki bölümler

  1. 1.Why this matters
  2. 2.The ideas
  3. 3.How this repository does it
  4. 4.What went wrong once
  5. 5.Try it yourself
  6. 6.Check yourself
  7. 7.Words to know
  8. 8.Go deeper

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:

  1. API version pinning: Every connector declares an exact dated or major revision (such as 2026-10 for Shopify, v27.0 for Meta Graph API or v26 for Google Ads) and rejects floating aliases such as latest or unstable so a provider cannot break response shapes silently overnight.
  2. Accepted is not done: Receiving HTTP 202 Accepted on 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 / railRelease plan (OD-06)Technical interfaceHonest status today
ikasDay 1 native connectorAdmin GraphQL v2 + OAuth 2.0 + HMAC webhooks + 15-min overlap pollingBuilt and verified locally; live partner credentials pending (issue 4)
WooCommerceDay 1 lightweight PHP pluginHPOS-compatible WordPress plugin (packages/connectors/woocommerce-plugin) capturing click IDs + signed order webhooksBuilt and verified locally; no live merchant installs yet
Universal JS SnippetDay 1 universal railFirst-party snippet capturing _fbp, _fbc, gclid, ttclid, _ttp on custom, IdeaSoft, T-Soft and Ticimax sitesBuilt and verified locally; awaits live domain (OD-01)
TicimaxDay 1 webhook bridgeMerchant admin-panel webhook bridge + Turkish currency parser (avoids legacy SOAP)Built and verified locally; official Solution Partner app is Release 2
ShopifyParallel review, unlock on approvalGraphQL 2026-10, Base64 HMAC webhooks, 3 mandatory compliance webhooks behind a rollout gateBuilt and verified locally; customer PII forced null until Shopify protected customer data review passes
IdeaSoft and T-SoftRelease 2 native apps (Day 1 via snippet)Order normalisers already written for canonical mappingNormalisers 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:

  1. 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 with crypto.timingSafeEqual against the provider header (X-Hub-Signature-256, X-Shopify-Hmac-Sha256, x-ikas-signature or X-IYZ-SIGNATURE-V3).
  2. Size cap and replay window: Payloads above 1 MiB (1,048,576 bytes) are dropped immediately, and timestamped requests outside plus or minus 300 seconds (5 minutes) are rejected with timestamp_out_of_window.
  3. Deduplication via raw ingest envelopes and the webhook identity triad: Every verified delivery is hashed with SHA-256 and recorded in raw_ingest_envelopes for 14 days (capped at 30 days for KVKK minimisation). Crucially, the triad separates delivery_id (changes on every provider retry), business event_id (stable for the underlying order or refund) and subscription_id (which webhook registration fired). Deduplicating on business event and payload hash prevents double-counting when a shop retries a slow response under a fresh delivery_id.
  4. 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 only signatureVerified === true envelopes 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:

text
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:

  1. conversion_events (rank 100): Consented Meta CAPI and Google Data Manager dispatches go first.
  2. order_sync (rank 50): Live storefront order and refund syncs come second.
  3. 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_marketing or consent_ad_user_data is 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:

  1. Zero secrets at startup: env-guard.ts inspects process.env before accepting any job and crashes cleanly with FORBIDDEN_ENV_SECRET if DATABASE_URL, VAULT_*, POSTGRES_*, IYZICO_*, META_APP_SECRET, GOOGLE_ADS_DEVELOPER_TOKEN, SHOPIFY_* or IKAS_CLIENT_SECRET is present. Even a total process compromise yields zero credentials.
  2. Connect-time DNS resolution and IP pinning: ssrf-guard.ts permits only http:/https: on ports 80 and 443, 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/.local hostnames), 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 at 5 MiB and enforces a 10-second timeout.
  3. Actionable 5-task cap (R8) and zero fabrication: Each SEO audit checks noindex, <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 to psi_lab_fallback when 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_difficulty and backlinks_count—stay strictly null with paid_data_required: true, never guessed or filled with 0.
  4. Byte-verified SEO patches: Writing an approved ikas SEO fix touches only five allow-listed fields (pageTitle, description, slug, canonicals, disableIndex), refuses any payload naming content, contentData, blogContent, prices, stocks or publish dates (IKAS_EDITOR_CONTENT_FORBIDDEN), binds the approved copy to a SHA-256 revision_hash and verifies UTF-8 bytes with Buffer.equals on 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, ConnectionHealthService calls Meta debug_token or Google tokeninfo plus account listing, caches healthy answers for 5 minutes and failures for 1 minute (preventing hammering a broken provider), surfaces missing scopes and returns null (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 due oauth_refreshable rows expiring within 24 hours using FOR 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.ts makes a bounded best-effort provider revoke call (10-second timeout) and always marks the row revoked and 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

External partner reviews and live sandboxes tracked in issue 4 (ikas, Shopify Level 2 Protected Customer Data, Meta App Review and Business Verification, Google OAuth verification and Ads Developer Token Basic access, Google Business Profile 60-day gate, and iyzico live settlement) have not been approved or called against live customer accounts yet (external_sandboxes_pending: true). All five webhook and dispatch lanes are built and verified against local PostgreSQL 18.7 FORCE RLS and loopback harnesses only. Screen 11 (Lead detail drawer at /w/:ws/crm/:id) is designed only, and native IdeaSoft and T-Soft App Store connectors belong to Release 2.

LayerKey repository filesWhat is built and verified locally
Webhook auth & normalisationpackages/connectors/src/hmac-verifiers.ts, packages/connectors/src/webhook-normalizer.ts, packages/connectors/src/kimi-v8-guards.ts, apps/api/src/routes/ingest-webhooks.tsConstant-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 budgetspackages/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.tsSingle-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 & snippetpackages/connectors/woocommerce-plugin (PHP file {product}-signals.php)HPOS-compatible order-meta click capture and signed order webhook sender
Delivery health & reconciliationapps/api/src/routes/developer-webhook-delivery-health.ts, apps/api/src/routes/connectors-order-reconcile.tsRead-only 5-channel BigInt health matrix (98% HMAC floor, 2%/10% DLQ thresholds, idle dashes) and exact kuruş order reconciliation
Closed-loop CRMpackages/db/src/repositories/signals-crm-repo.ts, apps/api/src/routes/crm-create-deal.ts, apps/api/src/routes/connections-crm.ts, docs/schema.sqlAtomic updateCrmDealStageAndEnqueueFeedback, enforce_conversion_feedback_consent() SQL trigger, 409 CONTACT_ERASED check, linear-time PII screen
Isolated SEO workerapps/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.tsStartup 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 & revokeapps/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.ts5-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:

bash
cd packages/connectors
npm test

Step 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:

bash
cd apps/seo-worker
npm test

Step 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:

bash
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.ts

Step 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:

bash
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.ts

Check yourself

0 / 6

Q1.A 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?

Q2.Why does the product run scheduled 15-minute polling with a 5-minute overlap lookback even when ikas webhooks are verified and working?

Q3.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?

Q4.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?

Q5.Why does ikas-seo-patch-policy.ts refuse a patch that includes contentData and check read-back bytes with SHA-256?

Q6.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

36
accepted is not done

The rule that a provider saying a request was accepted (such as HTTP 202) proves receipt only, never completion.

Bağlayıcılar ve CRMSözlükte incele
account connectionTR: hesap bağlantısı

An owner-approved OAuth link between a workspace and an external Meta, Google or storefront account.

Bağlayıcılar ve CRMSözlükte incele
API version pinning

Calling a fixed, dated provider API version (such as v27.0 or 2026-10) and rejecting floating aliases like latest.

Bağlayıcılar ve CRMSözlükte incele
closed-loop CRM

The built-in CRM workflow where moving a consented deal to qualified or won atomically queues conversion feedback for ad platforms.

Bağlayıcılar ve CRMSözlükte incele
connection healthTR: Hesap sağlığı

A cached live check of one connected account showing token validity, expiry, missing scopes and ad-account metadata.

Bağlayıcılar ve CRMSözlükte incele
connectorTR: bağlayıcı

The adapter code that authenticates with one external storefront or ad platform and maps its payloads into the product canonical schema.

Bağlayıcılar ve CRMSözlükte incele
crawler

The HTTP fetching program inside the isolated SEO worker that reads a storefront public HTML, robots.txt and sitemap.xml.

Bağlayıcılar ve CRMSözlükte incele
CRM dealTR: fırsat

One sales opportunity or storefront order in crm_deals, linked to a contact, stage and exact integer value.

Bağlayıcılar ve CRMSözlükte incele
deal stageTR: aşama

The lifecycle step of a CRM deal (lead, qualified, appointment_booked, proposal, won, lost, refunded).

Bağlayıcılar ve CRMSözlükte incele
fake provider

A test-only local HTTP transport stub for Meta and Google OAuth and dispatch flows, hard-blocked in production.

Bağlayıcılar ve CRMSözlükte incele
hybrid sync

Combining real-time inbound webhooks with periodic overlap-cursor polling so dropped webhooks never lose orders.

Bağlayıcılar ve CRMSözlükte incele
ikas

A Turkish e-commerce platform with an Admin GraphQL v2 API and OAuth webhooks, targeted as the flagship Day-1 native storefront connector.

Bağlayıcılar ve CRMSözlükte incele
contentData (ikas)

The visual page-builder body field (contentData) on ikas pages that SEO patches must leave byte-for-byte untouched.

Bağlayıcılar ve CRMSözlükte incele
needs reauthorisationTR: yeniden doğrulama

The connection status (needs_reauth) indicating stored tokens can no longer refresh and the owner must reconnect on the provider page.

Bağlayıcılar ve CRMSözlükte incele
order reconciliationTR: sipariş mutabakatı

Comparing storefront order and refund totals against the product ledger to the exact kuruş and surfacing any drift.

Bağlayıcılar ve CRMSözlükte incele
overlap lookback

Rewinding a polling cursor backwards by a small safety window (such as 5 minutes for ikas) on every sync.

Bağlayıcılar ve CRMSözlükte incele
polling

Periodically querying a platform API from a saved sync cursor to fetch every record changed since the previous check.

Bağlayıcılar ve CRMSözlükte incele
priority SEO tasksTR: öncelikli SEO görevleri

The deterministic ranked cap of at most five concrete SEO fixes produced per audit (R8), replacing overwhelming 200-item reports.

Bağlayıcılar ve CRMSözlükte incele
proactive throttle

Intentionally slowing down outbound provider calls before hitting 100 percent of a quota so HTTP 429 rejections are avoided.

Bağlayıcılar ve CRMSözlükte incele
quarantineTR: karantina

Temporarily parking a failing sync cursor or isolating a suspect webhook or export file so one bad item cannot stall healthy work.

Bağlayıcılar ve CRMSözlükte incele
rate budget

The product own per-provider, per-account call allowance and priority queue that stays below external quotas.

Bağlayıcılar ve CRMSözlükte incele
raw ingest envelopeTR: ham alım zarfı

The short-lived deduplicated database record of one incoming webhook delivery, stored by SHA-256 hash for 14 days.

Bağlayıcılar ve CRMSözlükte incele
replay windowTR: imza zaman penceresi

The strict plus-or-minus 300-second (5-minute) timestamp tolerance within which a signed webhook or collector request is accepted.

Bağlayıcılar ve CRMSözlükte incele
rollout gate

An explicit code switch keeping a partner-dependent capability disabled until external platform approval is granted.

Bağlayıcılar ve CRMSözlükte incele
SEO auditTR: SEO taraması

One isolated crawl and HTML analysis of a storefront public pages that records issues and outputs at most five priority tasks.

Bağlayıcılar ve CRMSözlükte incele
SEO patchTR: yama

A minimal, human-approved update touching only allow-listed SEO metadata (pageTitle, description, slug, canonicals, disableIndex).

Bağlayıcılar ve CRMSözlükte incele
SEO worker

The isolated Zone 3 process (apps/seo-worker) that runs web crawling and HTML audits with zero database, vault or payment secrets.

Bağlayıcılar ve CRMSözlükte incele
Shopify protected customer data review

Shopify mandatory Level 2 privacy review required before an app may read customer names, emails, phones or addresses.

Bağlayıcılar ve CRMSözlükte incele
sync cursorTR: imleç

A per-workspace, per-provider, per-stream database bookmark (sync_cursors) recording where the last successful poll stopped.

Bağlayıcılar ve CRMSözlükte incele
token refreshTR: belirteç yenileme

Automatically renewing expiring OAuth access tokens every 15 minutes inside the isolated dispatch process using FOR UPDATE SKIP LOCKED.

Bağlayıcılar ve CRMSözlükte incele
wake-up hint

The design principle that an inbound webhook signals something changed, prompting an authoritative API check or cursor sync.

Bağlayıcılar ve CRMSözlükte incele
webhookTR: webhook

An automated HTTP POST sent by an external platform to this product when an event happens, such as a new order or refund.

Bağlayıcılar ve CRMSözlükte incele
webhook identity triad

The rule distinguishing delivery_id (changes on every resend), business event_id (stable) and subscription_id (webhook config).

Bağlayıcılar ve CRMSözlükte incele
webhook replayTR: yeniden oynatma

Re-processing stored, signature-verified failed webhook envelopes single-flight per workspace once the root cause is fixed.

Bağlayıcılar ve CRMSözlükte incele
webhook signatureTR: webhook imzası

An HMAC digest computed by the sending provider over verbatim raw webhook bytes and verified in constant time before parsing JSON.

Bağlayıcılar ve CRMSözlükte incele
zero fabrication

The strict rule that missing or paid-only metrics stay null (rendered as a dash with a reason) and are never invented or faked.

Bağlayıcılar ve CRMSözlükte incele

Go deeper

  • Operational runbooks & decisions: Webhook delivery, HMAC & dead-letter runbook, docs/OWNER-DECISIONS.md (OD-06, OD-21, issue 4) and docs/THREAT-MODEL.md (T5).
  • Archived wave-by-wave notes: archived lesson 09, archived lesson 10, archived lesson 25 and archived 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.
◆

NOT LEGAL OR TAX ADVICE · Açık karar kapıları dürüstlüğü

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

Önceki ders: L09Sonraki ders: L11

L10 · Part C · intermediate · Verified 2026-12-04 · 20 min

Integrations: storefronts, webhooks, sync, the CRM loop, the SEO crawler

How connectors authenticate webhooks, sync orders safely, close the CRM conversion loop, isolate the SEO crawler, and refresh tokens.

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

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:

  1. API version pinning: Every connector declares an exact dated or major revision (such as 2026-10 for Shopify, v27.0 for Meta Graph API or v26 for Google Ads) and rejects floating aliases such as latest or unstable so a provider cannot break response shapes silently overnight.
  2. Accepted is not done: Receiving HTTP 202 Accepted on 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 / railRelease plan (OD-06)Technical interfaceHonest status today
ikasDay 1 native connectorAdmin GraphQL v2 + OAuth 2.0 + HMAC webhooks + 15-min overlap pollingBuilt and verified locally; live partner credentials pending (issue 4)
WooCommerceDay 1 lightweight PHP pluginHPOS-compatible WordPress plugin (packages/connectors/woocommerce-plugin) capturing click IDs + signed order webhooksBuilt and verified locally; no live merchant installs yet
Universal JS SnippetDay 1 universal railFirst-party snippet capturing _fbp, _fbc, gclid, ttclid, _ttp on custom, IdeaSoft, T-Soft and Ticimax sitesBuilt and verified locally; awaits live domain (OD-01)
TicimaxDay 1 webhook bridgeMerchant admin-panel webhook bridge + Turkish currency parser (avoids legacy SOAP)Built and verified locally; official Solution Partner app is Release 2
ShopifyParallel review, unlock on approvalGraphQL 2026-10, Base64 HMAC webhooks, 3 mandatory compliance webhooks behind a rollout gateBuilt and verified locally; customer PII forced null until Shopify protected customer data review passes
IdeaSoft and T-SoftRelease 2 native apps (Day 1 via snippet)Order normalisers already written for canonical mappingNormalisers 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:

  1. 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 with crypto.timingSafeEqual against the provider header (X-Hub-Signature-256, X-Shopify-Hmac-Sha256, x-ikas-signature or X-IYZ-SIGNATURE-V3).
  2. Size cap and replay window: Payloads above 1 MiB (1,048,576 bytes) are dropped immediately, and timestamped requests outside plus or minus 300 seconds (5 minutes) are rejected with timestamp_out_of_window.
  3. Deduplication via raw ingest envelopes and the webhook identity triad: Every verified delivery is hashed with SHA-256 and recorded in raw_ingest_envelopes for 14 days (capped at 30 days for KVKK minimisation). Crucially, the triad separates delivery_id (changes on every provider retry), business event_id (stable for the underlying order or refund) and subscription_id (which webhook registration fired). Deduplicating on business event and payload hash prevents double-counting when a shop retries a slow response under a fresh delivery_id.
  4. 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 only signatureVerified === true envelopes 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:

  1. conversion_events (rank 100): Consented Meta CAPI and Google Data Manager dispatches go first.
  2. order_sync (rank 50): Live storefront order and refund syncs come second.
  3. 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_marketing or consent_ad_user_data is 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:

  1. Zero secrets at startup: env-guard.ts inspects process.env before accepting any job and crashes cleanly with FORBIDDEN_ENV_SECRET if DATABASE_URL, VAULT_*, POSTGRES_*, IYZICO_*, META_APP_SECRET, GOOGLE_ADS_DEVELOPER_TOKEN, SHOPIFY_* or IKAS_CLIENT_SECRET is present. Even a total process compromise yields zero credentials.
  2. Connect-time DNS resolution and IP pinning: ssrf-guard.ts permits only http:/https: on ports 80 and 443, 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/.local hostnames), 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 at 5 MiB and enforces a 10-second timeout.
  3. Actionable 5-task cap (R8) and zero fabrication: Each SEO audit checks noindex, <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 to psi_lab_fallback when 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_difficulty and backlinks_count—stay strictly null with paid_data_required: true, never guessed or filled with 0.
  4. Byte-verified SEO patches: Writing an approved ikas SEO fix touches only five allow-listed fields (pageTitle, description, slug, canonicals, disableIndex), refuses any payload naming content, contentData, blogContent, prices, stocks or publish dates (IKAS_EDITOR_CONTENT_FORBIDDEN), binds the approved copy to a SHA-256 revision_hash and verifies UTF-8 bytes with Buffer.equals on 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, ConnectionHealthService calls Meta debug_token or Google tokeninfo plus account listing, caches healthy answers for 5 minutes and failures for 1 minute (preventing hammering a broken provider), surfaces missing scopes and returns null (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 due oauth_refreshable rows expiring within 24 hours using FOR 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.ts makes a bounded best-effort provider revoke call (10-second timeout) and always marks the row revoked and 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

External partner reviews and live sandboxes tracked in issue 4 (ikas, Shopify Level 2 Protected Customer Data, Meta App Review and Business Verification, Google OAuth verification and Ads Developer Token Basic access, Google Business Profile 60-day gate, and iyzico live settlement) have not been approved or called against live customer accounts yet (external_sandboxes_pending: true). All five webhook and dispatch lanes are built and verified against local PostgreSQL 18.7 FORCE RLS and loopback harnesses only. Screen 11 (Lead detail drawer at /w/:ws/crm/:id) is designed only, and native IdeaSoft and T-Soft App Store connectors belong to Release 2.

LayerKey repository filesWhat is built and verified locally
Webhook auth & normalisationpackages/connectors/src/hmac-verifiers.ts, packages/connectors/src/webhook-normalizer.ts, packages/connectors/src/kimi-v8-guards.ts, apps/api/src/routes/ingest-webhooks.tsConstant-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 budgetspackages/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.tsSingle-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 & snippetpackages/connectors/woocommerce-plugin (PHP file {product}-signals.php)HPOS-compatible order-meta click capture and signed order webhook sender
Delivery health & reconciliationapps/api/src/routes/developer-webhook-delivery-health.ts, apps/api/src/routes/connectors-order-reconcile.tsRead-only 5-channel BigInt health matrix (98% HMAC floor, 2%/10% DLQ thresholds, idle dashes) and exact kuruş order reconciliation
Closed-loop CRMpackages/db/src/repositories/signals-crm-repo.ts, apps/api/src/routes/crm-create-deal.ts, apps/api/src/routes/connections-crm.ts, docs/schema.sqlAtomic updateCrmDealStageAndEnqueueFeedback, enforce_conversion_feedback_consent() SQL trigger, 409 CONTACT_ERASED check, linear-time PII screen
Isolated SEO workerapps/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.tsStartup 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 & revokeapps/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.ts5-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 test

Step 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 test

Step 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.ts

Step 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.ts

Words to know

  • accepted is not done
  • account connection
  • API version pinning
  • closed-loop CRM
  • connection health
  • connector
  • crawler
  • CRM deal
  • deal stage
  • fake provider
  • hybrid sync
  • ikas
  • contentData (ikas)
  • needs reauthorisation
  • order reconciliation
  • overlap lookback
  • polling
  • priority SEO tasks
  • proactive throttle
  • quarantine
  • rate budget
  • raw ingest envelope
  • replay window
  • rollout gate
  • SEO audit
  • SEO patch
  • SEO worker
  • Shopify protected customer data review
  • sync cursor
  • token refresh
  • wake-up hint
  • webhook
  • webhook identity triad
  • webhook replay
  • webhook signature
  • zero fabrication

Go deeper

  • Operational runbooks & decisions: Webhook delivery, HMAC & dead-letter runbook, docs/OWNER-DECISIONS.md (OD-06, OD-21, issue 4) and docs/THREAT-MODEL.md (T5).
  • Archived wave-by-wave notes: archived lesson 09, archived lesson 10, archived lesson 25 and archived 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.

Kendini sına soru özeti ve yanıt anahtarı

Q1. A 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?

Answer: B

Providers routinely mint a fresh delivery_id on every retry, so deduplicating only on delivery_id causes double-counted revenue (packages/connectors/src/kimi-v8-guards.ts and replay-queue.ts). Option A is wrong because legitimate concurrent orders arrive seconds apart; keying on business event ID and raw payload hash catches resends cleanly.

Q2. Why does the product run scheduled 15-minute polling with a 5-minute overlap lookback even when ikas webhooks are verified and working?

Answer: B

Webhooks act as fast wake-up hints, never as the sole source of truth (packages/connectors/src/ikas-sync.ts). Option C is wrong because polling still runs strictly under rate-budget.ts; the 5-minute safety overlap protects against late commits and brief outages without risking silent revenue loss.

Q3. 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?

Answer: B

Defence-in-depth pairs connect-time hop-by-hop IP pinning (apps/seo-worker/src/ssrf-guard.ts) with Zone 3 process isolation (apps/seo-worker/src/env-guard.ts). Option A is wrong because robots.txt is voluntary and never a security boundary against a hostile redirect target.

Q4. 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?

Answer: B

Using the transactional outbox (packages/db/src/repositories/signals-crm-repo.ts and docs/schema.sql) prevents lost or orphaned conversion events across crashes, hard-blocks erased or unconsented contacts via SQL trigger, and lets the separate least-privilege dispatch-main.ts process hold vault credentials. Option A is wrong—the separation is for reliability and least privilege, not a framework limit.

Q5. Why does ikas-seo-patch-policy.ts refuse a patch that includes contentData and check read-back bytes with SHA-256?

Answer: B

Storefront visual layouts live in contentData (apps/seo-worker/src/ikas-seo-patch-policy.ts); restricting writes to pageTitle, description, slug, canonicals and disableIndex and verifying exact bytes on read-back prevents an SEO fix from destroying a live product or blog design. Option A is wrong because pageTitle is explicitly on the five-field allow-list.

Q6. 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?

Answer: B

Separating dispatch-main.ts keeps vault secrets confined to the narrowest possible process (CS-47), and FOR UPDATE SKIP LOCKED (apps/api/src/connections/refresh.ts) prevents race conditions across concurrent workers. Option A is wrong because worker-main.ts uses the regular application database login—it simply never holds vault access.

GetClaps Kurucu Akademisi · Tarayıcı açılışında ağ çağrısı yapılmaz; ilerleme yalnızca cihazındaki yerel depolamada tutulur.