@simpleapps-com/augur-server 2.3.1 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,9 @@ import {
3
3
  getOrCreateScopedClient,
4
4
  getScopedCacheWrapper,
5
5
  getSdkCallWrapper,
6
- getSdkClientOrNull
7
- } from "./chunk-HPQQYROJ.js";
6
+ getSdkClientOrNull,
7
+ parseMethodPath
8
+ } from "./chunk-ALTIINP6.js";
8
9
 
9
10
  // src/query-action.ts
10
11
  import { isReadMethod, stripEdgeCacheForNoCachePaths } from "@simpleapps-com/augur-core";
@@ -12,6 +13,7 @@ var SECURE_COOKIE = "__Secure-authjs.session-token";
12
13
  var PLAIN_COOKIE = "authjs.session-token";
13
14
  var _decode;
14
15
  var _cookies;
16
+ var _decodeJwt;
15
17
  async function ensureImports() {
16
18
  if (_decode === void 0) {
17
19
  try {
@@ -29,7 +31,15 @@ async function ensureImports() {
29
31
  _cookies = null;
30
32
  }
31
33
  }
32
- return !!_decode && !!_cookies;
34
+ if (_decodeJwt === void 0) {
35
+ try {
36
+ const mod = await import("jose");
37
+ _decodeJwt = mod.decodeJwt;
38
+ } catch {
39
+ _decodeJwt = null;
40
+ }
41
+ }
42
+ return !!_decode && !!_cookies && !!_decodeJwt;
33
43
  }
34
44
  async function decodeSessionJwt(secret) {
35
45
  const cookieStore = await _cookies();
@@ -40,6 +50,19 @@ async function decodeSessionJwt(secret) {
40
50
  const salt = secureCookie ? SECURE_COOKIE : PLAIN_COOKIE;
41
51
  return _decode({ token: cookie.value, secret, salt });
42
52
  }
53
+ function parseBearerClientSiteId(bearer) {
54
+ try {
55
+ const payload = _decodeJwt(bearer);
56
+ const clientId = payload["client_id"];
57
+ if (typeof clientId !== "string") return null;
58
+ const pipeIndex = clientId.indexOf("|");
59
+ if (pipeIndex < 0) return null;
60
+ const siteId = clientId.slice(pipeIndex + 1);
61
+ return siteId.length > 0 ? siteId : null;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
43
66
  async function getSessionCredentials() {
44
67
  const secret = getAuthSecret();
45
68
  if (!secret) return null;
@@ -49,23 +72,28 @@ async function getSessionCredentials() {
49
72
  if (!decoded) return null;
50
73
  const targetSiteId = decoded["targetSiteId"];
51
74
  const token = decoded["token"];
52
- if (targetSiteId && token) {
53
- return { siteId: targetSiteId, token };
54
- }
75
+ if (typeof targetSiteId !== "string" || targetSiteId.length === 0) return null;
76
+ if (typeof token !== "string" || token.length === 0) return null;
77
+ const bearerSiteId = parseBearerClientSiteId(token);
78
+ if (bearerSiteId !== targetSiteId) return null;
79
+ return { siteId: targetSiteId, token };
55
80
  } catch {
56
81
  }
57
82
  return null;
58
83
  }
59
- async function resolveClientAndPrefix() {
60
- const globalClient = getSdkClientOrNull();
84
+ async function resolveClient() {
61
85
  const creds = await getSessionCredentials();
62
86
  if (creds) {
63
- const scoped = getOrCreateScopedClient(creds.siteId, creds.token);
64
- if (scoped) {
65
- return { client: scoped, cachePrefix: `${creds.siteId}:` };
87
+ const scoped = getOrCreateScopedClient(creds);
88
+ if (scoped !== null && typeof scoped === "object") {
89
+ return { kind: "scoped", client: scoped, credentials: creds };
66
90
  }
67
91
  }
68
- return { client: globalClient, cachePrefix: null };
92
+ const globalClient = getSdkClientOrNull();
93
+ if (globalClient !== null && typeof globalClient === "object") {
94
+ return { kind: "global", client: globalClient };
95
+ }
96
+ return { kind: "uninit" };
69
97
  }
70
98
  function unwrapBaseResponse(raw) {
71
99
  if (raw != null && typeof raw === "object" && "data" in raw && "status" in raw && "message" in raw) {
@@ -89,33 +117,29 @@ function resolveMethod(client, methodPath) {
89
117
  }
90
118
  return current;
91
119
  }
120
+ function bindScopedPrefix(scopedWrapper, prefix) {
121
+ if (!scopedWrapper) return null;
122
+ return (methodPath, sdkCall, ...keyArgs) => scopedWrapper(prefix, methodPath, sdkCall, ...keyArgs);
123
+ }
92
124
  async function queryAction(methodPath, ...args) {
93
- const { client, cachePrefix } = await resolveClientAndPrefix();
94
- if (!client) {
125
+ const approvedPath = parseMethodPath(methodPath);
126
+ if (approvedPath === null) {
95
127
  throw new Error(
96
- "SDK client not initialized. Call createServerSite() or set AUGUR_SITE_ID + AUGUR_JWT env vars."
128
+ `queryAction: methodPath ${JSON.stringify(methodPath)} is not in the registered allowlist. Register it via registerAllowedMethodPaths() in createServerSite() config.`
97
129
  );
98
130
  }
99
- const resolvedMethod = resolveMethod(client, methodPath);
100
- const leafName = methodPath.split(".").pop();
101
- const safeArgs = stripEdgeCacheForNoCachePaths(methodPath, args);
102
- if (cachePrefix !== null) {
103
- const scopedWrapper = getScopedCacheWrapper();
104
- if (scopedWrapper && isReadMethod(leafName)) {
105
- const result3 = await scopedWrapper(
106
- cachePrefix,
107
- methodPath,
108
- () => resolvedMethod(...safeArgs),
109
- ...safeArgs
110
- );
111
- return unwrapBaseResponse(result3);
112
- }
113
- const result2 = await resolvedMethod(...safeArgs);
114
- return unwrapBaseResponse(result2);
131
+ const resolution = await resolveClient();
132
+ if (resolution.kind === "uninit") {
133
+ throw new Error(
134
+ "SDK client not initialized. Call createServerSite() or set AUGUR_SITE_ID + AUGUR_JWT env vars."
135
+ );
115
136
  }
116
- const wrapper = getSdkCallWrapper();
137
+ const resolvedMethod = resolveMethod(resolution.client, approvedPath);
138
+ const leafName = approvedPath.split(".").pop();
139
+ const safeArgs = stripEdgeCacheForNoCachePaths(approvedPath, args);
140
+ const wrapper = resolution.kind === "scoped" ? bindScopedPrefix(getScopedCacheWrapper(), `${resolution.credentials.siteId}:`) : getSdkCallWrapper();
117
141
  if (wrapper && isReadMethod(leafName)) {
118
- const result2 = await wrapper(methodPath, () => resolvedMethod(...safeArgs), ...safeArgs);
142
+ const result2 = await wrapper(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);
119
143
  return unwrapBaseResponse(result2);
120
144
  }
121
145
  const result = await resolvedMethod(...safeArgs);
@@ -124,6 +148,7 @@ async function queryAction(methodPath, ...args) {
124
148
  function resetSessionImports() {
125
149
  _decode = void 0;
126
150
  _cookies = void 0;
151
+ _decodeJwt = void 0;
127
152
  }
128
153
 
129
154
  export {
@@ -133,4 +158,4 @@ export {
133
158
  queryAction,
134
159
  resetSessionImports
135
160
  };
136
- //# sourceMappingURL=chunk-ZUJZDRTP.js.map
161
+ //# sourceMappingURL=chunk-2NL4QKJN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/query-action.ts"],"sourcesContent":["// \"use server\" banner is injected by tsup at build time.\n// Isolated server action for the proxy pattern.\n// This file MUST NOT import from server-actions.ts, server-site-registry.ts,\n// cache/, or any factory. It imports only from lightweight stores with zero\n// deps, plus augur-core (external in tsup — not bundled into chunks).\n// Dynamic imports of next/headers and next-auth/jwt are used for session\n// credential resolution (both are external in tsup).\n\nimport {\n getSdkClientOrNull,\n getSdkCallWrapper,\n getAuthSecret,\n getOrCreateScopedClient,\n getScopedCacheWrapper,\n parseMethodPath,\n type SessionCredentials,\n type ApprovedMethodPath,\n type SdkCallWrapper,\n type ScopedCacheWrapper,\n} from \"./sdk-client-store\";\nimport { isReadMethod, stripEdgeCacheForNoCachePaths } from \"@simpleapps-com/augur-core\";\n\n/** Auth.js v5 session cookie names (HTTPS secure prefix + HTTP fallback). */\nconst SECURE_COOKIE = \"__Secure-authjs.session-token\";\nconst PLAIN_COOKIE = \"authjs.session-token\";\n\n/** Simplified function types for lazy-loaded external deps. */\ntype DecodeFn = (params: {\n token?: string;\n secret: string | string[];\n salt: string;\n}) => Promise<Record<string, unknown> | null>;\ntype CookiesFn = () => Promise<{ get: (name: string) => { value: string } | undefined }>;\ntype DecodeJwtFn = (token: string) => Record<string, unknown>;\n\n/** Cached dynamic imports for next-auth/jwt decode, next/headers cookies, and jose decodeJwt. */\nlet _decode: DecodeFn | null | undefined;\nlet _cookies: CookiesFn | null | undefined;\nlet _decodeJwt: DecodeJwtFn | null | undefined;\n\n/** Lazy-load decode, cookies, and decodeJwt functions from external deps. Cached after first call. */\nasync function ensureImports(): Promise<boolean> {\n if (_decode === undefined) {\n try {\n const mod = await import(\"next-auth/jwt\");\n _decode = mod.decode as unknown as DecodeFn;\n /* v8 ignore next 3 -- dynamic import only fails when next-auth is not installed */\n } catch {\n _decode = null;\n }\n }\n if (_cookies === undefined) {\n try {\n const mod = await import(\"next/headers\");\n _cookies = mod.cookies as unknown as CookiesFn;\n /* v8 ignore next 3 -- dynamic import only fails when next is not installed */\n } catch {\n _cookies = null;\n }\n }\n if (_decodeJwt === undefined) {\n try {\n const mod = await import(\"jose\");\n _decodeJwt = mod.decodeJwt as unknown as DecodeJwtFn;\n /* v8 ignore next 3 -- dynamic import only fails when jose is not installed */\n } catch {\n _decodeJwt = null;\n }\n }\n /* v8 ignore next -- null branch only when imports fail (untestable with vi.mock) */\n return !!_decode && !!_cookies && !!_decodeJwt;\n}\n\n/** Read and decode the Auth.js session JWT from request cookies. */\nasync function decodeSessionJwt(secret: string): Promise<Record<string, unknown> | null> {\n const cookieStore = await _cookies!();\n const secureCookie = cookieStore.get(SECURE_COOKIE);\n const plainCookie = secureCookie ? undefined : cookieStore.get(PLAIN_COOKIE);\n const cookie = secureCookie ?? plainCookie;\n if (!cookie?.value) return null;\n\n const salt = secureCookie ? SECURE_COOKIE : PLAIN_COOKIE;\n return _decode!({ token: cookie.value, secret, salt });\n}\n\n/**\n * Extract the siteId portion of an Augur bearer token's `client_id` claim.\n * Bearer tokens are JWTs whose payload contains `client_id: \"<numeric>|<siteId>\"`.\n * Returns null on any parse failure or unexpected shape.\n *\n * Uses jose.decodeJwt (no signature verification) — we trust the bearer\n * because the *outer* Auth.js cookie's signature was just verified upstream,\n * so the bearer's contents are trusted as session-issued. This check guards\n * against internal inconsistency between the session's `targetSiteId` and the\n * bearer's scope, not against a forged bearer (the auth provider's signature\n * does that).\n */\nfunction parseBearerClientSiteId(bearer: string): string | null {\n try {\n const payload = _decodeJwt!(bearer);\n const clientId = payload[\"client_id\"];\n if (typeof clientId !== \"string\") return null;\n\n const pipeIndex = clientId.indexOf(\"|\");\n if (pipeIndex < 0) return null;\n\n const siteId = clientId.slice(pipeIndex + 1);\n return siteId.length > 0 ? siteId : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve session credentials from the Auth.js JWT cookie.\n *\n * Trust-boundary mint point: this is the only function in the package that\n * produces {@link SessionCredentials} values. Bytes from a cookie become\n * typed, paired credentials here and only here. The branded pair cannot be\n * constructed elsewhere, so any function consuming `SessionCredentials` is\n * guaranteed to receive a JWT-validated, internally-consistent session.\n *\n * Returns null when:\n * - no AUTH_SECRET is configured\n * - next-auth/jwt, next/headers, or jose cannot be loaded\n * - no session cookie is present\n * - the JWT decode fails or returns null\n * - the decoded payload is missing `targetSiteId` or `token`, or either is\n * not a non-empty string (refuse to mint partial credentials)\n * - the bearer token's `client_id` siteId portion does not match\n * `targetSiteId` (defense-in-depth: refuses internally inconsistent sessions\n * before they reach the augur-api authority check)\n *\n * ## Verified preconditions for `result = some c`\n *\n * AUTH_SECRET configured\n * next-auth/jwt, next/headers, jose all loadable\n * session cookie present and decodable with the secret\n * typeof jwt.targetSiteId === \"string\" ∧ jwt.targetSiteId.length > 0\n * typeof jwt.token === \"string\" ∧ jwt.token.length > 0\n * bearerClientSiteId(jwt.token) = some jwt.targetSiteId\n *\n * Lean equivalent: each clause becomes a `requires` on the function;\n * `result = none` is the disjunction of any failing.\n * F* equivalent: refinement on the option payload covering the\n * conjunction of these clauses.\n *\n * The bearer cross-check (`bearerClientSiteId(jwt.token) = some jwt.targetSiteId`)\n * is the substantive runtime invariant: it refuses sessions where the bearer's\n * encoded `client_id` siteId disagrees with the session's targetSiteId,\n * catching internal-inconsistency bugs before the call reaches augur-api.\n *\n * ## By construction (not independently verified)\n *\n * c.siteId === jwt.targetSiteId (assigned, not checked)\n * c.token === jwt.token (assigned, not checked)\n *\n * ## Brand strength\n *\n * `SessionCredentials` is a TS-level brand: there is no runtime tag on the\n * value. `value as SessionCredentials` casts compile, so the brand is a\n * code-review signal (audit `as SessionCredentials` usages — there should be\n * exactly one, in this function), not a hard type-system gate.\n */\nasync function getSessionCredentials(): Promise<SessionCredentials | null> {\n const secret = getAuthSecret();\n if (!secret) return null;\n /* v8 ignore next -- ensureImports returns false only when dynamic imports fail (untestable with vi.mock) */\n if (!(await ensureImports())) return null;\n\n try {\n const decoded = await decodeSessionJwt(secret);\n if (!decoded) return null;\n\n const targetSiteId = decoded[\"targetSiteId\"];\n const token = decoded[\"token\"];\n\n if (typeof targetSiteId !== \"string\" || targetSiteId.length === 0) return null;\n if (typeof token !== \"string\" || token.length === 0) return null;\n\n const bearerSiteId = parseBearerClientSiteId(token);\n if (bearerSiteId !== targetSiteId) return null;\n\n return { siteId: targetSiteId, token } as unknown as SessionCredentials;\n } catch {\n // Not in a request context (build time, tests), or decode failed\n }\n\n return null;\n}\n\n/**\n * Discriminated result of client resolution.\n *\n * Encodes two structural invariants at the type level:\n *\n * 1. session credentials exist iff this is the scoped path\n * (only `kind: \"scoped\"` carries `credentials`)\n * 2. a usable client exists iff this is NOT the uninit path\n * (`kind: \"scoped\" | \"global\"` always carry `client: object`)\n *\n * The `client: object` constraint replaces the previous `client: unknown` +\n * runtime null check. Anything narrowed to `kind: \"scoped\"` or `kind: \"global\"`\n * is guaranteed by the type system to have a non-null, traversable client —\n * downstream code that walks the SDK namespace path cannot accidentally\n * dereference null. The runtime check moves into `resolveClient` itself, where\n * `kind: \"uninit\"` is constructed when neither a scoped nor a global client is\n * available.\n *\n * Downstream code that wants to derive a cache prefix can only do so on the\n * scoped variant, and only from the credentials carried by that variant —\n * there is no way to construct a cache prefix from a different source without\n * crossing into the type.\n */\ntype ClientResolution =\n | { kind: \"scoped\"; client: object; credentials: SessionCredentials }\n | { kind: \"global\"; client: object }\n | { kind: \"uninit\" };\n\n/**\n * Resolve the SDK client for this request.\n *\n * - If the session JWT validates and a scoped client can be minted, returns\n * the scoped variant carrying the {@link SessionCredentials} that produced\n * the client. The cache prefix is derived at the use site from\n * `credentials.siteId`, structurally guaranteeing it matches the credentials\n * under which the SDK call is made.\n * - Otherwise returns the global variant. No credentials, no cache prefix.\n *\n * The previous return shape `{ client, cachePrefix: string | null }` made\n * \"cachePrefix exists iff scoped\" a runtime invariant; the tagged union\n * promotes it to a type-level one.\n */\nasync function resolveClient(): Promise<ClientResolution> {\n const creds = await getSessionCredentials();\n if (creds) {\n const scoped = getOrCreateScopedClient(creds);\n if (scoped !== null && typeof scoped === \"object\") {\n return { kind: \"scoped\", client: scoped, credentials: creds };\n }\n }\n\n const globalClient = getSdkClientOrNull();\n if (globalClient !== null && typeof globalClient === \"object\") {\n return { kind: \"global\", client: globalClient };\n }\n return { kind: \"uninit\" };\n}\n\n/**\n * Unwrap SDK BaseResponse if the result matches the standard shape.\n * The SDK wraps all responses in `{ data: T, status: number, message: string }`.\n * SiteActions previously unwrapped this; queryAction now does it automatically\n * so consumers receive `T` directly.\n *\n * ## Property\n *\n * ∀ raw. result(raw) ∈ {raw.data, raw}\n * BaseResponse?(raw) ⟺ raw is non-null object ∧ \"data\" ∈ keys(raw)\n * ∧ \"status\" ∈ keys(raw)\n * ∧ \"message\" ∈ keys(raw)\n *\n * Two possible outcomes; never throws, never reshapes. The structural\n * test checks key presence only — it does NOT validate field types or\n * values. Assumes upstream code does not produce `{data, status, message}`\n * shapes that aren't actually BaseResponses; if it does, those will be\n * incorrectly unwrapped (false positive). In practice the augur-api SDK\n * is the only producer of this shape on the server path.\n *\n * This property is what lets queryAction call this exactly once per\n * request without double-unwrap risk: applying unwrapBaseResponse to\n * an already-unwrapped value is a no-op (the second branch of the\n * property fires).\n *\n * ## SDK envelope coupling — forward-compat additive, brittle to renames\n *\n * The structural test checks for `data ∧ status ∧ message`. Three implications:\n *\n * - Additive SDK changes (envelope grows new fields, e.g. `pagination`,\n * `requestId`) are forward-compatible — the predicate still matches and\n * this function still unwraps correctly.\n * - Renames are brittle: if the augur-api SDK ever changes the envelope\n * to `{ result, status, message }` (or any rename of `data`), this\n * function silently STOPS unwrapping. Consumers receive the envelope\n * as `T` and downstream code breaks far from the cause. The fix is\n * mechanical (update the predicate) but the failure mode is silent —\n * audit this function whenever the SDK envelope contract changes.\n * - This predicate MUST stay in sync with augur-api's BaseResponse type.\n * Treat the envelope shape as a coupled contract, not as inferred behaviour.\n */\nfunction unwrapBaseResponse(raw: unknown): unknown {\n if (\n raw != null &&\n typeof raw === \"object\" &&\n \"data\" in raw &&\n \"status\" in raw &&\n \"message\" in raw\n ) {\n return (raw as { data: unknown }).data;\n }\n return raw;\n}\n\n/**\n * Resolve a dot-separated method path on an object, returning the leaf function.\n *\n * Demands {@link ApprovedMethodPath} so callers must have run the path through\n * `parseMethodPath` first — passing an unvalidated string is a compile error.\n */\nfunction resolveMethod(\n client: unknown,\n methodPath: ApprovedMethodPath,\n): (...a: unknown[]) => Promise<unknown> {\n const segments = methodPath.split(\".\");\n\n let current: unknown = client;\n for (const segment of segments) {\n if (current == null || (typeof current !== \"object\" && typeof current !== \"function\")) {\n throw new Error(\n `Cannot resolve \"${methodPath}\": \"${segment}\" is not accessible on ${typeof current}`,\n );\n }\n current = (current as Record<string, unknown>)[segment];\n }\n\n if (typeof current !== \"function\") {\n throw new Error(`\"${methodPath}\" does not resolve to a function (got ${typeof current})`);\n }\n\n return current as (...a: unknown[]) => Promise<unknown>;\n}\n\n/**\n * Bind a scoped cache wrapper to a fixed prefix, producing an `SdkCallWrapper`\n * with the same signature as the global wrapper.\n *\n * On the scoped queryAction path, the cache prefix is derived structurally\n * from the `SessionCredentials` that minted the client (`${credentials.siteId}:`).\n * Capturing that prefix in a closure here lets queryAction's call site treat\n * scoped and global wrappers uniformly — the only thing that differs between\n * them is which prefix gets baked in, and that decision happens in exactly one\n * place per request.\n *\n * Returns null when no scoped wrapper is registered, so the caller falls\n * through to the unwrapped SDK call. The closure preserves the cross-tenant\n * invariant: prefix is captured at bind time from the same credentials value\n * used to mint the scoped client, and cannot be replaced or re-sourced later.\n *\n * ## Property\n *\n * bindScopedPrefix(null, _) = null\n * bindScopedPrefix(w, p)(methodPath, fn, ...args) = w(p, methodPath, fn, ...args)\n *\n * The bound wrapper forwards faithfully — it adds nothing, drops nothing,\n * and reorders nothing. Every effect (cache read, cache write, SDK call)\n * happens inside the underlying scopedWrapper exactly as if queryAction had\n * called it directly with the prefix as the first argument.\n */\nfunction bindScopedPrefix(\n scopedWrapper: ScopedCacheWrapper | null,\n prefix: string,\n): SdkCallWrapper | null {\n if (!scopedWrapper) return null;\n return (methodPath, sdkCall, ...keyArgs) =>\n scopedWrapper(prefix, methodPath, sdkCall, ...keyArgs);\n}\n\n/**\n * Generic server action that routes any SDK method call through the raw\n * SDK client with optional Redis caching. Used internally by\n * `createServerQueryProxy()` to bridge client-side React Query hooks\n * to server-side API calls.\n *\n * For read methods (get, list, lookup, search, suggest), the call is\n * wrapped in the registered cache wrapper (Redis) if one was registered\n * by createServerSite(). Write methods bypass caching.\n *\n * When the request has an active session with targetSiteId + token\n * (from cross-site auth), the call uses a scoped SDK client with those\n * credentials. Redis caching uses targetSiteId as the cache prefix so\n * users managing the same site share cached data.\n *\n * SDK responses wrapped in BaseResponse are automatically unwrapped --\n * consumers receive `T` instead of `{ data: T, status, message }`.\n *\n * This is the chokepoint: every B2B site without a client-side SDK\n * routes EVERY data access through this one function. The invariants\n * below are load-bearing across every site, every request, every user.\n *\n * ## Preconditions (enforced at runtime via thrown Error)\n *\n * parseMethodPath(methodPath) ≠ null\n * resolveClient().client ≠ null\n *\n * First clause: methodPath is a non-empty string AND — if an allowlist\n * has been registered via `registerAllowedMethodPaths` — methodPath is\n * in the allowlist. Assumes the site opted into surface restriction\n * when narrower-than-augur-api authority is desired; otherwise any\n * non-empty string passes (transparent forwarder default).\n *\n * Second clause: createServerSite() ran during bootstrap OR\n * AUGUR_SITE_ID + AUGUR_JWT env vars are set so the registry can\n * auto-init. Assumes the caller has bootstrapped one of the two paths.\n *\n * Lean equivalent: `requires path : ApprovedMethodPath ∧ client : SDKClient`.\n *\n * ## Cross-tenant cache-prefix invariant (load-bearing)\n *\n * resolution.kind = \"scoped\" ⟹ cachePrefix = `${resolution.credentials.siteId}:`\n *\n * On the scoped path the cache prefix is derived structurally from the\n * same `SessionCredentials` value that minted the scoped client — they\n * cannot be sourced separately. This makes \"siteId from session A\n * combined with token from session B\" or \"siteId X with cache prefix Y\"\n * unrepresentable here. Assumes `getSessionCredentials` performed the\n * bearer/session siteId cross-check at mint time; see the brand-strength\n * caveat on `SessionCredentials`.\n *\n * A regression here would silently leak cached data across tenants.\n * The structural derivation is the only thing standing between the\n * request and that leak — do not reintroduce a separate `cachePrefix`\n * parameter or compute it from anything other than `resolution.credentials`.\n *\n * ### Sibling assumption — bearer is NOT in the cache key\n *\n * The cross-tenant invariant covers cross-SITE leaks. It does NOT cover\n * intra-site cross-USER leaks: the cache key is `(siteId, methodPath, args)`\n * and the bearer token is intentionally absent. Two users with different\n * bearers on the same site share cached data for cacheable namespaces.\n *\n * This is a deliberate design choice. The assumption is:\n *\n * ∀ namespace ∉ NO_CACHE_PATHS, ∀ siteId, ∀ args.\n * augur-api(bearer_A, siteId, args) = augur-api(bearer_B, siteId, args)\n *\n * i.e. for cacheable namespaces, augur-api's response is bearer-independent\n * within a site. augur-api remains the auth authority; `NO_CACHE_PATHS`\n * (commerce.*, payments.*) is the carve-out for namespaces whose responses\n * ARE bearer-coupled. If a future namespace produces bearer-dependent\n * responses (e.g. user-specific permissions affecting query results), it\n * MUST be added to `NO_CACHE_PATHS` or the bearer MUST become part of the\n * cache key — otherwise this assumption silently produces a permission leak.\n *\n * ## No-edge-cache defense-in-depth (load-bearing)\n *\n * ∀ a ∈ safeArgs. methodPath ∈ NO_CACHE_PATHS ⟹ \"edgeCache\" ∉ keys(a)\n *\n * `stripEdgeCacheForNoCachePaths` removes the `edgeCache` key from every\n * first-level object arg when methodPath belongs to a no-cache namespace\n * (currently `commerce.*`, `payments.*`). The augur-api SDK transforms\n * `edgeCache` into a Cloudflare `cacheSiteId{N}` query param; removing\n * it here guarantees no CDN edge-caching of identity-bound responses\n * even if a caller passed one explicitly or a legacy factory injected\n * one. Assumes `NO_CACHE_PATHS` enumerates every namespace whose\n * responses must not cross identity boundaries.\n *\n * ## Postcondition — BaseResponse pass-through (exactly-once unwrap)\n *\n * result = unwrapBaseResponse(raw)\n * = raw.data when raw is { data, status, message }\n * = raw otherwise\n *\n * Consumers receive `T` directly when the SDK returns\n * `{ data: T, status, message }`, and the original value otherwise.\n * Assumes upstream cache wrappers do NOT themselves unwrap — they\n * return whatever the SDK returned, so unwrapping happens exactly\n * once, here. Double-unwrap (caller + queryAction) would silently\n * strip a layer of legitimate `{data, status, message}` user data\n * when that shape happens to round-trip through the API.\n *\n * ## Effects\n *\n * @mutates Redis (write-through on read methods when a wrapper is registered)\n * @io augur-api SDK (network request)\n * @throws Error when the allowlist gate fails or no client is initialised\n *\n * @param methodPath Dot-separated SDK method path (e.g. \"items.invMast.doc.get\")\n * @param args Arguments to pass to the resolved method\n * @returns The unwrapped result from the SDK method (possibly from Redis cache)\n */\nexport async function queryAction(methodPath: string, ...args: unknown[]): Promise<unknown> {\n const approvedPath = parseMethodPath(methodPath);\n if (approvedPath === null) {\n throw new Error(\n `queryAction: methodPath ${JSON.stringify(methodPath)} is not in the registered allowlist. ` +\n `Register it via registerAllowedMethodPaths() in createServerSite() config.`,\n );\n }\n\n const resolution = await resolveClient();\n if (resolution.kind === \"uninit\") {\n throw new Error(\n \"SDK client not initialized. Call createServerSite() or set AUGUR_SITE_ID + AUGUR_JWT env vars.\",\n );\n }\n\n const resolvedMethod = resolveMethod(resolution.client, approvedPath);\n const leafName = approvedPath.split(\".\").pop()!;\n // Defense in depth: strip `edgeCache` from no-cache paths before the SDK\n // sees it. The augur-api SDK transforms `edgeCache` into a Cloudflare\n // `cacheSiteId{N}` query param; removing it here guarantees no CDN edge\n // caching of identity-bound responses even if a caller explicitly passed\n // one. Also keeps cache keys consistent with what is actually sent.\n const safeArgs = stripEdgeCacheForNoCachePaths(approvedPath, args);\n\n // Pick the wrapper for this resolution's prefix policy. On the scoped path,\n // the prefix is structurally derived from `credentials.siteId` and bound into\n // a closure here — bindScopedPrefix is the only call site that builds it,\n // and the prefix cannot be re-sourced after binding. On the global path, the\n // prefix is closed over by the SdkCallWrapper that createServerSite registered.\n // Both paths now produce a uniform `SdkCallWrapper | null`, so the caching\n // and uncached branches collapse into a single shape below.\n const wrapper: SdkCallWrapper | null =\n resolution.kind === \"scoped\"\n ? bindScopedPrefix(getScopedCacheWrapper(), `${resolution.credentials.siteId}:`)\n : getSdkCallWrapper();\n\n if (wrapper && isReadMethod(leafName)) {\n const result = await wrapper(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);\n return unwrapBaseResponse(result);\n }\n\n const result = await resolvedMethod(...safeArgs);\n return unwrapBaseResponse(result);\n}\n\n/** Reset lazy-loaded imports. Used in tests only. @internal */\nexport function resetSessionImports(): void {\n _decode = undefined;\n _cookies = undefined;\n _decodeJwt = undefined;\n}\n\nexport { unwrapBaseResponse, getSessionCredentials, resolveMethod };\n"],"mappings":";;;;;;;;;;AAoBA,SAAS,cAAc,qCAAqC;AAG5D,IAAM,gBAAgB;AACtB,IAAM,eAAe;AAYrB,IAAI;AACJ,IAAI;AACJ,IAAI;AAGJ,eAAe,gBAAkC;AAC/C,MAAI,YAAY,QAAW;AACzB,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,eAAe;AACxC,gBAAU,IAAI;AAAA,IAEhB,QAAQ;AACN,gBAAU;AAAA,IACZ;AAAA,EACF;AACA,MAAI,aAAa,QAAW;AAC1B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,cAAc;AACvC,iBAAW,IAAI;AAAA,IAEjB,QAAQ;AACN,iBAAW;AAAA,IACb;AAAA,EACF;AACA,MAAI,eAAe,QAAW;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,MAAM;AAC/B,mBAAa,IAAI;AAAA,IAEnB,QAAQ;AACN,mBAAa;AAAA,IACf;AAAA,EACF;AAEA,SAAO,CAAC,CAAC,WAAW,CAAC,CAAC,YAAY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C;AAAA,IAEvD;AAAA,EACF;AAEA,QAAM,aAAa,MAAM,cAAc;AACvC,MAAI,WAAW,SAAS,UAAU;AAChC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,iBAAiB,cAAc,WAAW,QAAQ,YAAY;AACpE,QAAM,WAAW,aAAa,MAAM,GAAG,EAAE,IAAI;AAM7C,QAAM,WAAW,8BAA8B,cAAc,IAAI;AASjE,QAAM,UACJ,WAAW,SAAS,WAChB,iBAAiB,sBAAsB,GAAG,GAAG,WAAW,YAAY,MAAM,GAAG,IAC7E,kBAAkB;AAExB,MAAI,WAAW,aAAa,QAAQ,GAAG;AACrC,UAAMA,UAAS,MAAM,QAAQ,cAAc,MAAM,eAAe,GAAG,QAAQ,GAAG,GAAG,QAAQ;AACzF,WAAO,mBAAmBA,OAAM;AAAA,EAClC;AAEA,QAAM,SAAS,MAAM,eAAe,GAAG,QAAQ;AAC/C,SAAO,mBAAmB,MAAM;AAClC;AAGO,SAAS,sBAA4B;AAC1C,YAAU;AACV,aAAW;AACX,eAAa;AACf;","names":["result"]}
@@ -6,6 +6,7 @@ var _cachedAuthSecret = null;
6
6
  var _cachedClientFactory = null;
7
7
  var _cachedScopedCacheWrapper = null;
8
8
  var _scopedClient = null;
9
+ var _allowedMethodPaths = null;
9
10
  function registerSdkClient(client) {
10
11
  _cachedClient = client;
11
12
  g.__augur_sdk_client = client;
@@ -45,15 +46,22 @@ function registerScopedCacheWrapper(wrapper) {
45
46
  function getScopedCacheWrapper() {
46
47
  return g.__augur_scoped_cache_wrapper ?? _cachedScopedCacheWrapper ?? null;
47
48
  }
48
- function getOrCreateScopedClient(siteId, bearerToken) {
49
- const key = `${siteId}\0${bearerToken}`;
49
+ function getOrCreateScopedClient(credentials) {
50
+ const { siteId, token } = credentials;
51
+ const key = `${siteId}\0${token}`;
50
52
  if (_scopedClient?.key === key) return _scopedClient.client;
51
53
  const factory = g.__augur_client_factory ?? _cachedClientFactory;
52
54
  if (!factory) return null;
53
- const client = factory(siteId, bearerToken);
55
+ const client = factory(siteId, token);
54
56
  _scopedClient = { key, client };
55
57
  return client;
56
58
  }
59
+ function parseMethodPath(candidate) {
60
+ if (typeof candidate !== "string" || candidate.length === 0) return null;
61
+ const allowed = g.__augur_allowed_method_paths ?? _allowedMethodPaths;
62
+ if (allowed !== null && !allowed.has(candidate)) return null;
63
+ return candidate;
64
+ }
57
65
 
58
66
  export {
59
67
  registerSdkClient,
@@ -65,6 +73,7 @@ export {
65
73
  registerClientFactory,
66
74
  registerScopedCacheWrapper,
67
75
  getScopedCacheWrapper,
68
- getOrCreateScopedClient
76
+ getOrCreateScopedClient,
77
+ parseMethodPath
69
78
  };
70
- //# sourceMappingURL=chunk-HPQQYROJ.js.map
79
+ //# sourceMappingURL=chunk-ALTIINP6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk-client-store.ts"],"sourcesContent":["/**\n * Lightweight getter/setter for the raw SDK client instance, cache wrapper,\n * auth secret, client factory, and scoped client cache.\n *\n * queryAction resolves method paths on the SDK client directly (not on\n * SiteActions). This ensures the proxy pattern works end-to-end: the\n * proxy generates SDK namespace paths (e.g. \"pricing.priceEngine.get\")\n * which match the SDK client structure.\n *\n * The cache wrapper is a function registered by createServerSite() that\n * wraps SDK calls with Redis caching. It captures withServerCache + config\n * in its closure, so queryAction can use it without importing heavy deps.\n *\n * The auth secret, client factory, and scoped cache wrapper support\n * per-request session credentials for multi-tenant apps. queryAction\n * decodes the JWT from request cookies and creates scoped SDK clients\n * when the session contains a targetSiteId + token.\n *\n * This module has ZERO imports from actions/site, cache/, or any factory.\n * Same isolation constraints as site-actions-store.ts.\n */\n\n/** Function that wraps an SDK call with server-side caching. */\nexport type SdkCallWrapper = (\n methodPath: string,\n sdkCall: () => Promise<unknown>,\n ...keyArgs: unknown[]\n) => Promise<unknown>;\n\n/** Function that wraps an SDK call with server-side caching using a specific prefix. */\nexport type ScopedCacheWrapper = (\n prefix: string,\n methodPath: string,\n sdkCall: () => Promise<unknown>,\n ...keyArgs: unknown[]\n) => Promise<unknown>;\n\n/** Function that creates a scoped SDK client with different credentials. */\nexport type ClientFactory = (siteId: string, bearerToken: string) => unknown;\n\ndeclare const SessionSiteIdBrand: unique symbol;\ndeclare const SessionBearerTokenBrand: unique symbol;\ndeclare const SessionCredentialsBrand: unique symbol;\ndeclare const ApprovedMethodPathBrand: unique symbol;\n\n/**\n * Site identifier extracted from a validated Auth.js session JWT cookie.\n *\n * Intended to be minted only by `getSessionCredentials` in query-action.ts.\n *\n * Brand strength: code-review signal, not type-system enforcement. TypeScript\n * allows `value as SessionSiteId` casts, so audit `as SessionSiteId` usages\n * to catch unintended mints — there should be exactly one, at the JWT mint\n * point.\n */\nexport type SessionSiteId = string & { readonly [SessionSiteIdBrand]: true };\n\n/**\n * Bearer token extracted from a validated Auth.js session JWT cookie.\n * Same intended-mint and brand-strength caveat as {@link SessionSiteId}.\n */\nexport type SessionBearerToken = string & { readonly [SessionBearerTokenBrand]: true };\n\n/**\n * Paired session credentials. Bundles `siteId` and `token` from the same\n * validated session into one value so downstream functions can accept the\n * pair as a unit, instead of two separate parameters that callers might\n * accidentally mix across sessions.\n *\n * Intended to be minted only by `getSessionCredentials` in query-action.ts,\n * which performs the cross-check that the bearer's `client_id` siteId\n * matches `targetSiteId`. Anything that holds a `SessionCredentials` *was*\n * cross-checked at mint time — provided the value came through that mint\n * and not via a cast.\n *\n * Brand strength: same code-review signal as the field brands. `value as\n * SessionCredentials` compiles. Audit `as SessionCredentials` usages — there\n * should be exactly one, in `getSessionCredentials`.\n */\nexport type SessionCredentials = {\n readonly siteId: SessionSiteId;\n readonly token: SessionBearerToken;\n readonly [SessionCredentialsBrand]: true;\n};\n\n/**\n * SDK method path validated against the registered allowlist.\n *\n * Intended to be minted only by `parseMethodPath` below. Functions that walk\n * the path into the SDK client (notably `resolveMethod`) demand this type\n * so that an unvalidated string flowing into the walker is a compile error\n * for code that respects the convention.\n *\n * Brand strength: code-review signal. `value as ApprovedMethodPath` compiles.\n * Audit `as ApprovedMethodPath` usages — there should be one, in\n * `parseMethodPath`.\n *\n * Scope of validation: this is a *site-level surface restriction*, not a\n * security boundary. augur-api is the auth authority; the allowlist limits\n * what the application's proxy will forward to the SDK, not what tokens are\n * permitted to do. Useful for narrowing same-origin attack surface (XSS,\n * malicious bundled deps); not a substitute for API-level authorization.\n */\nexport type ApprovedMethodPath = string & { readonly [ApprovedMethodPathBrand]: true };\n\nconst g = globalThis as unknown as {\n __augur_sdk_client?: unknown;\n __augur_sdk_call_wrapper?: SdkCallWrapper;\n __augur_auth_secret?: string;\n __augur_client_factory?: ClientFactory;\n __augur_scoped_cache_wrapper?: ScopedCacheWrapper;\n __augur_allowed_method_paths?: Set<string>;\n};\n\nlet _cachedClient: unknown = null;\nlet _cachedWrapper: SdkCallWrapper | null = null;\nlet _cachedAuthSecret: string | null = null;\nlet _cachedClientFactory: ClientFactory | null = null;\nlet _cachedScopedCacheWrapper: ScopedCacheWrapper | null = null;\nlet _scopedClient: { key: string; client: unknown } | null = null;\nlet _allowedMethodPaths: Set<string> | null = null;\n\n/** Register the raw SDK client instance. Called by createServerSite(). */\nexport function registerSdkClient(client: unknown): void {\n _cachedClient = client;\n g.__augur_sdk_client = client;\n}\n\n/** Returns the registered SDK client, or null if not yet registered. */\nexport function getSdkClientOrNull(): unknown {\n const client = g.__augur_sdk_client ?? _cachedClient;\n if (client) {\n if (!g.__augur_sdk_client) {\n g.__augur_sdk_client = client;\n }\n return client;\n }\n return null;\n}\n\n/**\n * Register a cache wrapper for SDK calls. Called by createServerSite().\n * The wrapper captures withServerCache + config in its closure so that\n * queryAction can use Redis caching without importing heavy deps.\n */\nexport function registerSdkCallWrapper(wrapper: SdkCallWrapper): void {\n _cachedWrapper = wrapper;\n g.__augur_sdk_call_wrapper = wrapper;\n}\n\n/** Returns the registered cache wrapper, or null if not registered. */\nexport function getSdkCallWrapper(): SdkCallWrapper | null {\n return g.__augur_sdk_call_wrapper ?? _cachedWrapper ?? null;\n}\n\n/** Register the auth secret for JWT decoding. Called by createServerSite(). */\nexport function registerAuthSecret(secret: string): void {\n _cachedAuthSecret = secret;\n g.__augur_auth_secret = secret;\n}\n\n/** Returns the registered auth secret, or null if not registered. */\nexport function getAuthSecret(): string | null {\n return g.__augur_auth_secret ?? _cachedAuthSecret ?? null;\n}\n\n/** Register a factory that creates scoped SDK clients. Called by createServerSite(). */\nexport function registerClientFactory(factory: ClientFactory): void {\n _cachedClientFactory = factory;\n g.__augur_client_factory = factory;\n}\n\n/** Returns the registered client factory, or null if not registered. */\nexport function getClientFactory(): ClientFactory | null {\n return g.__augur_client_factory ?? _cachedClientFactory ?? null;\n}\n\n/** Register a scoped cache wrapper that accepts a prefix. Called by createServerSite(). */\nexport function registerScopedCacheWrapper(wrapper: ScopedCacheWrapper): void {\n _cachedScopedCacheWrapper = wrapper;\n g.__augur_scoped_cache_wrapper = wrapper;\n}\n\n/** Returns the registered scoped cache wrapper, or null if not registered. */\nexport function getScopedCacheWrapper(): ScopedCacheWrapper | null {\n return g.__augur_scoped_cache_wrapper ?? _cachedScopedCacheWrapper ?? null;\n}\n\n/**\n * Returns a cached scoped client for the given credentials, or creates one\n * via the registered factory. Caches the last credential pair so that\n * multiple queryAction calls in the same request reuse the same client.\n *\n * Accepts `SessionCredentials` (a branded paired type) rather than two raw\n * strings: well-behaved callers pass the pair as a unit, eliminating the\n * \"siteId from session A combined with token from session B\" mistake at\n * the type level — see {@link SessionCredentials} brand-strength caveat.\n * The factory itself still receives strings (its signature is user-facing API).\n *\n * ## Trust\n *\n * @trusted credentials // the SessionCredentials brand carries the\n * // bearer/session siteId cross-check discharged at\n * // mint time by `getSessionCredentials`. This\n * // function does NOT re-validate; if a non-mint\n * // path produces a SessionCredentials value (via\n * // `as` cast), this function will materialise a\n * // client for whatever siteId + token are present\n * // in the value. Audit `as SessionCredentials`\n * // usages — there should be exactly one, in\n * // getSessionCredentials.\n *\n * ## Decision (Property)\n *\n * let key = `${credentials.siteId}\\0${credentials.token}` in\n * result(credentials) =\n * _scopedClient.client when _scopedClient?.key = key // cache hit\n * factory(siteId, token) when factory ≠ null // mint + cache\n * null when factory = null // uninitialised\n *\n * Three outcomes; never throws. Side effect on the mint path only:\n * `_scopedClient` is replaced with `{key, client}` so the next call with\n * the same credentials hits the cached branch. Minting implicitly evicts\n * the previous `_scopedClient` value (single-slot semantics — see invariant).\n *\n * ## Invariant — null-byte key separator\n *\n * The key `${siteId}\\0${token}` is the unique injective serialisation of\n * the credential pair: `\\0` cannot appear in either field by construction,\n * so distinct `(siteId, token)` pairs always map to distinct keys.\n *\n * - `siteId` is the cross-site `targetSiteId` carried in the JWT body for\n * cross-site-auth flows (see `getSessionCredentials`). The auth provider\n * guarantees it is a non-empty identifier matching `/^[A-Za-z0-9_-]+$/`\n * — alphanumeric with optional `-` and `_`, never null, never containing\n * a literal `\\0`.\n * - `token` is a JWT bearer: base64url-encoded parts joined by `.`. The\n * base64url alphabet `[A-Za-z0-9_-]` and the `.` separator exclude `\\0`.\n *\n * Therefore the cache cannot collide one credential pair onto another's\n * client — the load-bearing security property the cross-tenant invariant\n * in `queryAction` relies on.\n *\n * The regex constraint on `targetSiteId` is currently relied upon from the\n * auth provider's configuration but NOT enforced in code at the mint point\n * in `getSessionCredentials`. The `SessionSiteId` brand only carries proof\n * of \"non-empty string\". If a future change introduces an auth source that\n * does not honour the alphanumeric+dash+underscore constraint, the\n * separator's unambiguity has to be re-derived. Easiest hardening if that\n * ever becomes a concern: add the regex check to `getSessionCredentials`\n * so the brand carries the encoding proof structurally rather than by\n * convention.\n *\n * Do NOT change the separator to a character that could legitimately\n * appear in either field. `-` and `_` are both inside the siteId alphabet\n * AND inside the base64url token alphabet; `:` and `|` are not in either\n * today but offer no margin of safety. `\\0` is the only choice that is\n * structurally guaranteed to be outside both alphabets.\n *\n * ## Invariant — single-slot cache (eviction is implicit)\n *\n * `_scopedClient` holds at most one entry. Minting a client for\n * credentials A AFTER credentials B were cached evicts B unrecoverably;\n * a later request with credentials B will call the factory again rather\n * than retrieving the previously-minted client.\n *\n * This is intentional. Scoped clients are per-request shortcuts; the\n * cache exists to let multiple queryAction calls within a single request\n * share an SDK client without re-running the factory. Cross-request\n * caching is NOT a goal — Next.js may or may not preserve module state\n * across invocations, so any retention beyond the single slot is\n * best-effort and MUST NOT be relied upon for correctness.\n *\n * A future refactor to multi-slot LRU would change this contract:\n * per-credential client identity becomes ambiguous across requests, and\n * eviction policy becomes security-relevant (e.g. oldest-out could re-mint\n * a client immediately after a credential rotation, surfacing stale\n * permissions to the next caller). Do not multi-slot this without\n * re-deriving the contract — particularly the relationship to credential\n * rotation and bearer-token revocation in augur-api.\n *\n * ## Postcondition — identity, not transformation\n *\n * result ≠ null ⟹ result is referentially identical to the value the\n * factory returned for the matching credentials.\n *\n * The cache stores and serves the factory's exact return value. It does\n * not wrap, transform, proxy, or copy the client. Consumers that mutate\n * the returned client (e.g. setting per-request properties on a singleton\n * field) will observe the mutation on subsequent cache hits within the\n * same request — by design.\n */\nexport function getOrCreateScopedClient(credentials: SessionCredentials): unknown {\n const { siteId, token } = credentials;\n const key = `${siteId}\\0${token}`;\n if (_scopedClient?.key === key) return _scopedClient.client;\n\n const factory = g.__augur_client_factory ?? _cachedClientFactory;\n if (!factory) return null;\n\n const client = factory(siteId, token);\n _scopedClient = { key, client };\n return client;\n}\n\n/**\n * Register one or more SDK method paths the application is permitted to call\n * through `queryAction`. Subsequent calls accumulate (idempotent on repeats).\n *\n * This is *site-level surface restriction*, not security. augur-api remains\n * the auth authority; this primitive lets a site narrow its proxy's surface\n * to the methods its UI actually wires up. Useful as defense-in-depth against\n * same-origin XSS or compromised bundled deps POSTing arbitrary methodPaths\n * to `/api/augur` — those calls will hit augur-api with the user's bearer\n * (which augur-api will allow if the bearer is authorized), but the allowlist\n * stops them from leaving the proxy in the first place.\n *\n * Permissive default: if `registerAllowedMethodPaths` is never called, all\n * non-empty paths pass — the proxy behaves as a transparent forwarder, which\n * is the package's design intent. Sites that want surface restriction opt in\n * by calling this function.\n */\nexport function registerAllowedMethodPaths(paths: readonly string[]): void {\n if (_allowedMethodPaths === null) {\n _allowedMethodPaths = new Set();\n g.__augur_allowed_method_paths = _allowedMethodPaths;\n }\n for (const p of paths) _allowedMethodPaths.add(p);\n}\n\n/**\n * Returns true if the application has registered an allowlist via\n * {@link registerAllowedMethodPaths}. When false, `parseMethodPath` operates\n * in permissive mode (any non-empty string passes).\n */\nexport function isMethodPathAllowlistRegistered(): boolean {\n return (g.__augur_allowed_method_paths ?? _allowedMethodPaths) !== null;\n}\n\n/**\n * Validate a candidate method path against the registered allowlist.\n *\n * - Returns the branded value if the path is a non-empty string AND\n * (no allowlist is registered OR the path is in the allowlist).\n * - Returns null if the path is not a non-empty string, or if an allowlist\n * has been registered and the path is not in it.\n *\n * The brand on the return type is the only way internal code can produce an\n * `ApprovedMethodPath`. Functions that walk the path into the SDK should\n * accept `ApprovedMethodPath`, forcing the caller to discharge the validation.\n */\nexport function parseMethodPath(candidate: unknown): ApprovedMethodPath | null {\n if (typeof candidate !== \"string\" || candidate.length === 0) return null;\n const allowed = g.__augur_allowed_method_paths ?? _allowedMethodPaths;\n if (allowed !== null && !allowed.has(candidate)) return null;\n return candidate as ApprovedMethodPath;\n}\n\n/** Clears the registered SDK client, wrapper, and session stores. Used in tests only. @internal */\nexport function clearSdkClient(): void {\n _cachedClient = null;\n _cachedWrapper = null;\n _cachedAuthSecret = null;\n _cachedClientFactory = null;\n _cachedScopedCacheWrapper = null;\n _scopedClient = null;\n _allowedMethodPaths = null;\n g.__augur_sdk_client = undefined;\n g.__augur_sdk_call_wrapper = undefined;\n g.__augur_auth_secret = undefined;\n g.__augur_client_factory = undefined;\n g.__augur_scoped_cache_wrapper = undefined;\n g.__augur_allowed_method_paths = undefined;\n}\n"],"mappings":";AAyGA,IAAM,IAAI;AASV,IAAI,gBAAyB;AAC7B,IAAI,iBAAwC;AAC5C,IAAI,oBAAmC;AACvC,IAAI,uBAA6C;AACj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IAAI,SAAS,EAAG,QAAO;AACxD,SAAO;AACT;","names":[]}
@@ -1,5 +1,6 @@
1
1
  // src/query-options-helper.ts
2
2
  import { CACHE_CONFIG } from "@simpleapps-com/augur-utils";
3
+ import { resolveGcTime } from "@simpleapps-com/augur-core";
3
4
  var createQueryOptions = ({
4
5
  baseKey,
5
6
  params,
@@ -19,7 +20,7 @@ var createQueryOptions = ({
19
20
  queryFn: () => queryFn(params),
20
21
  enabled: enabledFn ? enabledFn(params) : true,
21
22
  staleTime,
22
- gcTime
23
+ gcTime: resolveGcTime(gcTime)
23
24
  };
24
25
  };
25
26
  var createSuspenseQueryOptions = ({
@@ -39,7 +40,7 @@ var createSuspenseQueryOptions = ({
39
40
  queryKey,
40
41
  queryFn: () => queryFn(params),
41
42
  staleTime,
42
- gcTime
43
+ gcTime: resolveGcTime(gcTime)
43
44
  };
44
45
  };
45
46
 
@@ -47,4 +48,4 @@ export {
47
48
  createQueryOptions,
48
49
  createSuspenseQueryOptions
49
50
  };
50
- //# sourceMappingURL=chunk-TQP67TGL.js.map
51
+ //# sourceMappingURL=chunk-PIYHMA6F.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/query-options-helper.ts"],"sourcesContent":["import type { UseQueryOptions, UseSuspenseQueryOptions } from \"@tanstack/react-query\";\nimport { CACHE_CONFIG } from \"@simpleapps-com/augur-utils\";\nimport { resolveGcTime } from \"@simpleapps-com/augur-core\";\n\nexport interface QueryOptionsConfig<TParams, TData> {\n /** Base query key (e.g., \"customer-orders\") */\n baseKey: string;\n /** Parameters object */\n params: TParams;\n /** Function that returns the data */\n queryFn: (params: TParams) => Promise<TData>;\n /** Function to determine if query should be enabled */\n enabledFn?: (params: TParams) => boolean;\n /** Custom stale time in milliseconds (default: SEMI_STATIC) */\n staleTime?: number;\n /**\n * Custom garbage collection time in milliseconds (default: SEMI_STATIC).\n * Browser only: on the server the returned gcTime is always `Infinity`\n * (no GC timer), so the per-request cache is freed with the request (#481).\n */\n gcTime?: number;\n /** Key to exclude from query key generation */\n excludeFromKey?: keyof TParams;\n}\n\n/**\n * Creates useQuery options with consistent key generation.\n * Filters out undefined/null/empty params from the query key.\n */\nexport const createQueryOptions = <TParams extends Record<string, unknown>, TData>({\n baseKey,\n params,\n queryFn,\n enabledFn,\n staleTime = CACHE_CONFIG.SEMI_STATIC.staleTime,\n gcTime = CACHE_CONFIG.SEMI_STATIC.gcTime,\n excludeFromKey,\n}: QueryOptionsConfig<TParams, TData>): UseQueryOptions<TData> => {\n const paramEntries = Object.entries(params)\n .filter(([key, value]) => {\n if (excludeFromKey && key === excludeFromKey) return false;\n return value !== undefined && value !== null && value !== \"\";\n })\n .map(([key, value]) => `${key}:${value}`)\n .sort();\n\n const queryKey = [baseKey, ...paramEntries];\n\n return {\n queryKey,\n queryFn: () => queryFn(params),\n enabled: enabledFn ? enabledFn(params) : true,\n staleTime,\n gcTime: resolveGcTime(gcTime),\n };\n};\n\n/**\n * Creates useSuspenseQuery options with consistent key generation.\n * Same as createQueryOptions but without enabledFn (suspense queries\n * cannot be disabled).\n */\nexport const createSuspenseQueryOptions = <TParams extends Record<string, unknown>, TData>({\n baseKey,\n params,\n queryFn,\n staleTime = CACHE_CONFIG.SEMI_STATIC.staleTime,\n gcTime = CACHE_CONFIG.SEMI_STATIC.gcTime,\n excludeFromKey,\n}: Omit<QueryOptionsConfig<TParams, TData>, \"enabledFn\">): UseSuspenseQueryOptions<TData> => {\n const paramEntries = Object.entries(params)\n .filter(([key, value]) => {\n if (excludeFromKey && key === excludeFromKey) return false;\n return value !== undefined && value !== null && value !== \"\";\n })\n .map(([key, value]) => `${key}:${value}`)\n .sort();\n\n const queryKey = [baseKey, ...paramEntries];\n\n return {\n queryKey,\n queryFn: () => queryFn(params),\n staleTime,\n gcTime: resolveGcTime(gcTime),\n };\n};\n"],"mappings":";AACA,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AA2BvB,IAAM,qBAAqB,CAAiD;AAAA,EACjF;AAAA,EACA;AAA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"./chunk-ZUJZDRTP.js";
5
- import "./chunk-HPQQYROJ.js";
4
+ } from "./chunk-2NL4QKJN.js";
5
+ import "./chunk-ALTIINP6.js";
6
6
  import "./chunk-DGUM43GV.js";
7
7
 
8
8
  // src/hooks.ts
package/dist/index.d.ts CHANGED
@@ -84,7 +84,7 @@ declare function batchFetch<TParam, TKey extends string | number, TData>(params:
84
84
  * Creates a server-side query client optimised for prefetching.
85
85
  *
86
86
  * - No persistence (server-only)
87
- * - Longer cache times for prefetched data
87
+ * - No GC timers (gcTime: Infinity), so the client is freed with the request
88
88
  * - No retries (fail fast on server)
89
89
  * - No refetching (server renders are one-shot)
90
90
  */
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createQueryOptions,
3
3
  createSuspenseQueryOptions
4
- } from "./chunk-TQP67TGL.js";
4
+ } from "./chunk-PIYHMA6F.js";
5
5
  import {
6
6
  batchFetch,
7
7
  cacheGet,
@@ -21,8 +21,8 @@ import {
21
21
  unwrap,
22
22
  unwrapOr,
23
23
  withServerCache
24
- } from "./chunk-WOHZDFJF.js";
25
- import "./chunk-HPQQYROJ.js";
24
+ } from "./chunk-26WZBC4F.js";
25
+ import "./chunk-ALTIINP6.js";
26
26
  import "./chunk-DGUM43GV.js";
27
27
 
28
28
  // src/server-query-client.ts
@@ -34,7 +34,9 @@ function createServerQueryClient() {
34
34
  defaultOptions: {
35
35
  queries: {
36
36
  staleTime: CACHE_CONFIG.STATIC.staleTime,
37
- gcTime: CACHE_CONFIG.STATIC.staleTime,
37
+ // Infinity = no GC timer. A finite value pins this per-request client
38
+ // (and its whole cache) in memory until the timer fires (#481).
39
+ gcTime: Infinity,
38
40
  retry: 0,
39
41
  refetchOnMount: false,
40
42
  refetchOnWindowFocus: false,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server-query-client.ts","../src/recaptcha.ts"],"sourcesContent":["import { cache } from \"react\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { CACHE_CONFIG } from \"@simpleapps-com/augur-utils\";\n\n/**\n * Creates a server-side query client optimised for prefetching.\n *\n * - No persistence (server-only)\n * - Longer cache times for prefetched data\n * - No retries (fail fast on server)\n * - No refetching (server renders are one-shot)\n */\nexport function createServerQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: CACHE_CONFIG.STATIC.staleTime,\n gcTime: CACHE_CONFIG.STATIC.staleTime,\n retry: 0,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n },\n },\n });\n}\n\n/**\n * Returns a per-request singleton QueryClient for React Server Components.\n *\n * React's `cache()` deduplicates calls within a single server request,\n * so each request gets its own QueryClient while avoiding the cross-request\n * state leakage that a module-level singleton would cause.\n */\nexport const getServerQueryClient = cache((): QueryClient => createServerQueryClient());\n","/**\n * Server-side Google reCAPTCHA v3 verification.\n * Used by API routes that accept public form submissions.\n */\nexport async function verifyRecaptcha(token: string): Promise<boolean> {\n try {\n const secretKey = process.env[\"RECAPTCHA_SECRET_KEY\"];\n if (!secretKey) return false;\n\n const res = await fetch(\"https://www.google.com/recaptcha/api/siteverify\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({ secret: secretKey, response: token }),\n });\n if (!res.ok) {\n console.error(\"reCAPTCHA verify failed:\", res.status);\n return false;\n }\n const result = (await res.json()) as { success?: boolean };\n return result.success === true;\n } catch (error) {\n console.error(\"reCAPTCHA verify error:\", error);\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB;AAUtB,SAAS,0BAAuC;AACrD,SAAO,IAAI,YAAY;AAAA,IACrB,gBAAgB;AAAA,MACd,SAAS;AAAA,QACP,WAAW,aAAa,OAAO;AAAA,QAC/B,QAAQ,aAAa,OAAO;AAAA,QAC5B,OAAO;AAAA,QACP,gBAAgB;AAAA,QAChB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AASO,IAAM,uBAAuB,MAAM,MAAmB,wBAAwB,CAAC;;;AC9BtF,eAAsB,gBAAgB,OAAiC;AACrE,MAAI;AACF,UAAM,YAAY,QAAQ,IAAI,sBAAsB;AACpD,QAAI,CAAC,UAAW,QAAO;AAEvB,UAAM,MAAM,MAAM,MAAM,mDAAmD;AAAA,MACzE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,MAC/D,MAAM,IAAI,gBAAgB,EAAE,QAAQ,WAAW,UAAU,MAAM,CAAC;AAAA,IAClE,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,cAAQ,MAAM,4BAA4B,IAAI,MAAM;AACpD,aAAO;AAAA,IACT;AACA,UAAM,SAAU,MAAM,IAAI,KAAK;AAC/B,WAAO,OAAO,YAAY;AAAA,EAC5B,SAAS,OAAO;AACd,YAAQ,MAAM,2BAA2B,KAAK;AAC9C,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/server-query-client.ts","../src/recaptcha.ts"],"sourcesContent":["import { cache } from \"react\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { CACHE_CONFIG } from \"@simpleapps-com/augur-utils\";\n\n/**\n * Creates a server-side query client optimised for prefetching.\n *\n * - No persistence (server-only)\n * - No GC timers (gcTime: Infinity), so the client is freed with the request\n * - No retries (fail fast on server)\n * - No refetching (server renders are one-shot)\n */\nexport function createServerQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: CACHE_CONFIG.STATIC.staleTime,\n // Infinity = no GC timer. A finite value pins this per-request client\n // (and its whole cache) in memory until the timer fires (#481).\n gcTime: Infinity,\n retry: 0,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n },\n },\n });\n}\n\n/**\n * Returns a per-request singleton QueryClient for React Server Components.\n *\n * React's `cache()` deduplicates calls within a single server request,\n * so each request gets its own QueryClient while avoiding the cross-request\n * state leakage that a module-level singleton would cause.\n */\nexport const getServerQueryClient = cache((): QueryClient => createServerQueryClient());\n","/**\n * Server-side Google reCAPTCHA v3 verification.\n * Used by API routes that accept public form submissions.\n */\nexport async function verifyRecaptcha(token: string): Promise<boolean> {\n try {\n const secretKey = process.env[\"RECAPTCHA_SECRET_KEY\"];\n if (!secretKey) return false;\n\n const res = await fetch(\"https://www.google.com/recaptcha/api/siteverify\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({ secret: secretKey, response: token }),\n });\n if (!res.ok) {\n console.error(\"reCAPTCHA verify failed:\", res.status);\n return false;\n }\n const result = (await res.json()) as { success?: boolean };\n return result.success === true;\n } catch (error) {\n console.error(\"reCAPTCHA verify error:\", error);\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB;AAUtB,SAAS,0BAAuC;AACrD,SAAO,IAAI,YAAY;AAAA,IACrB,gBAAgB;AAAA,MACd,SAAS;AAAA,QACP,WAAW,aAAa,OAAO;AAAA;AAAA;AAAA,QAG/B,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,gBAAgB;AAAA,QAChB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AASO,IAAM,uBAAuB,MAAM,MAAmB,wBAAwB,CAAC;;;AChCtF,eAAsB,gBAAgB,OAAiC;AACrE,MAAI;AACF,UAAM,YAAY,QAAQ,IAAI,sBAAsB;AACpD,QAAI,CAAC,UAAW,QAAO;AAEvB,UAAM,MAAM,MAAM,MAAM,mDAAmD;AAAA,MACzE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,MAC/D,MAAM,IAAI,gBAAgB,EAAE,QAAQ,WAAW,UAAU,MAAM,CAAC;AAAA,IAClE,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,cAAQ,MAAM,4BAA4B,IAAI,MAAM;AACpD,aAAO;AAAA,IACT;AACA,UAAM,SAAU,MAAM,IAAI,KAAK;AAC/B,WAAO,OAAO,YAAY;AAAA,EAC5B,SAAS,OAAO;AACd,YAAQ,MAAM,2BAA2B,KAAK;AAC9C,WAAO;AAAA,EACT;AACF;","names":[]}