@simpleapps-com/augur-server 2026.11.3 → 2026.11.4
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.
- package/EXPORTS.md +3 -2
- package/README.md +12 -12
- package/dist/api-handler.d.ts +2 -1
- package/dist/api-handler.d.ts.map +1 -1
- package/dist/api.js +12 -8
- package/dist/api.js.map +1 -1
- package/dist/auth.js +2 -2
- package/dist/{chunk-5I7TBMGU.js → chunk-34NCJS52.js} +2 -2
- package/dist/{chunk-RGOLZMU3.js → chunk-B4MGIUCU.js} +12 -3
- package/dist/{chunk-RGOLZMU3.js.map → chunk-B4MGIUCU.js.map} +1 -1
- package/dist/{chunk-22B3WOGA.js → chunk-F7QWHMHH.js} +2 -2
- package/dist/{chunk-R573MZQL.js → chunk-WR7WT2FI.js} +12 -7
- package/dist/chunk-WR7WT2FI.js.map +1 -0
- package/dist/hooks.js +2 -2
- package/dist/index.js +2 -2
- package/dist/query-action.d.ts +21 -98
- package/dist/query-action.d.ts.map +1 -1
- package/dist/query-action.js +4 -2
- package/dist/rules.d.ts +20 -4
- package/dist/rules.d.ts.map +1 -1
- package/dist/site.js +3 -3
- package/dist/testing.js +2 -2
- package/llms.txt +3 -2
- package/package.json +2 -2
- package/dist/chunk-R573MZQL.js.map +0 -1
- /package/dist/{chunk-5I7TBMGU.js.map → chunk-34NCJS52.js.map} +0 -0
- /package/dist/{chunk-22B3WOGA.js.map → chunk-F7QWHMHH.js.map} +0 -0
|
@@ -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, the proved pure `rules` (with @atlas/utils' string scans, bundled), plus augur-core\n// and augur-api's `isSiteId` (both external in tsup — not bundled into chunks; every site\n// already loads the SDK on the server).\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 getCrossSite,\n getOrCreateScopedClient,\n getScopedCacheWrapper,\n parseMethodPath,\n type SessionCredentials,\n type ApprovedMethodPath,\n type SdkCallWrapper,\n type ScopedCacheWrapper,\n} from \"./sdk-client-store\";\nimport {\n isReadMethod,\n stripEdgeCacheForNoCachePaths,\n unwrapBaseResponse,\n} from \"@simpleapps-com/augur-core\";\nimport { isSiteId, type BaseResponse } from \"@simpleapps-com/augur-api\";\nimport {\n clientIdSiteIdOf,\n mintedCredentials,\n readsSession,\n resolutionOf,\n scopedPrefix,\n usesCache,\n} from \"./rules\";\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 } catch {\n // next-auth is an optional peer: without it there are no session credentials\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 } catch {\n // outside Next.js there is no request cookie store\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 } catch {\n // jose is an optional peer: without it the bearer cannot be cross-checked\n _decodeJwt = null;\n }\n }\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 return clientIdSiteIdOf(clientId);\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. No other production code\n * constructs the branded pair, so a `SessionCredentials` that came through\n * this mint is JWT-validated and internally consistent. The brand is not\n * enforced by the compiler: an `as SessionCredentials` cast compiles (tests\n * do it), so audit casts (see \"Brand strength\" below).\n *\n * Returns null when:\n * - the site did not opt in to cross-site sessions (`createServerSite`'s\n * `auth: { crossSite: true }`, atlas#105): then nothing is imported and no\n * cookie is read, so pages using queryAction can render statically\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 * - `targetSiteId` fails augur-api's `isSiteId` (`[a-z0-9_-]+`): siteIds are\n * lowercase by convention, and the scoped-client key's injectivity proof\n * (`scoped-client-key.ts`) needs a NUL-free siteId\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\" ∧ isSiteId(jwt.targetSiteId) // implies non-empty\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 // Only an opted-in site with a secret looks for a session (rules.readsSession, atlas#105):\n // every other site returns here, before next/headers is imported or cookies() read, so its\n // pages can render statically.\n if (!readsSession(getCrossSite(), Boolean(secret))) return null;\n if (!(await ensureImports())) return null;\n\n try {\n // readsSession held, so the secret is present (Boolean(secret) above).\n const decoded = await decodeSessionJwt(secret as string);\n if (!decoded) return null;\n\n const targetSiteId = decoded[\"targetSiteId\"];\n const token = decoded[\"token\"];\n\n if (typeof targetSiteId !== \"string\" || typeof token !== \"string\") return null;\n\n // An empty or undecodable token has no client_id siteId (\"\").\n const bearerSiteId = parseBearerClientSiteId(token) ?? \"\";\n const mint = mintedCredentials(isSiteId(targetSiteId), targetSiteId, token, bearerSiteId);\n if (mint.kind === \"refused\") return null;\n\n return { siteId: mint.siteId, token: mint.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 const scoped = creds ? getOrCreateScopedClient(creds) : null;\n const globalClient = getSdkClientOrNull();\n const kind = resolutionOf(creds !== null, isObject(scoped), isObject(globalClient));\n if (kind === \"scoped\") return { kind, client: scoped as object, credentials: creds! };\n if (kind === \"global\") return { kind, client: globalClient as object };\n return { kind };\n}\n\n/** A usable client: a non-null object. */\nfunction isObject(value: unknown): boolean {\n return value !== null && typeof value === \"object\";\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 * The one SDK call behind the two server actions, `queryAction` (the\n * envelope's data) and `queryActionRaw` (the result as returned): routes\n * any SDK method call through the raw SDK client with optional Redis\n * caching. `queryAction` is used internally by `createServerQueryProxy()`\n * to bridge client-side React Query hooks 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 * 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 — the SDK's result as returned\n *\n * result = raw (the SDK's result, from the call or the raw cache)\n *\n * Assumes upstream cache wrappers do NOT themselves unwrap — they\n * return whatever the SDK returned (the raw key space, #98), so\n * `queryAction` unwraps exactly once and `queryActionRaw` never does\n * (model: AugurServer.QueryResult).\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 */\nasync function callSdk(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(), scopedPrefix(resolution.credentials.siteId))\n : getSdkCallWrapper();\n\n if (usesCache(wrapper !== null, isReadMethod(leafName))) {\n return wrapper!(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);\n }\n return resolvedMethod(...safeArgs);\n}\n\n/**\n * The SDK call `callSdk` makes (everything above), answered as its envelope's data.\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 * Double-unwrap (caller + queryAction) would silently strip a layer of\n * legitimate `{data, status, message}` user data when that shape happens\n * to round-trip through the API. The envelope's paging (`total`,\n * `totalResults`, `count`) is not in `data`: read it with `queryActionRaw`.\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 return unwrapBaseResponse(await callSdk(methodPath, args));\n}\n\n/**\n * The same call as `queryAction` (allowlist, client, `edgeCache` strip, Redis), answered as\n * the SDK returned it: augur-api's `BaseResponse<T>` envelope (every SDK method's result) with\n * `data`, `total`, `totalResults` and `count`, so client code can page a list (atlas#107). A\n * method path carries no type, so the caller names `T` (`queryActionRaw<Article[]>(…)`). A\n * `queryAction` and a `queryActionRaw` of one call share one Redis entry.\n *\n * MUST NOT run under a React Query key that also holds `queryAction`'s shape (an options\n * proxy's `queryKey`): give it its own key.\n *\n * @param methodPath Dot-separated SDK method path (e.g. \"joomla.content.list\")\n * @param args Arguments to pass to the resolved method\n * @returns The SDK method's result unchanged (possibly from Redis cache)\n */\nexport async function queryActionRaw<T = unknown>(\n methodPath: string,\n ...args: unknown[]\n): Promise<BaseResponse<T>> {\n return callSdk(methodPath, args) as Promise<BaseResponse<T>>;\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":";;;;;;;;;;;;;;;;;AAuBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAmC;AAW5C,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,IAChB,QAAQ;AAEN,gBAAU;AAAA,IACZ;AAAA,EACF;AACA,MAAI,aAAa,QAAW;AAC1B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,cAAc;AACvC,iBAAW,IAAI;AAAA,IACjB,QAAQ;AAEN,iBAAW;AAAA,IACb;AAAA,EACF;AACA,MAAI,eAAe,QAAW;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,MAAM;AAC/B,mBAAa,IAAI;AAAA,IACnB,QAAQ;AAEN,mBAAa;AAAA,IACf;AAAA,EACF;AACA,SAAO,CAAC,CAAC,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;AACtC;AAGA,eAAe,iBAAiB,QAAyD;AACvF,QAAM,cAAc,MAAM,SAAU;AACpC,QAAM,eAAe,YAAY,IAAI,aAAa;AAClD,QAAM,cAAc,eAAe,SAAY,YAAY,IAAI,YAAY;AAC3E,QAAM,SAAS,gBAAgB;AAC/B,MAAI,CAAC,QAAQ,MAAO,QAAO;AAE3B,QAAM,OAAO,eAAe,gBAAgB;A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vD,WAAO,QAAS,cAAc,MAAM,eAAe,GAAG,QAAQ,GAAG,GAAG,QAAQ;AAAA,EAC9E;AACA,SAAO,eAAe,GAAG,QAAQ;AACnC;AAsBA,eAAsB,YAAY,eAAuB,MAAmC;AAC1F,SAAO,mBAAmB,MAAM,QAAQ,YAAY,IAAI,CAAC;AAC3D;AAgBA,eAAsB,eACpB,eACG,MACuB;AAC1B,SAAO,QAAQ,YAAY,IAAI;AACjC;AAGO,SAAS,sBAA4B;AAC1C,YAAU;AACV,aAAW;AACX,eAAa;AACf;","names":[]}
|
package/dist/hooks.js
CHANGED
package/dist/index.js
CHANGED
|
@@ -21,10 +21,10 @@ import {
|
|
|
21
21
|
unwrap,
|
|
22
22
|
unwrapOr,
|
|
23
23
|
withServerCache
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-34NCJS52.js";
|
|
25
25
|
import {
|
|
26
26
|
recaptchaOk
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-B4MGIUCU.js";
|
|
28
28
|
|
|
29
29
|
// src/server-query-client.ts
|
|
30
30
|
import { cache } from "react";
|
package/dist/query-action.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type SessionCredentials, type ApprovedMethodPath } from "./sdk-client-store";
|
|
2
2
|
import { unwrapBaseResponse } from "@simpleapps-com/augur-core";
|
|
3
|
+
import { type BaseResponse } from "@simpleapps-com/augur-api";
|
|
3
4
|
/**
|
|
4
5
|
* Resolve session credentials from the Auth.js JWT cookie.
|
|
5
6
|
*
|
|
@@ -68,93 +69,7 @@ declare function getSessionCredentials(): Promise<SessionCredentials | null>;
|
|
|
68
69
|
*/
|
|
69
70
|
declare function resolveMethod(client: unknown, methodPath: ApprovedMethodPath): (...a: unknown[]) => Promise<unknown>;
|
|
70
71
|
/**
|
|
71
|
-
*
|
|
72
|
-
* SDK client with optional Redis caching. Used internally by
|
|
73
|
-
* `createServerQueryProxy()` to bridge client-side React Query hooks
|
|
74
|
-
* to server-side API calls.
|
|
75
|
-
*
|
|
76
|
-
* For read methods (get, list, lookup, search, suggest), the call is
|
|
77
|
-
* wrapped in the registered cache wrapper (Redis) if one was registered
|
|
78
|
-
* by createServerSite(). Write methods bypass caching.
|
|
79
|
-
*
|
|
80
|
-
* When the request has an active session with targetSiteId + token
|
|
81
|
-
* (from cross-site auth), the call uses a scoped SDK client with those
|
|
82
|
-
* credentials. Redis caching uses targetSiteId as the cache prefix so
|
|
83
|
-
* users managing the same site share cached data.
|
|
84
|
-
*
|
|
85
|
-
* SDK responses wrapped in BaseResponse are automatically unwrapped --
|
|
86
|
-
* consumers receive `T` instead of `{ data: T, status, message }`.
|
|
87
|
-
*
|
|
88
|
-
* This is the chokepoint: every B2B site without a client-side SDK
|
|
89
|
-
* routes EVERY data access through this one function. The invariants
|
|
90
|
-
* below are load-bearing across every site, every request, every user.
|
|
91
|
-
*
|
|
92
|
-
* ## Preconditions (enforced at runtime via thrown Error)
|
|
93
|
-
*
|
|
94
|
-
* parseMethodPath(methodPath) ≠ null
|
|
95
|
-
* resolveClient().client ≠ null
|
|
96
|
-
*
|
|
97
|
-
* First clause: methodPath is a non-empty string AND — if an allowlist
|
|
98
|
-
* has been registered via `registerAllowedMethodPaths` — methodPath is
|
|
99
|
-
* in the allowlist. Assumes the site opted into surface restriction
|
|
100
|
-
* when narrower-than-augur-api authority is desired; otherwise any
|
|
101
|
-
* non-empty string passes (transparent forwarder default).
|
|
102
|
-
*
|
|
103
|
-
* Second clause: createServerSite() ran during bootstrap OR
|
|
104
|
-
* AUGUR_SITE_ID + AUGUR_JWT env vars are set so the registry can
|
|
105
|
-
* auto-init. Assumes the caller has bootstrapped one of the two paths.
|
|
106
|
-
*
|
|
107
|
-
* Lean equivalent: `requires path : ApprovedMethodPath ∧ client : SDKClient`.
|
|
108
|
-
*
|
|
109
|
-
* ## Cross-tenant cache-prefix invariant (load-bearing)
|
|
110
|
-
*
|
|
111
|
-
* resolution.kind = "scoped" ⟹ cachePrefix = `${resolution.credentials.siteId}:`
|
|
112
|
-
*
|
|
113
|
-
* On the scoped path the cache prefix is derived structurally from the
|
|
114
|
-
* same `SessionCredentials` value that minted the scoped client — they
|
|
115
|
-
* cannot be sourced separately. This makes "siteId from session A
|
|
116
|
-
* combined with token from session B" or "siteId X with cache prefix Y"
|
|
117
|
-
* unrepresentable here. Assumes `getSessionCredentials` performed the
|
|
118
|
-
* bearer/session siteId cross-check at mint time; see the brand-strength
|
|
119
|
-
* caveat on `SessionCredentials`.
|
|
120
|
-
*
|
|
121
|
-
* A regression here would silently leak cached data across tenants.
|
|
122
|
-
* The structural derivation is the only thing standing between the
|
|
123
|
-
* request and that leak — do not reintroduce a separate `cachePrefix`
|
|
124
|
-
* parameter or compute it from anything other than `resolution.credentials`.
|
|
125
|
-
*
|
|
126
|
-
* ### Sibling assumption — bearer is NOT in the cache key
|
|
127
|
-
*
|
|
128
|
-
* The cross-tenant invariant covers cross-SITE leaks. It does NOT cover
|
|
129
|
-
* intra-site cross-USER leaks: the cache key is `(siteId, methodPath, args)`
|
|
130
|
-
* and the bearer token is intentionally absent. Two users with different
|
|
131
|
-
* bearers on the same site share cached data for cacheable namespaces.
|
|
132
|
-
*
|
|
133
|
-
* This is a deliberate design choice. The assumption is:
|
|
134
|
-
*
|
|
135
|
-
* ∀ namespace ∉ NO_CACHE_PATHS, ∀ siteId, ∀ args.
|
|
136
|
-
* augur-api(bearer_A, siteId, args) = augur-api(bearer_B, siteId, args)
|
|
137
|
-
*
|
|
138
|
-
* i.e. for cacheable namespaces, augur-api's response is bearer-independent
|
|
139
|
-
* within a site. augur-api remains the auth authority; `NO_CACHE_PATHS`
|
|
140
|
-
* (commerce.*, payments.*) is the carve-out for namespaces whose responses
|
|
141
|
-
* ARE bearer-coupled. If a future namespace produces bearer-dependent
|
|
142
|
-
* responses (e.g. user-specific permissions affecting query results), it
|
|
143
|
-
* MUST be added to `NO_CACHE_PATHS` or the bearer MUST become part of the
|
|
144
|
-
* cache key — otherwise this assumption silently produces a permission leak.
|
|
145
|
-
*
|
|
146
|
-
* ## No-edge-cache defense-in-depth (load-bearing)
|
|
147
|
-
*
|
|
148
|
-
* ∀ a ∈ safeArgs. methodPath ∈ NO_CACHE_PATHS ⟹ "edgeCache" ∉ keys(a)
|
|
149
|
-
*
|
|
150
|
-
* `stripEdgeCacheForNoCachePaths` removes the `edgeCache` key from every
|
|
151
|
-
* first-level object arg when methodPath belongs to a no-cache namespace
|
|
152
|
-
* (currently `commerce.*`, `payments.*`). The augur-api SDK transforms
|
|
153
|
-
* `edgeCache` into a Cloudflare `cacheSiteId{N}` query param; removing
|
|
154
|
-
* it here guarantees no CDN edge-caching of identity-bound responses
|
|
155
|
-
* even if a caller passed one explicitly or a legacy factory injected
|
|
156
|
-
* one. Assumes `NO_CACHE_PATHS` enumerates every namespace whose
|
|
157
|
-
* responses must not cross identity boundaries.
|
|
72
|
+
* The SDK call `callSdk` makes (everything above), answered as its envelope's data.
|
|
158
73
|
*
|
|
159
74
|
* ## Postcondition — BaseResponse pass-through (exactly-once unwrap)
|
|
160
75
|
*
|
|
@@ -164,23 +79,31 @@ declare function resolveMethod(client: unknown, methodPath: ApprovedMethodPath):
|
|
|
164
79
|
*
|
|
165
80
|
* Consumers receive `T` directly when the SDK returns
|
|
166
81
|
* `{ data: T, status, message }`, and the original value otherwise.
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
* when that shape happens to round-trip through the API.
|
|
172
|
-
*
|
|
173
|
-
* ## Effects
|
|
174
|
-
*
|
|
175
|
-
* @mutates Redis (write-through on read methods when a wrapper is registered)
|
|
176
|
-
* @io augur-api SDK (network request)
|
|
177
|
-
* @throws Error when the allowlist gate fails or no client is initialised
|
|
82
|
+
* Double-unwrap (caller + queryAction) would silently strip a layer of
|
|
83
|
+
* legitimate `{data, status, message}` user data when that shape happens
|
|
84
|
+
* to round-trip through the API. The envelope's paging (`total`,
|
|
85
|
+
* `totalResults`, `count`) is not in `data`: read it with `queryActionRaw`.
|
|
178
86
|
*
|
|
179
87
|
* @param methodPath Dot-separated SDK method path (e.g. "items.invMast.doc.get")
|
|
180
88
|
* @param args Arguments to pass to the resolved method
|
|
181
89
|
* @returns The unwrapped result from the SDK method (possibly from Redis cache)
|
|
182
90
|
*/
|
|
183
91
|
export declare function queryAction(methodPath: string, ...args: unknown[]): Promise<unknown>;
|
|
92
|
+
/**
|
|
93
|
+
* The same call as `queryAction` (allowlist, client, `edgeCache` strip, Redis), answered as
|
|
94
|
+
* the SDK returned it: augur-api's `BaseResponse<T>` envelope (every SDK method's result) with
|
|
95
|
+
* `data`, `total`, `totalResults` and `count`, so client code can page a list (atlas#107). A
|
|
96
|
+
* method path carries no type, so the caller names `T` (`queryActionRaw<Article[]>(…)`). A
|
|
97
|
+
* `queryAction` and a `queryActionRaw` of one call share one Redis entry.
|
|
98
|
+
*
|
|
99
|
+
* MUST NOT run under a React Query key that also holds `queryAction`'s shape (an options
|
|
100
|
+
* proxy's `queryKey`): give it its own key.
|
|
101
|
+
*
|
|
102
|
+
* @param methodPath Dot-separated SDK method path (e.g. "joomla.content.list")
|
|
103
|
+
* @param args Arguments to pass to the resolved method
|
|
104
|
+
* @returns The SDK method's result unchanged (possibly from Redis cache)
|
|
105
|
+
*/
|
|
106
|
+
export declare function queryActionRaw<T = unknown>(methodPath: string, ...args: unknown[]): Promise<BaseResponse<T>>;
|
|
184
107
|
/** Reset lazy-loaded imports. Used in tests only. @internal */
|
|
185
108
|
export declare function resetSessionImports(): void;
|
|
186
109
|
export { unwrapBaseResponse, getSessionCredentials, resolveMethod };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-action.d.ts","sourceRoot":"","sources":["../src/query-action.ts"],"names":[],"mappings":"AAUA,OAAO,EAQL,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EAGxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAGL,kBAAkB,EACnB,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"query-action.d.ts","sourceRoot":"","sources":["../src/query-action.ts"],"names":[],"mappings":"AAUA,OAAO,EAQL,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EAGxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAGL,kBAAkB,EACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAY,KAAK,YAAY,EAAE,MAAM,2BAA2B,CAAC;AA+FxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,iBAAe,qBAAqB,IAAI,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CA6BzE;AA2DD;;;;;GAKG;AACH,iBAAS,aAAa,CACpB,MAAM,EAAE,OAAO,EACf,UAAU,EAAE,kBAAkB,GAC7B,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAkBvC;AAsLD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAE1F;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,cAAc,CAAC,CAAC,GAAG,OAAO,EAC9C,UAAU,EAAE,MAAM,EAClB,GAAG,IAAI,EAAE,OAAO,EAAE,GACjB,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAE1B;AAED,+DAA+D;AAC/D,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,aAAa,EAAE,CAAC"}
|
package/dist/query-action.js
CHANGED
|
@@ -2,14 +2,16 @@
|
|
|
2
2
|
import {
|
|
3
3
|
getSessionCredentials,
|
|
4
4
|
queryAction,
|
|
5
|
+
queryActionRaw,
|
|
5
6
|
resetSessionImports,
|
|
6
7
|
resolveMethod,
|
|
7
8
|
unwrapBaseResponse
|
|
8
|
-
} from "./chunk-
|
|
9
|
-
import "./chunk-
|
|
9
|
+
} from "./chunk-WR7WT2FI.js";
|
|
10
|
+
import "./chunk-B4MGIUCU.js";
|
|
10
11
|
export {
|
|
11
12
|
getSessionCredentials,
|
|
12
13
|
queryAction,
|
|
14
|
+
queryActionRaw,
|
|
13
15
|
resetSessionImports,
|
|
14
16
|
resolveMethod,
|
|
15
17
|
unwrapBaseResponse
|
package/dist/rules.d.ts
CHANGED
|
@@ -56,8 +56,11 @@ export declare function serverEnvOf(nodeEnv: string): Env;
|
|
|
56
56
|
* @ensures exactly the model's host rule
|
|
57
57
|
*/
|
|
58
58
|
export declare function hostEnvOf(host: string): Env;
|
|
59
|
-
/**
|
|
60
|
-
|
|
59
|
+
/**
|
|
60
|
+
* The API route's outcome for a request: "run" answers queryAction's data, "run-full"
|
|
61
|
+
* queryActionRaw's full response (atlas#107).
|
|
62
|
+
*/
|
|
63
|
+
export type ApiOutcome = "forbidden" | "bad-json" | "bad-method-path" | "bad-args" | "run" | "run-full";
|
|
61
64
|
/**
|
|
62
65
|
* A present, non-empty Sec-Fetch-Site other than same-origin is refused (a missing one, `""`
|
|
63
66
|
* from the caller, passes).
|
|
@@ -66,11 +69,24 @@ export type ApiOutcome = "forbidden" | "bad-json" | "bad-method-path" | "bad-arg
|
|
|
66
69
|
*/
|
|
67
70
|
export declare function isCrossOrigin(fetchSite: string): boolean;
|
|
68
71
|
/**
|
|
69
|
-
* The body's outcome: JSON, then a non-empty methodPath string, then an args array
|
|
72
|
+
* The body's outcome: JSON, then a non-empty methodPath string, then an args array; a valid
|
|
73
|
+
* body with `raw: true` (`full`) runs for the full response, any other for its data.
|
|
70
74
|
*
|
|
71
75
|
* @ensures exactly the model's ApiOutcomeOf past the origin check
|
|
72
76
|
*/
|
|
73
|
-
export declare function bodyOutcomeOf(jsonOk: boolean, methodPathOk: boolean, argsIsArray: boolean): ApiOutcome;
|
|
77
|
+
export declare function bodyOutcomeOf(jsonOk: boolean, methodPathOk: boolean, argsIsArray: boolean, full: boolean): ApiOutcome;
|
|
78
|
+
/**
|
|
79
|
+
* The route runs the call: either view; any other outcome is a refusal.
|
|
80
|
+
*
|
|
81
|
+
* @ensures exactly the model's Runs
|
|
82
|
+
*/
|
|
83
|
+
export declare function runsOf(o: ApiOutcome): boolean;
|
|
84
|
+
/**
|
|
85
|
+
* The route answers the full response (queryActionRaw), not its data.
|
|
86
|
+
*
|
|
87
|
+
* @ensures exactly the model's AnswersFull
|
|
88
|
+
*/
|
|
89
|
+
export declare function answersFullOf(o: ApiOutcome): boolean;
|
|
74
90
|
/**
|
|
75
91
|
* An outcome's HTTP status: 403, 400 for a bad body, 200 to run.
|
|
76
92
|
*
|
package/dist/rules.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../src/rules.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAMlD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAShE;AAED,kEAAkE;AAClE,MAAM,MAAM,IAAI,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC;AAE3F;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,OAAO,EACjB,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,MAAM,EACb,YAAY,EAAE,MAAM,GACnB,IAAI,CAQN;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CACvB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,SAAS,EAAE,MAAM,G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AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAIlE;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAMvE"}
|
package/dist/site.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createAuthConfig
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-F7QWHMHH.js";
|
|
4
4
|
import {
|
|
5
5
|
createSiteActions,
|
|
6
6
|
registerSiteActions,
|
|
7
7
|
withRawSdkCache
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-34NCJS52.js";
|
|
9
9
|
import {
|
|
10
10
|
crossSiteOf,
|
|
11
11
|
registerAuthSecret,
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
registerSdkCallWrapper,
|
|
16
16
|
registerSdkClient,
|
|
17
17
|
ttlFor
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-B4MGIUCU.js";
|
|
19
19
|
|
|
20
20
|
// src/server-site.ts
|
|
21
21
|
import { hours } from "@simpleapps-com/augur-utils";
|
package/dist/testing.js
CHANGED
package/llms.txt
CHANGED
|
@@ -211,14 +211,15 @@ const addToCart = useMutation(q.commerce.cartLine.add.create());
|
|
|
211
211
|
## @simpleapps-com/augur-server/query-action
|
|
212
212
|
|
|
213
213
|
- function: getSessionCredentials - Resolve session credentials from the Auth.js JWT cookie.
|
|
214
|
-
- function: queryAction -
|
|
214
|
+
- function: queryAction - The SDK call `callSdk` makes (everything above), answered as its envelope's data.
|
|
215
|
+
- function: queryActionRaw - The same call as `queryAction` (allowlist, client, `edgeCache` strip, Redis), answered as the SDK returned it: augur-api's `BaseResponse<T>` envelope (every SDK method's result) with `data`, `total`, `totalResults` and `count`, so client code can page a list (atlas#107). A method path carries no type, so the caller names `T` (`queryActionRaw<Article[]>(…)`). A `queryAction` and a `queryActionRaw` of one call share one Redis entry.
|
|
215
216
|
- function: resetSessionImports - Reset lazy-loaded imports. Used in tests only. @internal
|
|
216
217
|
- function: resolveMethod - Resolve a dot-separated method path on an object, returning the leaf function.
|
|
217
218
|
- value: unwrapBaseResponse
|
|
218
219
|
|
|
219
220
|
## @simpleapps-com/augur-server/api
|
|
220
221
|
|
|
221
|
-
- function: createAugurApiHandler - Creates a Next.js Route Handler that routes method calls through queryAction.
|
|
222
|
+
- function: createAugurApiHandler - Creates a Next.js Route Handler that routes method calls through queryAction, or through queryActionRaw when the body has `raw: true` (augur-core's `createFetchQueryActionRaw`).
|
|
222
223
|
|
|
223
224
|
### Examples
|
|
224
225
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simpleapps-com/augur-server",
|
|
3
|
-
"version": "2026.11.
|
|
3
|
+
"version": "2026.11.4",
|
|
4
4
|
"description": "Server-side utilities for Augur ecommerce sites (Redis caching, SDK helpers, auth)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"llms.txt"
|
|
59
59
|
],
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@simpleapps-com/augur-core": "^2026.11.
|
|
61
|
+
"@simpleapps-com/augur-core": "^2026.11.3",
|
|
62
62
|
"@simpleapps-com/augur-hooks": "^2026.11.2",
|
|
63
63
|
"@simpleapps-com/augur-utils": "^2026.11.3"
|
|
64
64
|
},
|
|
@@ -1 +0,0 @@
|
|
|
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, the proved pure `rules` (with @atlas/utils' string scans, bundled), plus augur-core\n// and augur-api's `isSiteId` (both external in tsup — not bundled into chunks; every site\n// already loads the SDK on the server).\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 getCrossSite,\n getOrCreateScopedClient,\n getScopedCacheWrapper,\n parseMethodPath,\n type SessionCredentials,\n type ApprovedMethodPath,\n type SdkCallWrapper,\n type ScopedCacheWrapper,\n} from \"./sdk-client-store\";\nimport {\n isReadMethod,\n stripEdgeCacheForNoCachePaths,\n unwrapBaseResponse,\n} from \"@simpleapps-com/augur-core\";\nimport { isSiteId } from \"@simpleapps-com/augur-api\";\nimport {\n clientIdSiteIdOf,\n mintedCredentials,\n readsSession,\n resolutionOf,\n scopedPrefix,\n usesCache,\n} from \"./rules\";\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 } catch {\n // next-auth is an optional peer: without it there are no session credentials\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 } catch {\n // outside Next.js there is no request cookie store\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 } catch {\n // jose is an optional peer: without it the bearer cannot be cross-checked\n _decodeJwt = null;\n }\n }\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 return clientIdSiteIdOf(clientId);\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. No other production code\n * constructs the branded pair, so a `SessionCredentials` that came through\n * this mint is JWT-validated and internally consistent. The brand is not\n * enforced by the compiler: an `as SessionCredentials` cast compiles (tests\n * do it), so audit casts (see \"Brand strength\" below).\n *\n * Returns null when:\n * - the site did not opt in to cross-site sessions (`createServerSite`'s\n * `auth: { crossSite: true }`, atlas#105): then nothing is imported and no\n * cookie is read, so pages using queryAction can render statically\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 * - `targetSiteId` fails augur-api's `isSiteId` (`[a-z0-9_-]+`): siteIds are\n * lowercase by convention, and the scoped-client key's injectivity proof\n * (`scoped-client-key.ts`) needs a NUL-free siteId\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\" ∧ isSiteId(jwt.targetSiteId) // implies non-empty\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 // Only an opted-in site with a secret looks for a session (rules.readsSession, atlas#105):\n // every other site returns here, before next/headers is imported or cookies() read, so its\n // pages can render statically.\n if (!readsSession(getCrossSite(), Boolean(secret))) return null;\n if (!(await ensureImports())) return null;\n\n try {\n // readsSession held, so the secret is present (Boolean(secret) above).\n const decoded = await decodeSessionJwt(secret as string);\n if (!decoded) return null;\n\n const targetSiteId = decoded[\"targetSiteId\"];\n const token = decoded[\"token\"];\n\n if (typeof targetSiteId !== \"string\" || typeof token !== \"string\") return null;\n\n // An empty or undecodable token has no client_id siteId (\"\").\n const bearerSiteId = parseBearerClientSiteId(token) ?? \"\";\n const mint = mintedCredentials(isSiteId(targetSiteId), targetSiteId, token, bearerSiteId);\n if (mint.kind === \"refused\") return null;\n\n return { siteId: mint.siteId, token: mint.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 const scoped = creds ? getOrCreateScopedClient(creds) : null;\n const globalClient = getSdkClientOrNull();\n const kind = resolutionOf(creds !== null, isObject(scoped), isObject(globalClient));\n if (kind === \"scoped\") return { kind, client: scoped as object, credentials: creds! };\n if (kind === \"global\") return { kind, client: globalClient as object };\n return { kind };\n}\n\n/** A usable client: a non-null object. */\nfunction isObject(value: unknown): boolean {\n return value !== null && typeof value === \"object\";\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(), scopedPrefix(resolution.credentials.siteId))\n : getSdkCallWrapper();\n\n if (usesCache(wrapper !== null, 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":";;;;;;;;;;;;;;;;;AAuBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AAWzB,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,IAChB,QAAQ;AAEN,gBAAU;AAAA,IACZ;AAAA,EACF;AACA,MAAI,aAAa,QAAW;AAC1B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,cAAc;AACvC,iBAAW,IAAI;AAAA,IACjB,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