@simpleapps-com/augur-server 2.4.0 → 2026.11.2
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 +30 -73
- package/README.md +29 -198
- package/dist/actions/agr-info.d.ts +44 -0
- package/dist/actions/agr-info.d.ts.map +1 -0
- package/dist/actions/agr-site.d.ts +38 -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 +48 -0
- package/dist/actions/basecamp2.d.ts.map +1 -0
- package/dist/actions/brand-folder.d.ts +39 -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 +45 -0
- package/dist/actions/customers.d.ts.map +1 -0
- package/dist/actions/favorites.d.ts +21 -0
- package/dist/actions/favorites.d.ts.map +1 -0
- package/dist/actions/gregorovich.d.ts +35 -0
- package/dist/actions/gregorovich.d.ts.map +1 -0
- package/dist/actions/items.d.ts +81 -0
- package/dist/actions/items.d.ts.map +1 -0
- package/dist/actions/joomla.d.ts +60 -0
- package/dist/actions/joomla.d.ts.map +1 -0
- package/dist/actions/legacy.d.ts +46 -0
- package/dist/actions/legacy.d.ts.map +1 -0
- package/dist/actions/logistics.d.ts +41 -0
- package/dist/actions/logistics.d.ts.map +1 -0
- package/dist/actions/orders.d.ts +37 -0
- package/dist/actions/orders.d.ts.map +1 -0
- package/dist/actions/p21-apis.d.ts +34 -0
- package/dist/actions/p21-apis.d.ts.map +1 -0
- package/dist/actions/p21-core.d.ts +47 -0
- package/dist/actions/p21-core.d.ts.map +1 -0
- package/dist/actions/p21-pim.d.ts +37 -0
- package/dist/actions/p21-pim.d.ts.map +1 -0
- package/dist/actions/p21-sism.d.ts +38 -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 +46 -0
- package/dist/actions/pricing.d.ts.map +1 -0
- package/dist/actions/search.d.ts +62 -0
- package/dist/actions/search.d.ts.map +1 -0
- package/dist/actions/shipping.d.ts +57 -0
- package/dist/actions/shipping.d.ts.map +1 -0
- package/dist/actions/site.d.ts +142 -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 +45 -0
- package/dist/actions/vmi.d.ts.map +1 -0
- package/dist/actions/wishlists.d.ts +29 -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 +18 -0
- package/dist/cache/redis-client.d.ts.map +1 -0
- package/dist/cache/with-cache.d.ts +17 -0
- package/dist/cache/with-cache.d.ts.map +1 -0
- package/dist/{chunk-PIYHMA6F.js → chunk-6CSVIBHQ.js} +15 -18
- package/dist/chunk-6CSVIBHQ.js.map +1 -0
- package/dist/{chunk-ALTIINP6.js → chunk-A4IVBK6P.js} +30 -6
- package/dist/chunk-A4IVBK6P.js.map +1 -0
- package/dist/{chunk-KHFEDL47.js → chunk-INVDQQ7T.js} +18 -12
- package/dist/chunk-INVDQQ7T.js.map +1 -0
- package/dist/{chunk-26WZBC4F.js → chunk-LX7SJJOU.js} +275 -667
- package/dist/chunk-LX7SJJOU.js.map +1 -0
- package/dist/chunk-OBWQSGB6.js +205 -0
- package/dist/chunk-OBWQSGB6.js.map +1 -0
- package/dist/{chunk-2NL4QKJN.js → chunk-UVGG74FO.js} +31 -30
- package/dist/chunk-UVGG74FO.js.map +1 -0
- package/dist/duration.d.ts +16 -0
- package/dist/duration.d.ts.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 +9 -7
- 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 +15 -117
- package/dist/query-action.d.ts.map +1 -0
- package/dist/query-action.js +3 -3
- package/dist/query-options-helper.d.ts +34 -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 +230 -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 +15 -14
- 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 +72 -51
- package/package.json +30 -20
- package/dist/actions.d.ts +0 -2
- package/dist/chunk-26WZBC4F.js.map +0 -1
- package/dist/chunk-2NL4QKJN.js.map +0 -1
- package/dist/chunk-ALTIINP6.js.map +0 -1
- package/dist/chunk-DGUM43GV.js +0 -11
- package/dist/chunk-DGUM43GV.js.map +0 -1
- package/dist/chunk-KHFEDL47.js.map +0 -1
- package/dist/chunk-PIYHMA6F.js.map +0 -1
- package/dist/query.d.ts +0 -35
- 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-UVGG74FO.js";
|
|
4
|
+
import "./chunk-A4IVBK6P.js";
|
|
5
|
+
import {
|
|
6
|
+
apiMessageOf,
|
|
7
|
+
apiStatusOf,
|
|
8
|
+
bodyOutcomeOf,
|
|
9
|
+
isCrossOrigin
|
|
10
|
+
} from "./chunk-OBWQSGB6.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,CAA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AACtE,MAAM,MAAM,eAAe,GAAG,IAAI,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,18 @@
|
|
|
1
|
+
import type { CacheKey } from "@simpleapps-com/augur-core";
|
|
2
|
+
import type { Seconds } from "../duration";
|
|
3
|
+
/**
|
|
4
|
+
* Read a cached value by key.
|
|
5
|
+
* Returns `null` on cache miss, circuit-open, connection failure, or if
|
|
6
|
+
* Redis is unavailable. Never throws.
|
|
7
|
+
*/
|
|
8
|
+
export declare function cacheGet(key: CacheKey): Promise<string | null>;
|
|
9
|
+
/**
|
|
10
|
+
* Write a value to cache with a TTL. Fire-and-forget semantics: no-ops
|
|
11
|
+
* silently when the circuit is open or Redis is unavailable. Never throws.
|
|
12
|
+
*/
|
|
13
|
+
export declare function cacheSet(key: CacheKey, value: string, ttl: Seconds): Promise<void>;
|
|
14
|
+
/** Returns the current circuit breaker state. */
|
|
15
|
+
export declare function getCircuitState(): "closed" | "open";
|
|
16
|
+
/** Whether the Redis client is connected and ready to accept commands. */
|
|
17
|
+
export declare function isRedisConnected(): boolean;
|
|
18
|
+
//# 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":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAE3D,OAAO,KAAK,EAAU,OAAO,EAAE,MAAM,aAAa,CAAC;AAgHnD;;;;GAIG;AACH,wBAAsB,QAAQ,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAcpE;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAYxF;AAED,iDAAiD;AACjD,wBAAgB,eAAe,IAAI,QAAQ,GAAG,MAAM,CAEnD;AAED,0EAA0E;AAC1E,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Seconds } from "../duration";
|
|
2
|
+
/**
|
|
3
|
+
* Caches an action's shaped value.
|
|
4
|
+
*
|
|
5
|
+
* @param prefix Cache key prefix (e.g. "example:"). Empty string if none.
|
|
6
|
+
* @param redisTtl Redis TTL (`Seconds`, e.g. `hours(1)`). 0 or undefined = skip caching.
|
|
7
|
+
* @param methodPath Dot-separated SDK method path (e.g. "pricing.priceEngine.get").
|
|
8
|
+
* @param fn The async function to cache.
|
|
9
|
+
* @param keyArgs Values to hash for the cache key.
|
|
10
|
+
*/
|
|
11
|
+
export declare function withServerCache<T>(prefix: string, redisTtl: Seconds | undefined, methodPath: string, fn: () => Promise<T>, ...keyArgs: unknown[]): Promise<T>;
|
|
12
|
+
/**
|
|
13
|
+
* Caches a raw SDK result (the envelope as returned), in its own key space: the same
|
|
14
|
+
* parameters as {@link withServerCache}.
|
|
15
|
+
*/
|
|
16
|
+
export declare function withRawSdkCache<T>(prefix: string, redisTtl: Seconds | undefined, methodPath: string, fn: () => Promise<T>, ...keyArgs: unknown[]): Promise<T>;
|
|
17
|
+
//# 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":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAqD3C;;;;;;;;GAQG;AACH,wBAAsB,eAAe,CAAC,CAAC,EACrC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,OAAO,GAAG,SAAS,EAC7B,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,GAAG,OAAO,EAAE,OAAO,EAAE,GACpB,OAAO,CAAC,CAAC,CAAC,CAEZ;AAED;;;GAGG;AACH,wBAAsB,eAAe,CAAC,CAAC,EACrC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,OAAO,GAAG,SAAS,EAC7B,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,GAAG,OAAO,EAAE,OAAO,EAAE,GACpB,OAAO,CAAC,CAAC,CAAC,CAEZ"}
|
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
// src/query-options-helper.ts
|
|
2
|
-
import {
|
|
2
|
+
import { tierBrowserGcTime, tierStaleTime } from "@simpleapps-com/augur-utils";
|
|
3
3
|
import { resolveGcTime } from "@simpleapps-com/augur-core";
|
|
4
|
+
function queryKeyFor(baseKey, params, excludeFromKey) {
|
|
5
|
+
const paramEntries = Object.entries(params).filter(([key, value]) => {
|
|
6
|
+
if (excludeFromKey && key === excludeFromKey) return false;
|
|
7
|
+
return value !== void 0 && value !== null && value !== "";
|
|
8
|
+
}).map(([key, value]) => `${key}:${value}`).sort();
|
|
9
|
+
return [baseKey, ...paramEntries];
|
|
10
|
+
}
|
|
4
11
|
var createQueryOptions = ({
|
|
5
12
|
baseKey,
|
|
6
13
|
params,
|
|
7
14
|
queryFn,
|
|
8
15
|
enabledFn,
|
|
9
|
-
staleTime =
|
|
10
|
-
gcTime =
|
|
16
|
+
staleTime = tierStaleTime("SEMI_STATIC"),
|
|
17
|
+
gcTime = tierBrowserGcTime("SEMI_STATIC"),
|
|
11
18
|
excludeFromKey
|
|
12
19
|
}) => {
|
|
13
|
-
const paramEntries = Object.entries(params).filter(([key, value]) => {
|
|
14
|
-
if (excludeFromKey && key === excludeFromKey) return false;
|
|
15
|
-
return value !== void 0 && value !== null && value !== "";
|
|
16
|
-
}).map(([key, value]) => `${key}:${value}`).sort();
|
|
17
|
-
const queryKey = [baseKey, ...paramEntries];
|
|
18
20
|
return {
|
|
19
|
-
queryKey,
|
|
21
|
+
queryKey: queryKeyFor(baseKey, params, excludeFromKey),
|
|
20
22
|
queryFn: () => queryFn(params),
|
|
21
23
|
enabled: enabledFn ? enabledFn(params) : true,
|
|
22
24
|
staleTime,
|
|
@@ -27,17 +29,12 @@ var createSuspenseQueryOptions = ({
|
|
|
27
29
|
baseKey,
|
|
28
30
|
params,
|
|
29
31
|
queryFn,
|
|
30
|
-
staleTime =
|
|
31
|
-
gcTime =
|
|
32
|
+
staleTime = tierStaleTime("SEMI_STATIC"),
|
|
33
|
+
gcTime = tierBrowserGcTime("SEMI_STATIC"),
|
|
32
34
|
excludeFromKey
|
|
33
35
|
}) => {
|
|
34
|
-
const paramEntries = Object.entries(params).filter(([key, value]) => {
|
|
35
|
-
if (excludeFromKey && key === excludeFromKey) return false;
|
|
36
|
-
return value !== void 0 && value !== null && value !== "";
|
|
37
|
-
}).map(([key, value]) => `${key}:${value}`).sort();
|
|
38
|
-
const queryKey = [baseKey, ...paramEntries];
|
|
39
36
|
return {
|
|
40
|
-
queryKey,
|
|
37
|
+
queryKey: queryKeyFor(baseKey, params, excludeFromKey),
|
|
41
38
|
queryFn: () => queryFn(params),
|
|
42
39
|
staleTime,
|
|
43
40
|
gcTime: resolveGcTime(gcTime)
|
|
@@ -48,4 +45,4 @@ export {
|
|
|
48
45
|
createQueryOptions,
|
|
49
46
|
createSuspenseQueryOptions
|
|
50
47
|
};
|
|
51
|
-
//# sourceMappingURL=chunk-
|
|
48
|
+
//# sourceMappingURL=chunk-6CSVIBHQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/query-options-helper.ts"],"sourcesContent":["import type { UseQueryOptions, UseSuspenseQueryOptions } from \"@tanstack/react-query\";\nimport { tierBrowserGcTime, tierStaleTime } from \"@simpleapps-com/augur-utils\";\nimport { resolveGcTime } from \"@simpleapps-com/augur-core\";\nimport type { Millis } from \"./duration\";\n\nexport interface QueryOptionsConfig<TParams, TData> {\n /** Base query key (e.g., \"customer-orders\") */\n baseKey: string;\n /** Parameters object */\n params: TParams;\n /** Function that returns the data */\n queryFn: (params: TParams) => Promise<TData>;\n /** Function to determine if query should be enabled */\n enabledFn?: (params: TParams) => boolean;\n /** Custom stale time (default: SEMI_STATIC's) */\n staleTime?: Millis;\n /**\n * Custom garbage collection time in the browser (default: SEMI_STATIC's). On the server the\n * returned gcTime is always `Infinity` (no GC timer), so the per-request cache is freed with\n * the request (#481).\n */\n gcTime?: Millis;\n /** Key to exclude from query key generation */\n excludeFromKey?: keyof TParams;\n}\n\n/**\n * `[baseKey, \"key:value\", ...]` from the params, sorted, leaving out `excludeFromKey` and\n * any undefined, null or empty-string value.\n */\nfunction queryKeyFor<TParams extends Record<string, unknown>>(\n baseKey: string,\n params: TParams,\n excludeFromKey: keyof TParams | undefined,\n): string[] {\n const paramEntries = Object.entries(params)\n .filter(([key, value]) => {\n if (excludeFromKey && key === excludeFromKey) return false;\n return value !== undefined && value !== null && value !== \"\";\n })\n .map(([key, value]) => `${key}:${value}`)\n .sort();\n\n return [baseKey, ...paramEntries];\n}\n\n/**\n * Creates useQuery options with consistent key generation.\n * Filters out undefined/null/empty params from the query key.\n */\nexport const createQueryOptions = <TParams extends Record<string, unknown>, TData>({\n baseKey,\n params,\n queryFn,\n enabledFn,\n staleTime = tierStaleTime(\"SEMI_STATIC\"),\n gcTime = tierBrowserGcTime(\"SEMI_STATIC\"),\n excludeFromKey,\n}: QueryOptionsConfig<TParams, TData>): UseQueryOptions<TData> => {\n return {\n queryKey: queryKeyFor(baseKey, params, excludeFromKey),\n queryFn: () => queryFn(params),\n enabled: enabledFn ? enabledFn(params) : true,\n staleTime,\n gcTime: resolveGcTime(gcTime),\n };\n};\n\n/**\n * Creates useSuspenseQuery options with consistent key generation.\n * Same as createQueryOptions but without enabledFn (suspense queries\n * cannot be disabled).\n */\nexport const createSuspenseQueryOptions = <TParams extends Record<string, unknown>, TData>({\n baseKey,\n params,\n queryFn,\n staleTime = tierStaleTime(\"SEMI_STATIC\"),\n gcTime = tierBrowserGcTime(\"SEMI_STATIC\"),\n excludeFromKey,\n}: Omit<QueryOptionsConfig<TParams, TData>, \"enabledFn\">): UseSuspenseQueryOptions<TData> => {\n return {\n queryKey: queryKeyFor(baseKey, params, excludeFromKey),\n queryFn: () => queryFn(params),\n staleTime,\n gcTime: resolveGcTime(gcTime),\n };\n};\n"],"mappings":";AACA,SAAS,mBAAmB,qBAAqB;AACjD,SAAS,qBAAqB;AA4B9B,SAAS,YACP,SACA,QACA,gBACU;AACV,QAAM,eAAe,OAAO,QAAQ,MAAM,EACvC,OAAO,CAAC,CAAC,KAAK,KAAK,MAAM;AACxB,QAAI,kBAAkB,QAAQ,eAAgB,QAAO;AACrD,WAAO,UAAU,UAAa,UAAU,QAAQ,UAAU;AAAA,EAC5D,CAAC,EACA,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,GAAG,IAAI,KAAK,EAAE,EACvC,KAAK;AAER,SAAO,CAAC,SAAS,GAAG,YAAY;AAClC;AAMO,IAAM,qBAAqB,CAAiD;AAAA,EACjF;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,cAAc,aAAa;AAAA,EACvC,SAAS,kBAAkB,aAAa;AAAA,EACxC;AACF,MAAkE;AAChE,SAAO;AAAA,IACL,UAAU,YAAY,SAAS,QAAQ,cAAc;AAAA,IACrD,SAAS,MAAM,QAAQ,MAAM;AAAA,IAC7B,SAAS,YAAY,UAAU,MAAM,IAAI;AAAA,IACzC;AAAA,IACA,QAAQ,cAAc,MAAM;AAAA,EAC9B;AACF;AAOO,IAAM,6BAA6B,CAAiD;AAAA,EACzF;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,cAAc,aAAa;AAAA,EACvC,SAAS,kBAAkB,aAAa;AAAA,EACxC;AACF,MAA6F;AAC3F,SAAO;AAAA,IACL,UAAU,YAAY,SAAS,QAAQ,cAAc;AAAA,IACrD,SAAS,MAAM,QAAQ,MAAM;AAAA,IAC7B;AAAA,IACA,QAAQ,cAAc,MAAM;AAAA,EAC9B;AACF;","names":[]}
|
|
@@ -1,3 +1,25 @@
|
|
|
1
|
+
import {
|
|
2
|
+
approvePath,
|
|
3
|
+
slotDecisionOf
|
|
4
|
+
} from "./chunk-OBWQSGB6.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;
|
|
@@ -48,18 +70,20 @@ function getScopedCacheWrapper() {
|
|
|
48
70
|
}
|
|
49
71
|
function getOrCreateScopedClient(credentials) {
|
|
50
72
|
const { siteId, token } = credentials;
|
|
51
|
-
const key =
|
|
52
|
-
if (_scopedClient?.key === key) return _scopedClient.client;
|
|
73
|
+
const key = scopedClientKey(siteId, token);
|
|
53
74
|
const factory = g.__augur_client_factory ?? _cachedClientFactory;
|
|
54
|
-
|
|
75
|
+
const decision = slotDecisionOf(_scopedClient?.key ?? "", key, !!factory);
|
|
76
|
+
if (decision === "hit") return _scopedClient.client;
|
|
77
|
+
if (decision === "no-client") return null;
|
|
55
78
|
const client = factory(siteId, token);
|
|
56
79
|
_scopedClient = { key, client };
|
|
57
80
|
return client;
|
|
58
81
|
}
|
|
59
82
|
function parseMethodPath(candidate) {
|
|
60
|
-
if (typeof candidate !== "string"
|
|
83
|
+
if (typeof candidate !== "string") return null;
|
|
61
84
|
const allowed = g.__augur_allowed_method_paths ?? _allowedMethodPaths;
|
|
62
|
-
|
|
85
|
+
const listed = allowed !== null && allowed.has(candidate);
|
|
86
|
+
if (!approvePath(candidate, allowed !== null, listed)) return null;
|
|
63
87
|
return candidate;
|
|
64
88
|
}
|
|
65
89
|
|
|
@@ -76,4 +100,4 @@ export {
|
|
|
76
100
|
getOrCreateScopedClient,
|
|
77
101
|
parseMethodPath
|
|
78
102
|
};
|
|
79
|
-
//# sourceMappingURL=chunk-
|
|
103
|
+
//# sourceMappingURL=chunk-A4IVBK6P.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;AAC5C,IAAI,oBAAmC;AACvC,IAAI,uBAA6C;AACjD,IAAI,4BAAuD;AAC3D,IAAI,gBAAyD;AAC7D,IAAI,sBAA0C;AAGvC,SAAS,kBAAkB,QAAuB;AACvD,kBAAgB;AAChB,IAAE,qBAAqB;AACzB;AAGO,SAAS,qBAA8B;AAC5C,QAAM,SAAS,EAAE,sBAAsB;AACvC,MAAI,QAAQ;AACV,QAAI,CAAC,EAAE,oBAAoB;AACzB,QAAE,qBAAqB;AAAA,IACzB;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,SAAS,uBAAuB,SAA+B;AACpE,mBAAiB;AACjB,IAAE,2BAA2B;AAC/B;AAGO,SAAS,oBAA2C;AACzD,SAAO,EAAE,4BAA4B,kBAAkB;AACzD;AAGO,SAAS,mBAAmB,QAAsB;AACvD,sBAAoB;AACpB,IAAE,sBAAsB;AAC1B;AAGO,SAAS,gBAA+B;AAC7C,SAAO,EAAE,uBAAuB,qBAAqB;AACvD;AAGO,SAAS,sBAAsB,SAA8B;AAClE,yBAAuB;AACvB,IAAE,yBAAyB;AAC7B;AAQO,SAAS,2BAA2B,SAAmC;AAC5E,8BAA4B;AAC5B,IAAE,+BAA+B;AACnC;AAGO,SAAS,wBAAmD;AACjE,SAAO,EAAE,gCAAgC,6BAA6B;AACxE;AA6FO,SAAS,wBAAwB,aAA0C;AAChF,QAAM,EAAE,QAAQ,MAAM,IAAI;AAC1B,QAAM,MAAM,gBAAgB,QAAQ,KAAK;AACzC,QAAM,UAAU,EAAE,0BAA0B;AAC5C,QAAM,WAAW,eAAe,eAAe,OAAO,IAAI,KAAK,CAAC,CAAC,OAAO;AACxE,MAAI,aAAa,MAAO,QAAO,cAAe;AAC9C,MAAI,aAAa,YAAa,QAAO;AAErC,QAAM,SAAS,QAAS,QAAQ,KAAK;AACrC,kBAAgB,EAAE,KAAK,OAAO;AAC9B,SAAO;AACT;AAgDO,SAAS,gBAAgB,WAA+C;AAC7E,MAAI,OAAO,cAAc,SAAU,QAAO;AAC1C,QAAM,UAAU,EAAE,gCAAgC;AAClD,QAAM,SAAS,YAAY,QAAQ,QAAQ,IAAI,SAAS;AACxD,MAAI,CAAC,YAAY,WAAW,YAAY,MAAM,MAAM,EAAG,QAAO;AAC9D,SAAO;AACT;","names":[]}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
verifiedFlag
|
|
3
|
+
} from "./chunk-OBWQSGB6.js";
|
|
4
|
+
|
|
1
5
|
// src/auth.ts
|
|
2
6
|
import Credentials from "next-auth/providers/credentials";
|
|
3
7
|
function buildInternalCallbacks(augurClient) {
|
|
@@ -23,12 +27,11 @@ function buildInternalCallbacks(augurClient) {
|
|
|
23
27
|
},
|
|
24
28
|
async cartHdrLookup(userId, _token, contactId, customerId) {
|
|
25
29
|
const result = await augurClient.commerce.cartHdr.lookup.get({
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
30
|
+
userId: Number(userId) || 0,
|
|
31
|
+
customerId: Number(customerId) || 0,
|
|
32
|
+
contactId: Number(contactId) || 0
|
|
30
33
|
});
|
|
31
|
-
return result.data
|
|
34
|
+
return result.data || null;
|
|
32
35
|
}
|
|
33
36
|
};
|
|
34
37
|
}
|
|
@@ -59,6 +62,13 @@ async function lookupCartHdr(siteCallbacks, profile, defaultCustomerId, defaultC
|
|
|
59
62
|
);
|
|
60
63
|
return cartHdr?.cartHdrUid;
|
|
61
64
|
}
|
|
65
|
+
function baseUserOf(token) {
|
|
66
|
+
return {
|
|
67
|
+
id: token["id"] || "",
|
|
68
|
+
username: token["username"] || "",
|
|
69
|
+
isVerified: token["isVerified"] || false
|
|
70
|
+
};
|
|
71
|
+
}
|
|
62
72
|
function createAuthConfig(options) {
|
|
63
73
|
const {
|
|
64
74
|
secret = process.env["AUTH_SECRET"],
|
|
@@ -85,7 +95,7 @@ function createAuthConfig(options) {
|
|
|
85
95
|
const { id, isVerified, username, token, siteId } = credentials;
|
|
86
96
|
return {
|
|
87
97
|
id,
|
|
88
|
-
isVerified: isVerified
|
|
98
|
+
isVerified: verifiedFlag(isVerified),
|
|
89
99
|
username,
|
|
90
100
|
token,
|
|
91
101
|
targetSiteId: siteId || void 0
|
|
@@ -101,11 +111,7 @@ function createAuthConfig(options) {
|
|
|
101
111
|
return baseUrl;
|
|
102
112
|
},
|
|
103
113
|
async session({ session, token }) {
|
|
104
|
-
const baseUser =
|
|
105
|
-
id: token["id"] || "",
|
|
106
|
-
username: token["username"] || "",
|
|
107
|
-
isVerified: token["isVerified"] || false
|
|
108
|
-
};
|
|
114
|
+
const baseUser = baseUserOf(token);
|
|
109
115
|
const targetSiteId = token["targetSiteId"];
|
|
110
116
|
const buildSession = (userOverrides = {}) => ({
|
|
111
117
|
...session,
|
|
@@ -161,4 +167,4 @@ function createAuthConfig(options) {
|
|
|
161
167
|
export {
|
|
162
168
|
createAuthConfig
|
|
163
169
|
};
|
|
164
|
-
//# sourceMappingURL=chunk-
|
|
170
|
+
//# sourceMappingURL=chunk-INVDQQ7T.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth.ts"],"sourcesContent":["// @simpleapps-com/augur-server/auth\n// NextAuth 5 configuration factory for Augur ecommerce sites.\n\nimport type { AugurAPI } from \"@simpleapps-com/augur-api\";\nimport type { NextAuthConfig } from \"next-auth\";\nimport Credentials from \"next-auth/providers/credentials\";\nimport { verifiedFlag } from \"./rules\";\n\n/** Base user fields shared across all Augur sites. */\nexport interface AugurUser {\n id: string;\n username: string;\n isVerified: boolean;\n name?: string;\n email?: string;\n customerId?: string | number;\n contactId?: string | number;\n cartHdrUid?: number;\n token?: string;\n /** Target site ID for cross-site auth sessions (augur_info + body siteId). */\n targetSiteId?: string;\n}\n\n/** Session shape returned by all Augur sites. */\nexport interface AugurSession {\n user: AugurUser;\n token?: string;\n targetSiteId?: string;\n expires: string;\n}\n\n/** JWT token shape used by Augur auth. */\nexport interface AugurJWT {\n id: string;\n username: string;\n isVerified: boolean;\n token?: string;\n targetSiteId?: string;\n}\n\n/** Site-specific callbacks the consumer can provide. */\nexport interface AugurAuthCallbacks {\n /** Fetch user profile from the Augur API given the user's Joomla ID. */\n getUserProfile: (userId: string) => Promise<AugurUser | null>;\n /** Look up or create a cart header for the authenticated user. */\n cartHdrLookup?: (\n userId: string | number,\n token: string,\n contactId: string | number,\n customerId: string | number,\n ) => Promise<{ cartHdrUid?: number } | null>;\n}\n\n/** Derived from augur-api SDK — keeps types in sync automatically. */\nexport type AugurAuthClient = Pick<AugurAPI, \"joomla\" | \"commerce\">;\n\nexport interface CreateAuthConfigOptions {\n /** Augur SDK client. When provided, auth SDK calls are handled internally. */\n augurClient?: AugurAuthClient;\n /** Site-specific callbacks. Override internal SDK calls when custom behavior is needed. */\n callbacks?: Partial<AugurAuthCallbacks>;\n /** NextAuth secret (defaults to AUTH_SECRET env var). */\n secret?: string;\n /** Session max age in seconds (defaults to 4 hours). */\n maxAge?: number;\n /** Default customer ID when profile doesn't provide one. */\n defaultCustomerId?: string | number;\n /** Default contact ID for cart header lookups. */\n defaultContactId?: string | number;\n /** Enable NextAuth debug logging (defaults to NODE_ENV === \"development\"). */\n debug?: boolean;\n}\n\n/** Build internal callbacks that call the Augur SDK directly. */\nfunction buildInternalCallbacks(augurClient: AugurAuthClient): AugurAuthCallbacks {\n return {\n async getUserProfile(userId: string): Promise<AugurUser | null> {\n if (!userId) return null;\n const uid = parseInt(userId, 10);\n if (isNaN(uid)) return null;\n const result = await augurClient.joomla.users.doc.get(uid, {\n edgeCache: 1,\n });\n const data = result.data as Record<string, unknown>;\n if (!data) return null;\n return {\n id: String(data[\"id\"]),\n name: data[\"name\"] as string | undefined,\n username: data[\"username\"] as string,\n email: data[\"email\"] as string | undefined,\n isVerified: true,\n customerId: data[\"customerId\"] as string | number | undefined,\n contactId: data[\"contactId\"] as string | number | undefined,\n };\n },\n async cartHdrLookup(\n userId: string | number,\n _token: string,\n contactId: string | number,\n customerId: string | number,\n ): Promise<{ cartHdrUid?: number } | null> {\n const result = await augurClient.commerce.cartHdr.lookup.get({\n userId: Number(userId) || 0,\n customerId: Number(customerId) || 0,\n contactId: Number(contactId) || 0,\n });\n // The SDK returns `false` when no cart header exists.\n return result.data || null;\n },\n };\n}\n\n/** Resolve final callbacks: callback overrides take priority over internal SDK calls. */\nfunction resolveCallbacks(options: CreateAuthConfigOptions): AugurAuthCallbacks {\n const { augurClient, callbacks } = options;\n\n if (augurClient) {\n const internal = buildInternalCallbacks(augurClient);\n return {\n getUserProfile: callbacks?.getUserProfile ?? internal.getUserProfile,\n cartHdrLookup: callbacks?.cartHdrLookup ?? internal.cartHdrLookup,\n };\n }\n\n if (!callbacks?.getUserProfile) {\n throw new Error(\"createAuthConfig requires either `augurClient` or `callbacks.getUserProfile`\");\n }\n\n return {\n getUserProfile: callbacks.getUserProfile,\n cartHdrLookup: callbacks.cartHdrLookup,\n };\n}\n\n/**\n * Create a NextAuth 5 configuration for an Augur ecommerce site.\n *\n * Accepts either an `augurClient` (recommended) for zero-boilerplate auth,\n * or explicit `callbacks` for custom behavior. Callback overrides take\n * priority when both are provided.\n *\n * For cross-site auth (augur-support pattern): use an augur_info API client\n * and pass `siteId` in the signIn credentials. The API uses augur_info as the\n * header siteId and the body siteId as the target. The session stores the\n * targetSiteId and user-scoped token for later API calls.\n *\n * @example\n * ```ts\n * // Single-site (recommended)\n * export const { handlers, signIn, signOut, auth } = NextAuth(\n * createAuthConfig({ augurClient }),\n * );\n * ```\n *\n * @example\n * ```ts\n * // Cross-site: site passes siteId in signIn credentials\n * await signIn(\"credentials\", { id, username, isVerified: \"true\", token, siteId: targetSiteId });\n * ```\n */\nasync function lookupCartHdr(\n siteCallbacks: AugurAuthCallbacks,\n profile: AugurUser,\n defaultCustomerId?: string | number,\n defaultContactId?: string | number,\n): Promise<number | undefined> {\n if (!siteCallbacks.cartHdrLookup || !profile.id) return undefined;\n const cartHdr = await siteCallbacks.cartHdrLookup(\n profile.id,\n \"\",\n profile.contactId ?? defaultContactId ?? \"\",\n profile.customerId ?? defaultCustomerId ?? \"\",\n );\n return cartHdr?.cartHdrUid;\n}\n\n/** The user fields the JWT carries, each defaulted when absent (\"\", \"\", false). */\nfunction baseUserOf(token: Record<string, unknown>): {\n id: string;\n username: string;\n isVerified: boolean;\n} {\n return {\n id: (token[\"id\"] as string) || \"\",\n username: (token[\"username\"] as string) || \"\",\n isVerified: (token[\"isVerified\"] as boolean) || false,\n };\n}\n\n/** Creates a NextAuth configuration with Joomla credential provider, session callbacks, and automatic cart initialization. */\nexport function createAuthConfig(options: CreateAuthConfigOptions): NextAuthConfig {\n const {\n secret = process.env[\"AUTH_SECRET\"],\n maxAge = 4 * 60 * 60,\n defaultCustomerId,\n defaultContactId,\n debug = process.env[\"NODE_ENV\"] === \"development\",\n } = options;\n\n const siteCallbacks = resolveCallbacks(options);\n\n return {\n providers: [\n Credentials({\n name: \"Credentials\",\n credentials: {\n username: { label: \"Username\", type: \"text\" },\n password: { label: \"Password\", type: \"password\" },\n id: { label: \"ID\", type: \"text\" },\n isVerified: { label: \"Is Verified\", type: \"text\" },\n token: { label: \"Token\", type: \"text\" },\n siteId: { label: \"Site ID\", type: \"text\" },\n },\n async authorize(credentials) {\n if (!credentials) return null;\n\n const { id, isVerified, username, token, siteId } = credentials as {\n id: string;\n isVerified: string;\n username: string;\n token: string;\n siteId?: string;\n };\n\n return {\n id,\n isVerified: verifiedFlag(isVerified),\n username,\n token,\n targetSiteId: siteId || undefined,\n };\n },\n }),\n ],\n callbacks: {\n async signIn() {\n return true;\n },\n async redirect({ baseUrl }) {\n return baseUrl;\n },\n async session({ session, token }) {\n const baseUser = baseUserOf(token);\n\n const targetSiteId = token[\"targetSiteId\"] as string | undefined;\n\n const buildSession = (userOverrides = {}) => ({\n ...session,\n user: { ...session.user, ...baseUser, ...userOverrides, targetSiteId },\n token: token[\"token\"] as string | undefined,\n targetSiteId,\n });\n\n try {\n const userProfile = await siteCallbacks.getUserProfile(baseUser.id);\n if (!userProfile) return buildSession();\n\n const cartHdrUid = await lookupCartHdr(\n siteCallbacks,\n userProfile,\n defaultCustomerId,\n defaultContactId,\n );\n\n return buildSession({\n name: userProfile.name ?? session.user?.name,\n email: userProfile.email ?? session.user?.email,\n customerId: userProfile.customerId ?? defaultCustomerId,\n contactId: userProfile.contactId,\n cartHdrUid,\n });\n } catch {\n return buildSession();\n }\n },\n async jwt({ token, user }) {\n if (user) {\n const typedUser = user as {\n id: string;\n isVerified: boolean;\n username: string;\n token?: string;\n targetSiteId?: string;\n };\n\n return {\n ...token,\n id: typedUser.id,\n isVerified: typedUser.isVerified,\n username: typedUser.username,\n token: typedUser.token,\n targetSiteId: typedUser.targetSiteId,\n };\n }\n return token;\n },\n },\n secret,\n debug,\n session: {\n strategy: \"jwt\",\n maxAge,\n },\n trustHost: true,\n };\n}\n"],"mappings":";;;;;AAKA,OAAO,iBAAiB;AAqExB,SAAS,uBAA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