Skip to content

feat(adapters): createOAuthPassthroughResolver (#1363) - #1369

Merged
bokelley merged 4 commits into
mainfrom
bokelley/oauth-passthrough-resolver
May 2, 2026
Merged

bokelley merged 4 commits into
mainfrom
bokelley/oauth-passthrough-resolver

Conversation

@bokelley

@bokelley bokelley commented May 2, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #1363. Standardizes the canonical "Shape B" account-resolution pattern that every adapter wrapping a vendor OAuth + ad-account API (Snap, Meta, TikTok, LinkedIn, Reddit, Pinterest, etc.) re-derives by hand:

extract bearer from ctx.authInfo → GET /me/adaccounts (or equivalent) → match upstream row by account_id → return tenant with ctx_metadata populated

Without the factory, each adapter writes ~30 LOC of boilerplate. The doha-v20 (scope3data/agentic-adapters) monorepo had this pattern repeated across 13 of 14 adapters when #1363 was filed.

Usage

import {
  createUpstreamHttpClient,
  createOAuthPassthroughResolver,
  defineSalesPlatform,
} from '@adcp/sdk/server';

const snap = createUpstreamHttpClient({
  baseUrl: 'https://adsapi.snapchat.com',
  auth: {
    kind: 'dynamic_bearer',
    getToken: async (ctx) => ctx?.authInfo?.credential?.token,
  },
});

const resolve = createOAuthPassthroughResolver({
  httpClient: snap,
  listEndpoint: '/v1/me/adaccounts',
  idField: 'id',
  rowsPath: 'adaccounts',
  toAccount: (row, ctx) => ({
    id: row.id,
    name: row.name,
    status: 'active',
    advertiser: row.advertiser_url,
    ctx_metadata: {
      upstreamId: row.id,
      accessToken: ctx?.authInfo?.credential?.token,
    },
  }),
  cache: { ttlMs: 60_000 },
});

defineSalesPlatform({
  accounts: { resolve, /* upsert omitted — Shape B doesn't manage account lifecycle */ },
  // ...
});

Configurable shape

Option Default Notes
idField 'id' Match column on each upstream row
rowsPath 'data' Path to the array; null = body is flat array
getAuthContext (ctx) => ctx?.authInfo Auth-context to forward to dynamic_bearer.getToken
toAccount required Adapter-supplied row → Account<TCtxMeta> mapper
cache.ttlMs unset (no cache) Opt-in TTL cache; recommended 30s–5min in prod
cache.getCacheKey JSON.stringify(authContext) Narrow when authContext has request-id noise

Behavior

  • Only handles { account_id } arm — { brand, operator } and undefined ref return null without calling upstream
  • Cache is auth-context keyed — different buyers never share cache entries (security boundary)
  • Upstream errors propagate verbatim — adopters compose composeMethod over the result for typed envelope mapping (e.g. AUTH_REQUIRED on 401)

Test plan

  • 15 new tests in test/server-adapters-oauth-passthrough-resolver.test.js covering: ref-arm short-circuits, upstream lookup + match, no-match returns null, empty body returns null, error propagation, custom idField/rowsPath/getAuthContext, cache hit/miss, TTL expiry, multi-buyer isolation, custom getCacheKey, public re-export from @adcp/sdk
  • npm run build:lib clean
  • npm run format:check clean
  • Changeset (minor — additive surface)

Source

#1340 triage thread → #1363 spin-off. The 8–12 line snippet in the planned docs/guides/account-resolution.md (PR #1357) is fine for one or two adopters; for a multi-adapter monorepo it's pure repetition. This factory is the ergonomic answer for that case.

🤖 Generated with Claude Code

Standardize the canonical "Shape B" account-resolution pattern that
every adapter wrapping a vendor OAuth + ad-account API (Snap, Meta,
TikTok, LinkedIn, Reddit, Pinterest, etc.) re-derives by hand:

  extract bearer from ctx.authInfo →
  GET /me/adaccounts (or equivalent) →
  match upstream row by account_id →
  return tenant with ctx_metadata populated

Without the factory, each adapter writes ~30 LOC of boilerplate; the
agentic-adapters monorepo had this pattern repeated across 13 of 14
adapters when this issue was filed.

The factory composes with createUpstreamHttpClient — adopters
configure dynamic_bearer.getToken on the http client for per-buyer
credential injection; the factory's getAuthContext output flows
through as the authContext per-call option.

Configurable shape:
- idField (default 'id') — match column on the upstream row
- rowsPath (default 'data', null = body is flat array)
- getAuthContext (default forwards ctx?.authInfo verbatim)
- toAccount mapper — adopter shapes the framework Account
- cache opt-in TTL — auth-context-keyed so different buyers don't
  share cached entries; getCacheKey override for narrowing the
  cache dimension when authContext carries request-id noise

Closes #1363.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…#1369)

Address expert-review findings on PR #1369:

1. **Listing-keyed cache** (product reviewer). Previous shape cached
   `(authContext, account_id) → Account` — N upstream hits for N
   account_ids on the same buyer. The whole point of /me/adaccounts
   is to return ALL accounts in one call; per-id caching defeats it.
   Cache now stores the full row array per buyer, resolves account_id
   matches in-memory within the TTL window. Memory cost trivial; the
   upstream-hit-rate win is meaningful for multi-account buyers calling
   3-5 tools concurrently.

2. **SHA-256 cache key default** (security reviewer). Previous default
   was `JSON.stringify(authContext)` — embeds the raw bearer in Map
   keys for the TTL window. Heap dumps, util.inspect(cache), or
   debug logs that iterate the Map surface the token. Now hashes the
   serialized authContext (same isolation guarantee, no plaintext at
   rest). Adopters can still supply their own `getCacheKey` to narrow
   the dimension.

3. **maxEntries with LRU eviction** (code reviewer). Default 1024.
   Bounds memory under token-rotation churn; insertion-order Map
   iteration gives O(1) LRU eviction.

4. **JSDoc warnings**:
   - `toAccount` callout: treat ctx_metadata.accessToken as a secret;
     adopter throws/logs that include the account WILL leak it.
   - `cache.ttlMs` guidance: distinguish read-tool TTL (60-300s) from
     mutating-tool TTL (0-30s, or skip cache via composeMethod).
     Revoked-but-not-expired bearer would otherwise authorize
     mutations for the full TTL window.
   - `idField` footgun: when `TUpstreamRow` is inferred, `keyof &
     string` collapses and typos compile fine, silently always
     returning null.
   - `rowsPath` carve-out: TikTok's `data.list` and Google Ads'
     `customers:listAccessibleCustomers` are not direct fits.

5. **JSON.stringify failure fallback**: circular refs / BigInt /
   non-serializable auth contexts now produce a truncated literal
   key instead of throwing.

New tests cover: listing-cache (1 buyer × 3 account_ids = 1 hit),
sha256-stability (same token → cache hit; different token → miss),
LRU eviction at maxEntries.

Closes the open expert-review items on adcp-client#1369.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley bokelley closed this May 2, 2026
@bokelley bokelley reopened this May 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(server): createOAuthPassthroughResolver — factory for the 'Shape B' AccountStore.resolve pattern

1 participant