← Back to Pull requests

finance: Shopee adapter S1, signer, token, shop info and orders read, dormant (#2524, #4274) #4277

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 21, 2026 11:12 UTC
Author

Closes #4274

Summary


First slice of the Shopee adapter (#2524), built from the official Open Platform docs read on 2026-11-21 (design note, PO decisions in the next comment). Dormant: nothing offers shopee until the live check (#2522); no migration, no table, no UI.

  • marketplace-shopee-sign.ts: signer (HMAC-SHA256 over partner id + path + timestamp [+ token + shop id]); vectors checked against openssl.

  • marketplace-shopee-token.ts: token create and ShopeeRefresher (provider marketplace_shopee, 30 min horizon). The refresh token is single use and replaced each refresh; one call, never repeated; refusal only by dates; unreadable verdicts not re-asked for 30 min.

  • marketplace-shopee.ts: the one signed caller (partner.shopeemobile.com), paced 1 call/s per partner and shop, error words to the port's kinds, shop info (also gives the authorization end), connection test.

  • marketplace-shopee-orders.ts: get_order_list by update time + get_order_detail in batches of 50, no buyer field requested, amounts kept as exact JSON source text (context.source), stage table, stock rule (system/Ops cancellation after pickup stays shipped), cursor with window end and width.

  • kernel.ts registers the refresher only where MARKETPLACE_PROVIDERS names shopee; shopee added to MARKETPLACE_ADAPTERS.
  • New finding from the API pages: only the ERP System and Seller In-house System app types can call order list, returns, escrow and shop info together (Accounting and Finance cannot read the order list).

    Acceptance


  • Signature vectors vs openssl: marketplace-shopee-token.test.ts (local run: 45 tests pass across the two new test files).

  • Refresh token rotation, one call, concurrent sweeps keep the new pair: unit tests plus channel-refresh.db.test.ts Shopee block (DB test not run locally, CI only).

  • No key, token, code, signed URL or Shopee sentence in any result: tests plant them and search outputs.

  • Amount exactness: 4503599627370497.5 kept; 3 x 0.1 = 0.3; exponent, >4 decimals, negative refused.

  • Review checklist: correctness: cursor/window/stock rule tested, reviewer found none blocking; security: closed error words, secret never echoed; tenancy: n/a (no table); money: decimal strings via decimal.js, floats never JS numbers; performance: at most 7 list + 2 detail calls per poll, paced; accessibility: n/a.

  • pnpm lint, pnpm --filter @crove/kernel typecheck, @crove/mod-finance typecheck, docs:check pass locally.
  • Review


    Codex is not installed in this environment (not run). A fresh-context reviewer found no blocking issue; taken: unnamed canceller after pickup stays shipped, throttle words no longer shadow unreadable ones, shop id capped at 15 digits (exact in JSON number), first window one second inside the 15-day limit, pacing aligned with the port's 60/min. Not taken (non-blocking): overlap counted inside narrow widths, a permanently missing detail entry stalls loudly (deliberate "never skip"), unknown error words read as unreachable.

    Risk left: all words and stages are the code's reading of the docs until the live check (#2522); bundle-deal lines use the original price (order money is the escrow's job, S3).

    ---
    _Generated by Claude Code_

    ---

    <!-- dos-pr-summary -->

    📌 TL;DR


    This PR introduces the Shopee marketplace integration (S1 slice), implementing the API caller, HMAC-SHA256 signing, token management (with single-use refresh token rotation), and a read-only orders adapter with a sophisticated cursor-based pagination strategy. It also registers the ShopeeRefresher in the kernel's channel refresh sweep and adds comprehensive integration tests.

    🎯 Type of Change


  • 🚀 New feature

  • 🐛 Bugfix

  • 🧹 Refactor

  • ⚡ Performance

  • 📚 Documentation

  • ⚙️ CI / Configuration
  • 🔍 Changes Walkthrough


    | File | Summary of Changes |
    | :--- | :--- |
    | apps/kernel/src/kernel.ts | Registers the ShopeeRefresher in the channelRefreshers factory when the shopee provider is configured, enabling automatic token renewal via the worker sweep. |
    | apps/kernel/src/marketplace-shopee-sign.ts | New. Implements the pure function signShopeeRequest which generates the HMAC-SHA256 signature required by Shopee's Open API v2, handling both public and shop-scoped calls. |
    | apps/kernel/src/marketplace-shopee-token.ts | New. Implements the token lifecycle: createShopeeToken (trading auth codes for tokens) and the ShopeeRefresher class. Handles single-use refresh token rotation, expiration checks, and in-memory verdict caching to prevent redundant API calls. |
    | apps/kernel/src/marketplace-shopee.ts | New. The core API caller (shopeeCaller) with rate limiting (turn-taking per partner/shop), error classification, and the testShopeeConnection logic. Includes parseShopeeSecret for credential validation. |
    | apps/kernel/src/marketplace-shopee-orders.ts | New. The orders adapter implementing MarketplaceProvider. Features a complex cursor-based pagination system that adapts window sizes (15d → 1min) to handle rate limits and data density, along with strict data validation and stock-stage mapping logic. |
    | apps/kernel/test/channel-refresh.db.test.ts | Adds integration tests for the Shopee refresher within the PostgreSQL-backed channel refresh sweep, verifying token rotation, concurrency safety, and expiration handling. |
    | apps/kernel/test/fake-shopee.ts | New. An in-process mock fetch implementation that simulates the Shopee API, including signature verification and token state management, for use in tests. |

    📊 Architectural Flow

    sequenceDiagram
        participant Worker as Kernel Worker
        participant Refresher as ShopeeRefresher
        participant Caller as ShopeeCaller
        participant Signer as signShopeeRequest
        participant Shopee as Shopee API
    
        Note over Worker, Shopee: Token Refresh Flow
        Worker->>Refresher: refresh(secret)
        Refresher->>Refresher: Validate dates & check verdict cache
        Refresher->>Caller: postToken(REFRESH_PATH)
        Caller->>Signer: sign(partnerKey, partnerId, path, timestamp)
        Signer-->>Caller: signature
        Caller->>Shopee: POST /auth/access_token/get (signed)
        Shopee-->>Caller: { access_token, refresh_token, expire_in }
        Caller-->>Refresher: Tokens
        Refresher->>Refresher: Rotate tokens & update secret
        Refresher-->>Worker: { secret, expiresAt }
    
        Note over Worker, Shopee: Orders Polling Flow
        Worker->>Caller: listOrders(secret, cursor)
        Caller->>Caller: Calculate window & take turn (rate limit)
        Caller->>Signer: sign(...)
        Caller->>Shopee: GET /order/get_order_list (signed)
        Shopee-->>Caller: { order_list, more }
        alt more == true
            Caller->>Caller: Narrow window & retry
        else more == false
            Caller->>Shopee: GET /order/get_order_detail (batched)
            Shopee-->>Caller: { order_list: [details] }
            Caller-->>Worker: { orders, nextCursor }
        end
    

    <!-- /dos-pr-summary -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: claude[bot] Review duration: 11m
    All Vouch review confidence checks passed
    Residual risk 0.48 = Change Risk (0.75) × (1 − Review Confidence (0.36)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.75 · 650 lines diff across 8 files
    0.75
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 68% · Reviewer familiarity: 35%
    36%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Sensitive Paths sensitive_paths
    0.075
    Real PR Conversation Timeline
    1 comments
    "Review active on #4277"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: medium confidence: 36.4% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 75.2% (HIGH) · Higher = larger blast radius
    75.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 36.4% · Lower = rushed or shallow review
    36.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 47.8% · Moderate risk
    47.8%
    Repository