@simpleapps-com/augur-server 2.3.1 → 2026.11.1
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 +29 -72
- package/README.md +29 -198
- package/dist/actions/agr-info.d.ts +43 -0
- package/dist/actions/agr-info.d.ts.map +1 -0
- package/dist/actions/agr-site.d.ts +37 -0
- package/dist/actions/agr-site.d.ts.map +1 -0
- package/dist/actions/agr-work.d.ts +29 -0
- package/dist/actions/agr-work.d.ts.map +1 -0
- package/dist/actions/avalara.d.ts +38 -0
- package/dist/actions/avalara.d.ts.map +1 -0
- package/dist/actions/basecamp2.d.ts +47 -0
- package/dist/actions/basecamp2.d.ts.map +1 -0
- package/dist/actions/brand-folder.d.ts +38 -0
- package/dist/actions/brand-folder.d.ts.map +1 -0
- package/dist/actions/commerce.d.ts +58 -0
- package/dist/actions/commerce.d.ts.map +1 -0
- package/dist/actions/customers.d.ts +44 -0
- package/dist/actions/customers.d.ts.map +1 -0
- package/dist/actions/favorites.d.ts +20 -0
- package/dist/actions/favorites.d.ts.map +1 -0
- package/dist/actions/gregorovich.d.ts +34 -0
- package/dist/actions/gregorovich.d.ts.map +1 -0
- package/dist/actions/items.d.ts +80 -0
- package/dist/actions/items.d.ts.map +1 -0
- package/dist/actions/joomla.d.ts +59 -0
- package/dist/actions/joomla.d.ts.map +1 -0
- package/dist/actions/legacy.d.ts +45 -0
- package/dist/actions/legacy.d.ts.map +1 -0
- package/dist/actions/logistics.d.ts +40 -0
- package/dist/actions/logistics.d.ts.map +1 -0
- package/dist/actions/orders.d.ts +36 -0
- package/dist/actions/orders.d.ts.map +1 -0
- package/dist/actions/p21-apis.d.ts +33 -0
- package/dist/actions/p21-apis.d.ts.map +1 -0
- package/dist/actions/p21-core.d.ts +46 -0
- package/dist/actions/p21-core.d.ts.map +1 -0
- package/dist/actions/p21-pim.d.ts +36 -0
- package/dist/actions/p21-pim.d.ts.map +1 -0
- package/dist/actions/p21-sism.d.ts +37 -0
- package/dist/actions/p21-sism.d.ts.map +1 -0
- package/dist/actions/payments.d.ts +39 -0
- package/dist/actions/payments.d.ts.map +1 -0
- package/dist/actions/pricing.d.ts +45 -0
- package/dist/actions/pricing.d.ts.map +1 -0
- package/dist/actions/search.d.ts +61 -0
- package/dist/actions/search.d.ts.map +1 -0
- package/dist/actions/shipping.d.ts +56 -0
- package/dist/actions/shipping.d.ts.map +1 -0
- package/dist/actions/site.d.ts +141 -0
- package/dist/actions/site.d.ts.map +1 -0
- package/dist/actions/smarty-streets.d.ts +45 -0
- package/dist/actions/smarty-streets.d.ts.map +1 -0
- package/dist/actions/vmi.d.ts +44 -0
- package/dist/actions/vmi.d.ts.map +1 -0
- package/dist/actions/wishlists.d.ts +28 -0
- package/dist/actions/wishlists.d.ts.map +1 -0
- package/dist/api-handler.d.ts +25 -0
- package/dist/api-handler.d.ts.map +1 -0
- package/dist/api.d.ts +2 -26
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +19 -14
- package/dist/api.js.map +1 -1
- package/dist/auth.d.ts +10 -12
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +2 -2
- package/dist/cache/redis-client.d.ts +16 -0
- package/dist/cache/redis-client.d.ts.map +1 -0
- package/dist/cache/with-cache.d.ts +18 -0
- package/dist/cache/with-cache.d.ts.map +1 -0
- package/dist/chunk-FWO6Q43T.js +162 -0
- package/dist/chunk-FWO6Q43T.js.map +1 -0
- package/dist/{chunk-HPQQYROJ.js → chunk-NTUPTNOI.js} +40 -7
- package/dist/chunk-NTUPTNOI.js.map +1 -0
- package/dist/{chunk-WOHZDFJF.js → chunk-PFYEMJTQ.js} +212 -642
- package/dist/chunk-PFYEMJTQ.js.map +1 -0
- package/dist/{chunk-KHFEDL47.js → chunk-SXXWBSTX.js} +18 -12
- package/dist/chunk-SXXWBSTX.js.map +1 -0
- package/dist/chunk-TVH5EONP.js +178 -0
- package/dist/chunk-TVH5EONP.js.map +1 -0
- package/dist/{chunk-TQP67TGL.js → chunk-U2BKHRJC.js} +13 -15
- package/dist/chunk-U2BKHRJC.js.map +1 -0
- package/dist/environment.d.ts +10 -0
- package/dist/environment.d.ts.map +1 -0
- package/dist/hooks.d.ts +8 -10
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +3 -3
- package/dist/hooks.js.map +1 -1
- package/dist/index.d.ts +16 -125
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -8
- package/dist/index.js.map +1 -1
- package/dist/pagination.d.ts +32 -0
- package/dist/pagination.d.ts.map +1 -0
- package/dist/query-action.d.ts +156 -17
- package/dist/query-action.d.ts.map +1 -0
- package/dist/query-action.js +3 -3
- package/dist/query-options-helper.d.ts +33 -0
- package/dist/query-options-helper.d.ts.map +1 -0
- package/dist/query.js +1 -2
- package/dist/recaptcha.d.ts +6 -0
- package/dist/recaptcha.d.ts.map +1 -0
- package/dist/rules.d.ts +221 -0
- package/dist/rules.d.ts.map +1 -0
- package/dist/scoped-client-key.d.ts +9 -0
- package/dist/scoped-client-key.d.ts.map +1 -0
- package/dist/sdk-call.d.ts +66 -0
- package/dist/sdk-call.d.ts.map +1 -0
- package/dist/sdk-client-store.d.ts +250 -0
- package/dist/sdk-client-store.d.ts.map +1 -0
- package/dist/server-actions.d.ts +2 -0
- package/dist/server-actions.d.ts.map +1 -0
- package/dist/server-query-client.d.ts +19 -0
- package/dist/server-query-client.d.ts.map +1 -0
- package/dist/{server-site-registry-CdBfczOj.d.ts → server-site-registry.d.ts} +7 -9
- package/dist/server-site-registry.d.ts.map +1 -0
- package/dist/{site.d.ts → server-site.d.ts} +11 -16
- package/dist/server-site.d.ts.map +1 -0
- package/dist/site-actions-store.d.ts +27 -0
- package/dist/site-actions-store.d.ts.map +1 -0
- package/dist/site.js +10 -10
- package/dist/site.js.map +1 -1
- package/dist/testing.d.ts +9 -12
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +7 -27
- package/dist/testing.js.map +1 -1
- package/dist/utils/batch-fetch.d.ts +7 -0
- package/dist/utils/batch-fetch.d.ts.map +1 -0
- package/llms.txt +71 -50
- package/package.json +34 -20
- package/dist/actions.d.ts +0 -2
- package/dist/chunk-DGUM43GV.js +0 -11
- package/dist/chunk-DGUM43GV.js.map +0 -1
- package/dist/chunk-HPQQYROJ.js.map +0 -1
- package/dist/chunk-KHFEDL47.js.map +0 -1
- package/dist/chunk-TQP67TGL.js.map +0 -1
- package/dist/chunk-WOHZDFJF.js.map +0 -1
- package/dist/chunk-ZUJZDRTP.js +0 -136
- package/dist/chunk-ZUJZDRTP.js.map +0 -1
- package/dist/query.d.ts +0 -31
- package/dist/site-BjSFqufX.d.ts +0 -469
package/dist/api.d.ts
CHANGED
|
@@ -1,26 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
* Exposes the existing queryAction as an HTTP POST endpoint so that
|
|
5
|
-
* `createFetchQueryAction()` from augur-core can route calls through
|
|
6
|
-
* fetch() instead of server actions. This is needed on platforms where
|
|
7
|
-
* server actions cannot access request cookies (e.g., CF Workers via OpenNext).
|
|
8
|
-
*
|
|
9
|
-
* The handler validates same-origin requests via the Sec-Fetch-Site header
|
|
10
|
-
* (set by browsers automatically and cannot be forged by scripts).
|
|
11
|
-
*/
|
|
12
|
-
/**
|
|
13
|
-
* Creates a Next.js Route Handler that routes method calls through queryAction.
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* ```ts
|
|
17
|
-
* // app/api/augur/route.ts
|
|
18
|
-
* import { createAugurApiHandler } from "@simpleapps-com/augur-server/api";
|
|
19
|
-
*
|
|
20
|
-
* const handler = createAugurApiHandler();
|
|
21
|
-
* export const POST = handler;
|
|
22
|
-
* ```
|
|
23
|
-
*/
|
|
24
|
-
declare function createAugurApiHandler(): (req: Request) => Promise<Response>;
|
|
25
|
-
|
|
26
|
-
export { createAugurApiHandler };
|
|
1
|
+
export { createAugurApiHandler } from "./api-handler";
|
|
2
|
+
//# sourceMappingURL=api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC"}
|
package/dist/api.js
CHANGED
|
@@ -1,29 +1,34 @@
|
|
|
1
1
|
import {
|
|
2
2
|
queryAction
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
5
|
-
import
|
|
3
|
+
} from "./chunk-FWO6Q43T.js";
|
|
4
|
+
import "./chunk-NTUPTNOI.js";
|
|
5
|
+
import {
|
|
6
|
+
apiMessageOf,
|
|
7
|
+
apiStatusOf,
|
|
8
|
+
bodyOutcomeOf,
|
|
9
|
+
isCrossOrigin
|
|
10
|
+
} from "./chunk-TVH5EONP.js";
|
|
6
11
|
|
|
7
12
|
// src/api-handler.ts
|
|
13
|
+
function refusal(outcome) {
|
|
14
|
+
return new Response(apiMessageOf(outcome), { status: apiStatusOf(outcome) });
|
|
15
|
+
}
|
|
8
16
|
function createAugurApiHandler() {
|
|
9
17
|
return async (req) => {
|
|
10
|
-
|
|
11
|
-
if (fetchSite && fetchSite !== "same-origin") {
|
|
12
|
-
return new Response("Forbidden: cross-origin requests not allowed", { status: 403 });
|
|
13
|
-
}
|
|
18
|
+
if (isCrossOrigin(req.headers.get("sec-fetch-site") ?? "")) return refusal("forbidden");
|
|
14
19
|
let body;
|
|
15
20
|
try {
|
|
16
21
|
body = await req.json();
|
|
17
22
|
} catch {
|
|
18
|
-
return
|
|
23
|
+
return refusal("bad-json");
|
|
19
24
|
}
|
|
20
25
|
const { methodPath, args } = body;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
26
|
+
const outcome = bodyOutcomeOf(
|
|
27
|
+
true,
|
|
28
|
+
typeof methodPath === "string" && methodPath !== "",
|
|
29
|
+
Array.isArray(args)
|
|
30
|
+
);
|
|
31
|
+
if (outcome !== "run") return refusal(outcome);
|
|
27
32
|
try {
|
|
28
33
|
const result = await queryAction(methodPath, ...args);
|
|
29
34
|
return Response.json(result);
|
package/dist/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api-handler.ts"],"sourcesContent":["/**\n * Generic API route handler for fetch-mode proxy.\n *\n * Exposes the existing queryAction as an HTTP POST endpoint so that\n * `createFetchQueryAction()` from augur-core can route calls through\n * fetch() instead of server actions. This is needed on platforms where\n * server actions cannot access request cookies (e.g., CF Workers via OpenNext).\n *\n * The handler validates same-origin requests via the Sec-Fetch-Site header\n * (set by browsers automatically and cannot be forged by scripts).\n */\n\nimport { queryAction } from \"./query-action\";\n\n/** Request body shape for the API handler. */\ninterface AugurApiRequestBody {\n methodPath: string;\n args: unknown[];\n}\n\n/**\n * Creates a Next.js Route Handler that routes method calls through queryAction.\n *\n * @example\n * ```ts\n * // app/api/augur/route.ts\n * import { createAugurApiHandler } from \"@simpleapps-com/augur-server/api\";\n *\n * const handler = createAugurApiHandler();\n * export const POST = handler;\n * ```\n */\nexport function createAugurApiHandler() {\n return async (req: Request): Promise<Response> => {\n // Same-origin validation: Sec-Fetch-Site is set by browsers and\n // cannot be forged by JavaScript. Reject cross-origin requests.\n
|
|
1
|
+
{"version":3,"sources":["../src/api-handler.ts"],"sourcesContent":["/**\n * Generic API route handler for fetch-mode proxy.\n *\n * Exposes the existing queryAction as an HTTP POST endpoint so that\n * `createFetchQueryAction()` from augur-core can route calls through\n * fetch() instead of server actions. This is needed on platforms where\n * server actions cannot access request cookies (e.g., CF Workers via OpenNext).\n *\n * The handler validates same-origin requests via the Sec-Fetch-Site header\n * (set by browsers automatically and cannot be forged by scripts).\n */\n\nimport { queryAction } from \"./query-action\";\nimport { apiMessageOf, apiStatusOf, bodyOutcomeOf, isCrossOrigin, type ApiOutcome } from \"./rules\";\n\n/** A refused request's response: the outcome's text and status. */\nfunction refusal(outcome: ApiOutcome): Response {\n return new Response(apiMessageOf(outcome), { status: apiStatusOf(outcome) });\n}\n\n/** Request body shape for the API handler. */\ninterface AugurApiRequestBody {\n methodPath: string;\n args: unknown[];\n}\n\n/**\n * Creates a Next.js Route Handler that routes method calls through queryAction.\n *\n * @example\n * ```ts\n * // app/api/augur/route.ts\n * import { createAugurApiHandler } from \"@simpleapps-com/augur-server/api\";\n *\n * const handler = createAugurApiHandler();\n * export const POST = handler;\n * ```\n */\nexport function createAugurApiHandler() {\n return async (req: Request): Promise<Response> => {\n // Same-origin validation: Sec-Fetch-Site is set by browsers and\n // cannot be forged by JavaScript. Reject cross-origin requests.\n if (isCrossOrigin(req.headers.get(\"sec-fetch-site\") ?? \"\")) return refusal(\"forbidden\");\n\n let body: AugurApiRequestBody;\n try {\n body = (await req.json()) as AugurApiRequestBody;\n } catch {\n return refusal(\"bad-json\");\n }\n\n const { methodPath, args } = body;\n const outcome = bodyOutcomeOf(\n true,\n typeof methodPath === \"string\" && methodPath !== \"\",\n Array.isArray(args),\n );\n if (outcome !== \"run\") return refusal(outcome);\n\n try {\n const result = await queryAction(methodPath, ...args);\n return Response.json(result);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Internal server error\";\n return new Response(message, { status: 500 });\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;AAgBA,SAAS,QAAQ,SAA+B;AAC9C,SAAO,IAAI,SAAS,aAAa,OAAO,GAAG,EAAE,QAAQ,YAAY,OAAO,EAAE,CAAC;AAC7E;AAoBO,SAAS,wBAAwB;AACtC,SAAO,OAAO,QAAoC;AAGhD,QAAI,cAAc,IAAI,QAAQ,IAAI,gBAAgB,KAAK,EAAE,EAAG,QAAO,QAAQ,WAAW;AAEtF,QAAI;AACJ,QAAI;AACF,aAAQ,MAAM,IAAI,KAAK;AAAA,IACzB,QAAQ;AACN,aAAO,QAAQ,UAAU;AAAA,IAC3B;AAEA,UAAM,EAAE,YAAY,KAAK,IAAI;AAC7B,UAAM,UAAU;AAAA,MACd;AAAA,MACA,OAAO,eAAe,YAAY,eAAe;AAAA,MACjD,MAAM,QAAQ,IAAI;AAAA,IACpB;AACA,QAAI,YAAY,MAAO,QAAO,QAAQ,OAAO;AAE7C,QAAI;AACF,YAAM,SAAS,MAAM,YAAY,YAAY,GAAG,IAAI;AACpD,aAAO,SAAS,KAAK,MAAM;AAAA,IAC7B,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,aAAO,IAAI,SAAS,SAAS,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC9C;AAAA,EACF;AACF;","names":[]}
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { AugurAPI } from
|
|
2
|
-
import { NextAuthConfig } from
|
|
3
|
-
|
|
1
|
+
import type { AugurAPI } from "@simpleapps-com/augur-api";
|
|
2
|
+
import type { NextAuthConfig } from "next-auth";
|
|
4
3
|
/** Base user fields shared across all Augur sites. */
|
|
5
|
-
interface AugurUser {
|
|
4
|
+
export interface AugurUser {
|
|
6
5
|
id: string;
|
|
7
6
|
username: string;
|
|
8
7
|
isVerified: boolean;
|
|
@@ -16,14 +15,14 @@ interface AugurUser {
|
|
|
16
15
|
targetSiteId?: string;
|
|
17
16
|
}
|
|
18
17
|
/** Session shape returned by all Augur sites. */
|
|
19
|
-
interface AugurSession {
|
|
18
|
+
export interface AugurSession {
|
|
20
19
|
user: AugurUser;
|
|
21
20
|
token?: string;
|
|
22
21
|
targetSiteId?: string;
|
|
23
22
|
expires: string;
|
|
24
23
|
}
|
|
25
24
|
/** JWT token shape used by Augur auth. */
|
|
26
|
-
interface AugurJWT {
|
|
25
|
+
export interface AugurJWT {
|
|
27
26
|
id: string;
|
|
28
27
|
username: string;
|
|
29
28
|
isVerified: boolean;
|
|
@@ -31,7 +30,7 @@ interface AugurJWT {
|
|
|
31
30
|
targetSiteId?: string;
|
|
32
31
|
}
|
|
33
32
|
/** Site-specific callbacks the consumer can provide. */
|
|
34
|
-
interface AugurAuthCallbacks {
|
|
33
|
+
export interface AugurAuthCallbacks {
|
|
35
34
|
/** Fetch user profile from the Augur API given the user's Joomla ID. */
|
|
36
35
|
getUserProfile: (userId: string) => Promise<AugurUser | null>;
|
|
37
36
|
/** Look up or create a cart header for the authenticated user. */
|
|
@@ -40,8 +39,8 @@ interface AugurAuthCallbacks {
|
|
|
40
39
|
} | null>;
|
|
41
40
|
}
|
|
42
41
|
/** Derived from augur-api SDK — keeps types in sync automatically. */
|
|
43
|
-
type AugurAuthClient = Pick<AugurAPI, "joomla" | "commerce">;
|
|
44
|
-
interface CreateAuthConfigOptions {
|
|
42
|
+
export type AugurAuthClient = Pick<AugurAPI, "joomla" | "commerce">;
|
|
43
|
+
export interface CreateAuthConfigOptions {
|
|
45
44
|
/** Augur SDK client. When provided, auth SDK calls are handled internally. */
|
|
46
45
|
augurClient?: AugurAuthClient;
|
|
47
46
|
/** Site-specific callbacks. Override internal SDK calls when custom behavior is needed. */
|
|
@@ -58,6 +57,5 @@ interface CreateAuthConfigOptions {
|
|
|
58
57
|
debug?: boolean;
|
|
59
58
|
}
|
|
60
59
|
/** Creates a NextAuth configuration with Joomla credential provider, session callbacks, and automatic cart initialization. */
|
|
61
|
-
declare function createAuthConfig(options: CreateAuthConfigOptions): NextAuthConfig;
|
|
62
|
-
|
|
63
|
-
export { type AugurAuthCallbacks, type AugurAuthClient, type AugurJWT, type AugurSession, type AugurUser, type CreateAuthConfigOptions, createAuthConfig };
|
|
60
|
+
export declare function createAuthConfig(options: CreateAuthConfigOptions): NextAuthConfig;
|
|
61
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAIhD,sDAAsD;AACtD,MAAM,WA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AI,CAAC,QAAQ,EAAE,QAAQ,GAAG,UAAU,CAAC,CAAC;AAEpE,MAAM,WAAW,uBAAuB;IACtC,8EAA8E;IAC9E,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACxC,yDAAyD;IACzD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wDAAwD;IACxD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4DAA4D;IAC5D,iBAAiB,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACpC,kDAAkD;IAClD,gBAAgB,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACnC,8EAA8E;IAC9E,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAsHD,8HAA8H;AAC9H,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,cAAc,CAmHjF"}
|
package/dist/auth.js
CHANGED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read a cached value by key.
|
|
3
|
+
* Returns `null` on cache miss, circuit-open, connection failure, or if
|
|
4
|
+
* Redis is unavailable. Never throws.
|
|
5
|
+
*/
|
|
6
|
+
export declare function cacheGet(key: string): Promise<string | null>;
|
|
7
|
+
/**
|
|
8
|
+
* Write a value to cache with a TTL. Fire-and-forget semantics: no-ops
|
|
9
|
+
* silently when the circuit is open or Redis is unavailable. Never throws.
|
|
10
|
+
*/
|
|
11
|
+
export declare function cacheSet(key: string, value: string, ttlSeconds: number): Promise<void>;
|
|
12
|
+
/** Returns the current circuit breaker state. */
|
|
13
|
+
export declare function getCircuitState(): "closed" | "open";
|
|
14
|
+
/** Whether the Redis client is connected and ready to accept commands. */
|
|
15
|
+
export declare function isRedisConnected(): boolean;
|
|
16
|
+
//# sourceMappingURL=redis-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis-client.d.ts","sourceRoot":"","sources":["../../src/cache/redis-client.ts"],"names":[],"mappings":"AAgHA;;;;GAIG;AACH,wBAAsB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAclE;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAY5F;AAED,iDAAiD;AACjD,wBAAgB,eAAe,IAAI,QAAQ,GAAG,MAAM,CAEnD;AAED,0EAA0E;AAC1E,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side cache wrapper using augur-server's Redis client.
|
|
3
|
+
*
|
|
4
|
+
* Uses the same cache key format as augur-hooks' client-side caching
|
|
5
|
+
* via augur-core's `buildCacheKey`:
|
|
6
|
+
* `${prefix}sdk:${methodPath}:${fnv1a(stableStringify(keyArgs))}`
|
|
7
|
+
*
|
|
8
|
+
* This means server-side cached data can be read by client-side hooks
|
|
9
|
+
* (and vice versa) when using the same prefix and method path.
|
|
10
|
+
*
|
|
11
|
+
* @param prefix Cache key prefix (e.g. "example:"). Empty string if none.
|
|
12
|
+
* @param redisTtl Redis TTL in seconds. 0 or undefined = skip caching.
|
|
13
|
+
* @param methodPath Dot-separated SDK method path (e.g. "pricing.priceEngine.get").
|
|
14
|
+
* @param fn The async function to cache.
|
|
15
|
+
* @param keyArgs Values to hash for the cache key.
|
|
16
|
+
*/
|
|
17
|
+
export declare function withServerCache<T>(prefix: string, redisTtl: number | undefined, methodPath: string, fn: () => Promise<T>, ...keyArgs: unknown[]): Promise<T>;
|
|
18
|
+
//# sourceMappingURL=with-cache.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"with-cache.d.ts","sourceRoot":"","sources":["../../src/cache/with-cache.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,eAAe,CAAC,CAAC,EACrC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,GAAG,OAAO,EAAE,OAAO,EAAE,GACpB,OAAO,CAAC,CAAC,CAAC,CAuBZ"}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getAuthSecret,
|
|
3
|
+
getOrCreateScopedClient,
|
|
4
|
+
getScopedCacheWrapper,
|
|
5
|
+
getSdkCallWrapper,
|
|
6
|
+
getSdkClientOrNull,
|
|
7
|
+
parseMethodPath
|
|
8
|
+
} from "./chunk-NTUPTNOI.js";
|
|
9
|
+
import {
|
|
10
|
+
clientIdSiteIdOf,
|
|
11
|
+
mintedCredentials,
|
|
12
|
+
resolutionOf,
|
|
13
|
+
scopedPrefix,
|
|
14
|
+
usesCache
|
|
15
|
+
} from "./chunk-TVH5EONP.js";
|
|
16
|
+
|
|
17
|
+
// src/query-action.ts
|
|
18
|
+
import {
|
|
19
|
+
isReadMethod,
|
|
20
|
+
stripEdgeCacheForNoCachePaths,
|
|
21
|
+
unwrapBaseResponse
|
|
22
|
+
} from "@simpleapps-com/augur-core";
|
|
23
|
+
import { isSiteId } from "@simpleapps-com/augur-api";
|
|
24
|
+
var SECURE_COOKIE = "__Secure-authjs.session-token";
|
|
25
|
+
var PLAIN_COOKIE = "authjs.session-token";
|
|
26
|
+
var _decode;
|
|
27
|
+
var _cookies;
|
|
28
|
+
var _decodeJwt;
|
|
29
|
+
async function ensureImports() {
|
|
30
|
+
if (_decode === void 0) {
|
|
31
|
+
try {
|
|
32
|
+
const mod = await import("next-auth/jwt");
|
|
33
|
+
_decode = mod.decode;
|
|
34
|
+
} catch {
|
|
35
|
+
_decode = null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (_cookies === void 0) {
|
|
39
|
+
try {
|
|
40
|
+
const mod = await import("next/headers");
|
|
41
|
+
_cookies = mod.cookies;
|
|
42
|
+
} catch {
|
|
43
|
+
_cookies = null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (_decodeJwt === void 0) {
|
|
47
|
+
try {
|
|
48
|
+
const mod = await import("jose");
|
|
49
|
+
_decodeJwt = mod.decodeJwt;
|
|
50
|
+
} catch {
|
|
51
|
+
_decodeJwt = null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return !!_decode && !!_cookies && !!_decodeJwt;
|
|
55
|
+
}
|
|
56
|
+
async function decodeSessionJwt(secret) {
|
|
57
|
+
const cookieStore = await _cookies();
|
|
58
|
+
const secureCookie = cookieStore.get(SECURE_COOKIE);
|
|
59
|
+
const plainCookie = secureCookie ? void 0 : cookieStore.get(PLAIN_COOKIE);
|
|
60
|
+
const cookie = secureCookie ?? plainCookie;
|
|
61
|
+
if (!cookie?.value) return null;
|
|
62
|
+
const salt = secureCookie ? SECURE_COOKIE : PLAIN_COOKIE;
|
|
63
|
+
return _decode({ token: cookie.value, secret, salt });
|
|
64
|
+
}
|
|
65
|
+
function parseBearerClientSiteId(bearer) {
|
|
66
|
+
try {
|
|
67
|
+
const payload = _decodeJwt(bearer);
|
|
68
|
+
const clientId = payload["client_id"];
|
|
69
|
+
if (typeof clientId !== "string") return null;
|
|
70
|
+
return clientIdSiteIdOf(clientId);
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function getSessionCredentials() {
|
|
76
|
+
const secret = getAuthSecret();
|
|
77
|
+
if (!secret) return null;
|
|
78
|
+
if (!await ensureImports()) return null;
|
|
79
|
+
try {
|
|
80
|
+
const decoded = await decodeSessionJwt(secret);
|
|
81
|
+
if (!decoded) return null;
|
|
82
|
+
const targetSiteId = decoded["targetSiteId"];
|
|
83
|
+
const token = decoded["token"];
|
|
84
|
+
if (typeof targetSiteId !== "string" || typeof token !== "string") return null;
|
|
85
|
+
const bearerSiteId = parseBearerClientSiteId(token) ?? "";
|
|
86
|
+
const mint = mintedCredentials(isSiteId(targetSiteId), targetSiteId, token, bearerSiteId);
|
|
87
|
+
if (mint.kind === "refused") return null;
|
|
88
|
+
return { siteId: mint.siteId, token: mint.token };
|
|
89
|
+
} catch {
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
async function resolveClient() {
|
|
94
|
+
const creds = await getSessionCredentials();
|
|
95
|
+
const scoped = creds ? getOrCreateScopedClient(creds) : null;
|
|
96
|
+
const globalClient = getSdkClientOrNull();
|
|
97
|
+
const kind = resolutionOf(creds !== null, isObject(scoped), isObject(globalClient));
|
|
98
|
+
if (kind === "scoped") return { kind, client: scoped, credentials: creds };
|
|
99
|
+
if (kind === "global") return { kind, client: globalClient };
|
|
100
|
+
return { kind };
|
|
101
|
+
}
|
|
102
|
+
function isObject(value) {
|
|
103
|
+
return value !== null && typeof value === "object";
|
|
104
|
+
}
|
|
105
|
+
function resolveMethod(client, methodPath) {
|
|
106
|
+
const segments = methodPath.split(".");
|
|
107
|
+
let current = client;
|
|
108
|
+
for (const segment of segments) {
|
|
109
|
+
if (current == null || typeof current !== "object" && typeof current !== "function") {
|
|
110
|
+
throw new Error(
|
|
111
|
+
`Cannot resolve "${methodPath}": "${segment}" is not accessible on ${typeof current}`
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
current = current[segment];
|
|
115
|
+
}
|
|
116
|
+
if (typeof current !== "function") {
|
|
117
|
+
throw new Error(`"${methodPath}" does not resolve to a function (got ${typeof current})`);
|
|
118
|
+
}
|
|
119
|
+
return current;
|
|
120
|
+
}
|
|
121
|
+
function bindScopedPrefix(scopedWrapper, prefix) {
|
|
122
|
+
if (!scopedWrapper) return null;
|
|
123
|
+
return (methodPath, sdkCall, ...keyArgs) => scopedWrapper(prefix, methodPath, sdkCall, ...keyArgs);
|
|
124
|
+
}
|
|
125
|
+
async function queryAction(methodPath, ...args) {
|
|
126
|
+
const approvedPath = parseMethodPath(methodPath);
|
|
127
|
+
if (approvedPath === null) {
|
|
128
|
+
throw new Error(
|
|
129
|
+
`queryAction: methodPath ${JSON.stringify(methodPath)} is not in the registered allowlist. Register it via registerAllowedMethodPaths() in createServerSite() config.`
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
const resolution = await resolveClient();
|
|
133
|
+
if (resolution.kind === "uninit") {
|
|
134
|
+
throw new Error(
|
|
135
|
+
"SDK client not initialized. Call createServerSite() or set AUGUR_SITE_ID + AUGUR_JWT env vars."
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
const resolvedMethod = resolveMethod(resolution.client, approvedPath);
|
|
139
|
+
const leafName = approvedPath.split(".").pop();
|
|
140
|
+
const safeArgs = stripEdgeCacheForNoCachePaths(approvedPath, args);
|
|
141
|
+
const wrapper = resolution.kind === "scoped" ? bindScopedPrefix(getScopedCacheWrapper(), scopedPrefix(resolution.credentials.siteId)) : getSdkCallWrapper();
|
|
142
|
+
if (usesCache(wrapper !== null, isReadMethod(leafName))) {
|
|
143
|
+
const result2 = await wrapper(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);
|
|
144
|
+
return unwrapBaseResponse(result2);
|
|
145
|
+
}
|
|
146
|
+
const result = await resolvedMethod(...safeArgs);
|
|
147
|
+
return unwrapBaseResponse(result);
|
|
148
|
+
}
|
|
149
|
+
function resetSessionImports() {
|
|
150
|
+
_decode = void 0;
|
|
151
|
+
_cookies = void 0;
|
|
152
|
+
_decodeJwt = void 0;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export {
|
|
156
|
+
unwrapBaseResponse,
|
|
157
|
+
getSessionCredentials,
|
|
158
|
+
resolveMethod,
|
|
159
|
+
queryAction,
|
|
160
|
+
resetSessionImports
|
|
161
|
+
};
|
|
162
|
+
//# sourceMappingURL=chunk-FWO6Q43T.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, 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 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 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 * - 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 if (!secret) return null;\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\" || 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":";;;;;;;;;;;;;;;;;AAsBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AAUzB,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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2B,KAAK,UAAU,UAAU,CAAC;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,aAAa,WAAW,YAAY,MAAM,CAAC,IACrF,kBAAkB;AAExB,MAAI,UAAU,YAAY,MAAM,aAAa,QAAQ,CAAC,GAAG;AACvD,UAAMA,UAAS,MAAM,QAAS,cAAc,MAAM,eAAe,GAAG,QAAQ,GAAG,GAAG,QAAQ;AAC1F,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"]}
|
|
@@ -1,3 +1,25 @@
|
|
|
1
|
+
import {
|
|
2
|
+
approvePath,
|
|
3
|
+
slotDecisionOf
|
|
4
|
+
} from "./chunk-TVH5EONP.js";
|
|
5
|
+
|
|
6
|
+
// src/scoped-client-key.ts
|
|
7
|
+
var SEPARATOR_CODE = 0;
|
|
8
|
+
function hasNoSeparator(siteId) {
|
|
9
|
+
return !siteId.includes(String.fromCharCode(SEPARATOR_CODE));
|
|
10
|
+
}
|
|
11
|
+
function scopedClientKeyOf(siteId, token) {
|
|
12
|
+
if (!hasNoSeparator(siteId)) return null;
|
|
13
|
+
return siteId + String.fromCharCode(SEPARATOR_CODE) + token;
|
|
14
|
+
}
|
|
15
|
+
function scopedClientKey(siteId, token) {
|
|
16
|
+
const key = scopedClientKeyOf(siteId, token);
|
|
17
|
+
if (key === null) {
|
|
18
|
+
throw new TypeError("scopedClientKey: siteId must not contain a NUL character");
|
|
19
|
+
}
|
|
20
|
+
return key;
|
|
21
|
+
}
|
|
22
|
+
|
|
1
23
|
// src/sdk-client-store.ts
|
|
2
24
|
var g = globalThis;
|
|
3
25
|
var _cachedClient = null;
|
|
@@ -6,6 +28,7 @@ var _cachedAuthSecret = null;
|
|
|
6
28
|
var _cachedClientFactory = null;
|
|
7
29
|
var _cachedScopedCacheWrapper = null;
|
|
8
30
|
var _scopedClient = null;
|
|
31
|
+
var _allowedMethodPaths = null;
|
|
9
32
|
function registerSdkClient(client) {
|
|
10
33
|
_cachedClient = client;
|
|
11
34
|
g.__augur_sdk_client = client;
|
|
@@ -45,15 +68,24 @@ function registerScopedCacheWrapper(wrapper) {
|
|
|
45
68
|
function getScopedCacheWrapper() {
|
|
46
69
|
return g.__augur_scoped_cache_wrapper ?? _cachedScopedCacheWrapper ?? null;
|
|
47
70
|
}
|
|
48
|
-
function getOrCreateScopedClient(
|
|
49
|
-
const
|
|
50
|
-
|
|
71
|
+
function getOrCreateScopedClient(credentials) {
|
|
72
|
+
const { siteId, token } = credentials;
|
|
73
|
+
const key = scopedClientKey(siteId, token);
|
|
51
74
|
const factory = g.__augur_client_factory ?? _cachedClientFactory;
|
|
52
|
-
|
|
53
|
-
|
|
75
|
+
const decision = slotDecisionOf(_scopedClient?.key ?? "", key, !!factory);
|
|
76
|
+
if (decision === "hit") return _scopedClient.client;
|
|
77
|
+
if (decision === "no-client") return null;
|
|
78
|
+
const client = factory(siteId, token);
|
|
54
79
|
_scopedClient = { key, client };
|
|
55
80
|
return client;
|
|
56
81
|
}
|
|
82
|
+
function parseMethodPath(candidate) {
|
|
83
|
+
if (typeof candidate !== "string") return null;
|
|
84
|
+
const allowed = g.__augur_allowed_method_paths ?? _allowedMethodPaths;
|
|
85
|
+
const listed = allowed !== null && allowed.has(candidate);
|
|
86
|
+
if (!approvePath(candidate, allowed !== null, listed)) return null;
|
|
87
|
+
return candidate;
|
|
88
|
+
}
|
|
57
89
|
|
|
58
90
|
export {
|
|
59
91
|
registerSdkClient,
|
|
@@ -65,6 +97,7 @@ export {
|
|
|
65
97
|
registerClientFactory,
|
|
66
98
|
registerScopedCacheWrapper,
|
|
67
99
|
getScopedCacheWrapper,
|
|
68
|
-
getOrCreateScopedClient
|
|
100
|
+
getOrCreateScopedClient,
|
|
101
|
+
parseMethodPath
|
|
69
102
|
};
|
|
70
|
-
//# sourceMappingURL=chunk-
|
|
103
|
+
//# sourceMappingURL=chunk-NTUPTNOI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/scoped-client-key.ts","../src/sdk-client-store.ts"],"sourcesContent":["//@ backend dafny\n\n/* Cache key for the per-request scoped SDK client (`sdk-client-store.ts`\n `getOrCreateScopedClient`). Verified with LemmaScript → Dafny (`pnpm proofs`; model:\n models/AugurServer.dfy `ScopedClientKey`, whose `ScopedClientKeyInjective` proves that for two\n siteIds with no NUL character, equal keys mean equal siteIds AND equal tokens, so two\n credential pairs never share a cached client; link:\n models/links/augur-server-scoped-client-key.dfy). Only the siteId needs to be NUL-free; the\n token may contain anything. Not proved: that every siteId reaching this function is NUL-free.\n That rests on `getSessionCredentials` (query-action.ts), the only mint point, refusing any\n siteId that fails augur-api's `isSiteId` (`[a-z0-9_-]+`, proved in augur-api), which is\n tested. */\n\n/** Character code of the separator; no siteId contains it. */\nconst SEPARATOR_CODE = 0;\n\n/** `siteId` has no NUL character, so the first NUL in a key marks where the siteId ends. */\nfunction hasNoSeparator(siteId: string): boolean {\n //@ verify\n //@ ensures \\result === !siteId.includes(String.fromCharCode(0))\n return !siteId.includes(String.fromCharCode(SEPARATOR_CODE));\n}\n\n/** The key `siteId + \"\\0\" + token`, or null (the refusal) when the siteId has a NUL. */\nfunction scopedClientKeyOf(siteId: string, token: string): string | null {\n //@ verify\n //@ ensures hasNoSeparator(siteId) ==> \\result === siteId + String.fromCharCode(0) + token\n //@ ensures !hasNoSeparator(siteId) ==> \\result === null\n if (!hasNoSeparator(siteId)) return null;\n return siteId + String.fromCharCode(SEPARATOR_CODE) + token;\n}\n\n/**\n * The key `siteId + \"\\0\" + token`. Callers MUST pass a siteId with no NUL character\n * (`getSessionCredentials` enforces `isSiteId`); with that, distinct pairs give distinct keys.\n * A siteId with a NUL throws instead of returning a key that could collide.\n *\n * @throws TypeError when `siteId` contains a NUL character\n */\nexport function scopedClientKey(siteId: string, token: string): string {\n const key = scopedClientKeyOf(siteId, token);\n if (key === null) {\n throw new TypeError(\"scopedClientKey: siteId must not contain a NUL character\");\n }\n return key;\n}\n","/**\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\nimport { approvePath, slotDecisionOf } from \"./rules\";\nimport { scopedClientKey } from \"./scoped-client-key\";\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. Throws only if `credentials.siteId` contains a NUL\n * (`scopedClientKey`), which the mint point rules out by `isSiteId`, so it\n * is reachable only through an `as SessionCredentials` cast. Side effect on\n * 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 (machine-checked)\n *\n * The key is `scopedClientKey(siteId, token)` = `siteId + \"\\0\" + token`\n * (`scoped-client-key.ts`). Dafny proves (`ScopedClientKeyInjective`) that\n * for two NUL-free siteIds, equal keys mean equal siteIds and equal tokens,\n * so the cache cannot hand one credential pair another pair's client. Only\n * the siteId has to be NUL-free; the token may contain anything.\n *\n * The precondition is enforced, not assumed: `getSessionCredentials`, the\n * only mint point, refuses any `targetSiteId` that fails augur-api's\n * `isSiteId` (`[a-z0-9_-]+`, machine-checked in augur-api), and\n * `scopedClientKey` throws on a NUL rather than return a key that could\n * collide. What is NOT proved: that no other code path casts a value to\n * `SessionCredentials` (see the Trust note above).\n *\n * Do NOT change the separator to a character that could appear in a\n * siteId; the proof is stated for NUL and would have to be redone.\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 = scopedClientKey(siteId, token);\n const factory = g.__augur_client_factory ?? _cachedClientFactory;\n const decision = slotDecisionOf(_scopedClient?.key ?? \"\", key, !!factory);\n if (decision === \"hit\") return _scopedClient!.client;\n if (decision === \"no-client\") 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\") return null;\n const allowed = g.__augur_allowed_method_paths ?? _allowedMethodPaths;\n const listed = allowed !== null && allowed.has(candidate);\n if (!approvePath(candidate, allowed !== null, listed)) 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":";;;;;;AAcA,IAAM,iBAAiB;AAGvB,SAAS,eAAe,QAAyB;AAG/C,SAAO,CAAC,OAAO,SAAS,OAAO,aAAa,cAAc,CAAC;AAC7D;AAGA,SAAS,kBAAkB,QAAgB,OAA8B;AAIvE,MAAI,CAAC,eAAe,MAAM,EAAG,QAAO;AACpC,SAAO,SAAS,OAAO,aAAa,cAAc,IAAI;AACxD;AASO,SAAS,gBAAgB,QAAgB,OAAuB;AACrE,QAAM,MAAM,kBAAkB,QAAQ,KAAK;AAC3C,MAAI,QAAQ,MAAM;AAChB,UAAM,IAAI,UAAU,0DAA0D;AAAA,EAChF;AACA,SAAO;AACT;;;AC+DA,IAAM,IAAI;AASV,IAAI,gBAAyB;AAC7B,IAAI,iBAAwC;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