@simpleapps-com/augur-server 2026.11.10 → 2026.11.12
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 +2 -2
- package/README.md +45 -6
- package/dist/actions/commerce.d.ts.map +1 -1
- package/dist/actions/customers.d.ts +7 -2
- package/dist/actions/customers.d.ts.map +1 -1
- package/dist/actions/joomla.d.ts +3 -2
- package/dist/actions/joomla.d.ts.map +1 -1
- package/dist/actions/pricing.d.ts.map +1 -1
- package/dist/actions/require-customer.d.ts +9 -0
- package/dist/actions/require-customer.d.ts.map +1 -0
- package/dist/address-id.d.ts +12 -0
- package/dist/address-id.d.ts.map +1 -0
- package/dist/api-handler.d.ts.map +1 -1
- package/dist/api.js +7 -5
- package/dist/api.js.map +1 -1
- package/dist/auth.d.ts +44 -6
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +4 -3
- package/dist/{chunk-4KPTIVYO.js → chunk-5DBFTSWY.js} +11 -14
- package/dist/chunk-5DBFTSWY.js.map +1 -0
- package/dist/{chunk-AYHUM7SG.js → chunk-GKT4MAWC.js} +46 -64
- package/dist/chunk-GKT4MAWC.js.map +1 -0
- package/dist/{chunk-BG4G5QUQ.js → chunk-HGJF667G.js} +8 -1
- package/dist/{chunk-BG4G5QUQ.js.map → chunk-HGJF667G.js.map} +1 -1
- package/dist/chunk-ILXNFJVM.js +86 -0
- package/dist/chunk-ILXNFJVM.js.map +1 -0
- package/dist/{chunk-JIYVQWXK.js → chunk-IM7FDRER.js} +1 -1
- package/dist/chunk-IM7FDRER.js.map +1 -0
- package/dist/chunk-M35O5JDZ.js +257 -0
- package/dist/chunk-M35O5JDZ.js.map +1 -0
- package/dist/{chunk-G5P4IDK7.js → chunk-Y54RGILF.js} +35 -3
- package/dist/chunk-Y54RGILF.js.map +1 -0
- package/dist/hooks.js +4 -3
- package/dist/hooks.js.map +1 -1
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/query-action.d.ts +2 -8
- package/dist/query-action.d.ts.map +1 -1
- package/dist/query-action.js +4 -3
- package/dist/recaptcha.d.ts.map +1 -1
- package/dist/rules.d.ts +17 -17
- package/dist/rules.d.ts.map +1 -1
- package/dist/sdk-client-store.d.ts +4 -3
- package/dist/sdk-client-store.d.ts.map +1 -1
- package/dist/server-site.d.ts +6 -8
- package/dist/server-site.d.ts.map +1 -1
- package/dist/session-rules.d.ts +118 -0
- package/dist/session-rules.d.ts.map +1 -0
- package/dist/site.js +14 -9
- package/dist/site.js.map +1 -1
- package/dist/sitemap.js +2 -2
- package/dist/testing.js +4 -4
- package/llms.txt +4 -2
- package/next-auth.d.ts +2 -2
- package/package.json +6 -5
- package/dist/chunk-4KPTIVYO.js.map +0 -1
- package/dist/chunk-AUIC4HS2.js +0 -174
- package/dist/chunk-AUIC4HS2.js.map +0 -1
- package/dist/chunk-AYHUM7SG.js.map +0 -1
- package/dist/chunk-G5P4IDK7.js.map +0 -1
- package/dist/chunk-JIYVQWXK.js.map +0 -1
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import {
|
|
2
|
+
actsAsDefaultOf,
|
|
3
|
+
asksJoomla,
|
|
4
|
+
callbackSourceOf,
|
|
5
|
+
claimVerified,
|
|
6
|
+
configRefused,
|
|
7
|
+
lookupNumberOf,
|
|
8
|
+
sessionCustomerOf,
|
|
9
|
+
sessionKept,
|
|
10
|
+
sessionKeys,
|
|
11
|
+
signInOutcomeOf
|
|
12
|
+
} from "./chunk-ILXNFJVM.js";
|
|
13
|
+
import {
|
|
14
|
+
cartLookupRuns,
|
|
15
|
+
getCrossSite,
|
|
16
|
+
signInTarget
|
|
17
|
+
} from "./chunk-5DBFTSWY.js";
|
|
18
|
+
|
|
19
|
+
// src/auth.ts
|
|
20
|
+
import { addressIdOf, errorLogLine, logLineOf } from "@simpleapps-com/augur-utils";
|
|
21
|
+
import Credentials from "next-auth/providers/credentials";
|
|
22
|
+
function buildInternalCallbacks(augurClient) {
|
|
23
|
+
return {
|
|
24
|
+
async getUserProfile(userId) {
|
|
25
|
+
if (!userId) return null;
|
|
26
|
+
const uid = parseInt(userId, 10);
|
|
27
|
+
if (isNaN(uid)) return null;
|
|
28
|
+
const result = await augurClient.joomla.users.doc.get(uid, {
|
|
29
|
+
edgeCache: 1
|
|
30
|
+
});
|
|
31
|
+
const data = result.data;
|
|
32
|
+
if (!data) return null;
|
|
33
|
+
return {
|
|
34
|
+
id: String(data["id"]),
|
|
35
|
+
name: data["name"],
|
|
36
|
+
username: data["username"],
|
|
37
|
+
email: data["email"],
|
|
38
|
+
isVerified: true,
|
|
39
|
+
// Joomla holds it as text; "" and "0" are no customer, so none reaches the session (atlas#95).
|
|
40
|
+
customerId: addressIdOf(data["customerId"]) ?? void 0,
|
|
41
|
+
contactId: data["contactId"],
|
|
42
|
+
// Joomla's `block` is 1 for a blocked account (the session then ends, sessionKept).
|
|
43
|
+
blocked: data["block"] === 1
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
async verifyPassword(username, password, siteId) {
|
|
47
|
+
const result = await augurClient.joomla.users.verifyPassword.create(
|
|
48
|
+
siteId === void 0 ? { username, password } : { username, password, siteId }
|
|
49
|
+
);
|
|
50
|
+
return result.data;
|
|
51
|
+
},
|
|
52
|
+
async cartHdrLookup(userId, _token, contactId, customerId) {
|
|
53
|
+
const user = Number(userId);
|
|
54
|
+
const contact = Number(contactId);
|
|
55
|
+
const result = await augurClient.commerce.cartHdr.lookup.get({
|
|
56
|
+
userId: lookupNumberOf(!Number.isNaN(user), user),
|
|
57
|
+
// Always a usable id: lookupCartHdr looks up no cart without one (atlas#95).
|
|
58
|
+
customerId,
|
|
59
|
+
contactId: lookupNumberOf(!Number.isNaN(contact), contact)
|
|
60
|
+
});
|
|
61
|
+
return result.data || null;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function resolveCallbacks(options) {
|
|
66
|
+
const site = options.callbacks ?? {};
|
|
67
|
+
const client = options.augurClient;
|
|
68
|
+
if (configRefused(
|
|
69
|
+
client !== void 0,
|
|
70
|
+
site.getUserProfile !== void 0,
|
|
71
|
+
site.verifyPassword !== void 0
|
|
72
|
+
)) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
"createAuthConfig requires either `augurClient` or both `callbacks.getUserProfile` and `callbacks.verifyPassword`"
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
const internal = client === void 0 ? {} : buildInternalCallbacks(client);
|
|
78
|
+
const pick = (key) => callbackSourceOf(site[key] !== void 0, internal[key] !== void 0) === "override" ? site[key] : internal[key];
|
|
79
|
+
return {
|
|
80
|
+
getUserProfile: pick("getUserProfile"),
|
|
81
|
+
cartHdrLookup: pick("cartHdrLookup"),
|
|
82
|
+
verifyPassword: pick("verifyPassword")
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
async function lookupCartHdr(siteCallbacks, profile, customerId, defaultContactId) {
|
|
86
|
+
const lookup = siteCallbacks.cartHdrLookup;
|
|
87
|
+
if (!cartLookupRuns(lookup !== void 0, !!profile.id, customerId)) {
|
|
88
|
+
return void 0;
|
|
89
|
+
}
|
|
90
|
+
const cartHdr = await lookup(
|
|
91
|
+
profile.id,
|
|
92
|
+
"",
|
|
93
|
+
profile.contactId ?? defaultContactId ?? "",
|
|
94
|
+
customerId
|
|
95
|
+
);
|
|
96
|
+
return cartHdr?.cartHdrUid;
|
|
97
|
+
}
|
|
98
|
+
function baseUserOf(token) {
|
|
99
|
+
return {
|
|
100
|
+
id: token["id"] || "",
|
|
101
|
+
username: token["username"] || "",
|
|
102
|
+
isVerified: claimVerified(
|
|
103
|
+
typeof token["isVerified"] === "boolean",
|
|
104
|
+
token["isVerified"] === true
|
|
105
|
+
)
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function createAuthConfig(options) {
|
|
109
|
+
const {
|
|
110
|
+
secret = process.env["AUTH_SECRET"],
|
|
111
|
+
maxAge = 4 * 60 * 60,
|
|
112
|
+
defaultCustomerId,
|
|
113
|
+
defaultContactId,
|
|
114
|
+
debug = process.env["NODE_ENV"] === "development"
|
|
115
|
+
} = options;
|
|
116
|
+
const actsAsDefault = actsAsDefaultOf(options.withoutCustomer);
|
|
117
|
+
if (actsAsDefault === null) {
|
|
118
|
+
throw new Error(
|
|
119
|
+
'createAuthConfig requires `withoutCustomer: "default" | "none"`: whether a signed-in user with no customer of their own acts as the site\'s default customer (atlas#212)'
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
const siteCallbacks = resolveCallbacks(options);
|
|
123
|
+
return {
|
|
124
|
+
providers: [
|
|
125
|
+
Credentials({
|
|
126
|
+
name: "Credentials",
|
|
127
|
+
// Only what a person types. Anything else a post carries (an id, a verified flag, a
|
|
128
|
+
// token) is never read: the user comes from Joomla's answer alone (atlas#97, model
|
|
129
|
+
// PostedFieldsNeverChooseTheUser).
|
|
130
|
+
credentials: {
|
|
131
|
+
username: { label: "Username", type: "text" },
|
|
132
|
+
password: { label: "Password", type: "password" },
|
|
133
|
+
siteId: { label: "Site ID", type: "text" }
|
|
134
|
+
},
|
|
135
|
+
async authorize(credentials) {
|
|
136
|
+
const posted = credentials ?? {};
|
|
137
|
+
const username = typeof posted["username"] === "string" ? posted["username"] : "";
|
|
138
|
+
const password = typeof posted["password"] === "string" ? posted["password"] : "";
|
|
139
|
+
const postedSite = typeof posted["siteId"] === "string" ? posted["siteId"] : void 0;
|
|
140
|
+
const crossSite = getCrossSite();
|
|
141
|
+
const targetSiteId = signInTarget(crossSite, postedSite);
|
|
142
|
+
if (!asksJoomla(username, password)) return null;
|
|
143
|
+
const answer = await siteCallbacks.verifyPassword(username, password, targetSiteId);
|
|
144
|
+
const answerId = typeof answer.id === "number" ? answer.id : 0;
|
|
145
|
+
const answerToken = typeof answer.token === "string" ? answer.token : "";
|
|
146
|
+
const outcome = signInOutcomeOf(
|
|
147
|
+
true,
|
|
148
|
+
answerId,
|
|
149
|
+
answer.isVerified === true,
|
|
150
|
+
answerToken !== "",
|
|
151
|
+
crossSite
|
|
152
|
+
);
|
|
153
|
+
if (outcome !== "signed-in") return null;
|
|
154
|
+
return {
|
|
155
|
+
id: String(answerId),
|
|
156
|
+
isVerified: true,
|
|
157
|
+
username: typeof answer.username === "string" ? answer.username : username,
|
|
158
|
+
token: answerToken,
|
|
159
|
+
targetSiteId
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
})
|
|
163
|
+
],
|
|
164
|
+
callbacks: {
|
|
165
|
+
async signIn() {
|
|
166
|
+
return true;
|
|
167
|
+
},
|
|
168
|
+
async redirect({ baseUrl }) {
|
|
169
|
+
return baseUrl;
|
|
170
|
+
},
|
|
171
|
+
async session({ session, token }) {
|
|
172
|
+
const baseUser = baseUserOf(token);
|
|
173
|
+
const targetSiteId = token["targetSiteId"];
|
|
174
|
+
const buildSession = (userOverrides = {}) => {
|
|
175
|
+
const fields = {
|
|
176
|
+
user: { ...session.user, ...baseUser, ...userOverrides, targetSiteId },
|
|
177
|
+
targetSiteId
|
|
178
|
+
};
|
|
179
|
+
const added = Object.fromEntries(sessionKeys().map((key) => [key, fields[key]]));
|
|
180
|
+
return { ...session, ...added };
|
|
181
|
+
};
|
|
182
|
+
try {
|
|
183
|
+
const userProfile = await siteCallbacks.getUserProfile(baseUser.id);
|
|
184
|
+
if (!userProfile) return buildSession();
|
|
185
|
+
const customerId = sessionCustomerOf(
|
|
186
|
+
addressIdOf(userProfile.customerId),
|
|
187
|
+
addressIdOf(defaultCustomerId),
|
|
188
|
+
actsAsDefault
|
|
189
|
+
);
|
|
190
|
+
const cartHdrUid = await lookupCartHdr(
|
|
191
|
+
siteCallbacks,
|
|
192
|
+
userProfile,
|
|
193
|
+
customerId,
|
|
194
|
+
defaultContactId
|
|
195
|
+
);
|
|
196
|
+
return buildSession({
|
|
197
|
+
name: userProfile.name ?? session.user?.name,
|
|
198
|
+
email: userProfile.email ?? session.user?.email,
|
|
199
|
+
customerId: customerId ?? void 0,
|
|
200
|
+
contactId: userProfile.contactId,
|
|
201
|
+
cartHdrUid
|
|
202
|
+
});
|
|
203
|
+
} catch {
|
|
204
|
+
return buildSession();
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
async jwt({ token, user, trigger }) {
|
|
208
|
+
if (!user) {
|
|
209
|
+
if (trigger === "update") return token;
|
|
210
|
+
try {
|
|
211
|
+
const profile = await siteCallbacks.getUserProfile(baseUserOf(token).id);
|
|
212
|
+
if (!sessionKept(profile !== null, profile?.blocked === true)) return null;
|
|
213
|
+
} catch {
|
|
214
|
+
return token;
|
|
215
|
+
}
|
|
216
|
+
return token;
|
|
217
|
+
}
|
|
218
|
+
const typedUser = user;
|
|
219
|
+
return {
|
|
220
|
+
...token,
|
|
221
|
+
id: typedUser.id,
|
|
222
|
+
isVerified: typedUser.isVerified,
|
|
223
|
+
username: typedUser.username,
|
|
224
|
+
token: typedUser.token,
|
|
225
|
+
targetSiteId: typedUser.targetSiteId
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
secret,
|
|
230
|
+
debug,
|
|
231
|
+
// Auth.js's default logger prints an error's cause and its debug metadata: on an expired
|
|
232
|
+
// session that cause is the decrypted JWT, the user's Augur token included. Log the error's
|
|
233
|
+
// type and fixed text only (model AugurServerSecurity, "every log line").
|
|
234
|
+
logger: authLogger,
|
|
235
|
+
session: {
|
|
236
|
+
strategy: "jwt",
|
|
237
|
+
maxAge
|
|
238
|
+
},
|
|
239
|
+
trustHost: true
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
var authLogger = {
|
|
243
|
+
error(error) {
|
|
244
|
+
console.error(errorLogLine("[auth]", error));
|
|
245
|
+
},
|
|
246
|
+
warn(code) {
|
|
247
|
+
console.warn(logLineOf("[auth] warning", code));
|
|
248
|
+
},
|
|
249
|
+
debug(message) {
|
|
250
|
+
console.debug(logLineOf("[auth] debug", message));
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
export {
|
|
255
|
+
createAuthConfig
|
|
256
|
+
};
|
|
257
|
+
//# sourceMappingURL=chunk-M35O5JDZ.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 { addressIdOf, errorLogLine, logLineOf } from \"@simpleapps-com/augur-utils\";\nimport type { NextAuthConfig } from \"next-auth\";\nimport Credentials from \"next-auth/providers/credentials\";\nimport type { AddressId } from \"./address-id\";\nimport { cartLookupRuns, signInTarget } from \"./rules\";\nimport {\n actsAsDefaultOf,\n asksJoomla,\n callbackSourceOf,\n claimVerified,\n configRefused,\n lookupNumberOf,\n sessionCustomerOf,\n sessionKept,\n sessionKeys,\n signInOutcomeOf,\n} from \"./session-rules\";\nimport { getCrossSite } from \"./sdk-client-store\";\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 /** Target site ID for cross-site auth sessions (augur_info + body siteId). */\n targetSiteId?: string;\n /**\n * True when Joomla has blocked the account. A profile that says so ends the session on its\n * next read (owner 2026-11-16: a blocked account \"can't have a session\"). A site's own\n * `getUserProfile` SHOULD set it from the users doc's `block`.\n */\n blocked?: boolean;\n}\n\n/**\n * Joomla's answer to `joomla.users.verifyPassword`: the user's `id` (0 when the password did not\n * match), `isVerified`, and a user `token` (null without a match). augur answers `id` and `token`\n * only when `isVerified` (VerifyPassword.php).\n */\nexport interface PasswordAnswer {\n id: number;\n isVerified: boolean;\n username?: string;\n token?: string | null;\n}\n\n/**\n * Session shape returned by all Augur sites. It reaches the browser (`/api/auth/session`,\n * `useSession`), so it never carries the user's Augur token: that stays in the encrypted JWT\n * ({@link AugurJWT}), where server code reads it (atlas#212).\n */\nexport interface AugurSession {\n user: AugurUser;\n targetSiteId?: string;\n expires: string;\n}\n\n/**\n * What a site does for a signed-in user whose profile has no usable P21 customer (atlas#212):\n * `\"default\"` acts as the site's `defaultCustomerId` (a retail site, or the legacy rule for an\n * unapproved account); `\"none\"` gives them no customer and no cart (a B2B portal, where the\n * default customer's orders are not theirs). Required: there is no safe default either way.\n */\nexport type WithoutCustomer = \"default\" | \"none\";\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 /**\n * Look up or create a cart header for the authenticated user. `customerId` is always a usable\n * P21 customer id (resolved by augur-utils `resolveAddressId`): without one no lookup is made\n * (atlas#95).\n */\n cartHdrLookup?: (\n userId: string | number,\n token: string,\n contactId: string | number,\n customerId: number,\n ) => Promise<{ cartHdrUid?: number } | null>;\n /**\n * Check a username and password with Joomla, on the server (atlas#97). `siteId` is passed only\n * on the cross-site (augur_info) site: the site whose password is checked. The package's own\n * calls `joomla.users.verifyPassword`.\n */\n verifyPassword: (username: string, password: string, siteId?: string) => Promise<PasswordAnswer>;\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 /** The site's default customer, used for a signed-in user only with `withoutCustomer: \"default\"`. */\n defaultCustomerId?: string | number;\n /** A signed-in user with no usable customer of their own: see {@link WithoutCustomer}. */\n withoutCustomer: WithoutCustomer;\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 // Joomla holds it as text; \"\" and \"0\" are no customer, so none reaches the session (atlas#95).\n customerId: addressIdOf(data[\"customerId\"] as string | number | undefined) ?? undefined,\n contactId: data[\"contactId\"] as string | number | undefined,\n // Joomla's `block` is 1 for a blocked account (the session then ends, sessionKept).\n blocked: data[\"block\"] === 1,\n };\n },\n async verifyPassword(\n username: string,\n password: string,\n siteId?: string,\n ): Promise<PasswordAnswer> {\n const result = await augurClient.joomla.users.verifyPassword.create(\n siteId === undefined ? { username, password } : { username, password, siteId },\n );\n return result.data;\n },\n async cartHdrLookup(\n userId: string | number,\n _token: string,\n contactId: string | number,\n customerId: number,\n ): Promise<{ cartHdrUid?: number } | null> {\n const user = Number(userId);\n const contact = Number(contactId);\n const result = await augurClient.commerce.cartHdr.lookup.get({\n userId: lookupNumberOf(!Number.isNaN(user), user),\n // Always a usable id: lookupCartHdr looks up no cart without one (atlas#95).\n customerId,\n contactId: lookupNumberOf(!Number.isNaN(contact), contact),\n });\n // The SDK returns `false` when no cart header exists.\n return result.data || null;\n },\n };\n}\n\n/**\n * Resolve final callbacks: the site's callback when given, else the package's SDK call\n * (callbackSourceOf, proved).\n */\nfunction resolveCallbacks(options: CreateAuthConfigOptions): AugurAuthCallbacks {\n const site: Partial<AugurAuthCallbacks> = options.callbacks ?? {};\n const client = options.augurClient;\n\n if (\n configRefused(\n client !== undefined,\n site.getUserProfile !== undefined,\n site.verifyPassword !== undefined,\n )\n ) {\n throw new Error(\n \"createAuthConfig requires either `augurClient` or both `callbacks.getUserProfile` and `callbacks.verifyPassword`\",\n );\n }\n\n const internal: Partial<AugurAuthCallbacks> =\n client === undefined ? {} : buildInternalCallbacks(client);\n const pick = <K extends keyof AugurAuthCallbacks>(key: K): AugurAuthCallbacks[K] =>\n (callbackSourceOf(site[key] !== undefined, internal[key] !== undefined) === \"override\"\n ? site[key]\n : internal[key]) as AugurAuthCallbacks[K];\n // configRefused held, so the profile and verify sources are never \"none\".\n return {\n getUserProfile: pick(\"getUserProfile\"),\n cartHdrLookup: pick(\"cartHdrLookup\"),\n verifyPassword: pick(\"verifyPassword\"),\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 * A sign-in posts the username and password; the server checks them with Joomla\n * (`joomla.users.verifyPassword`) and the user comes from that answer alone (atlas#97).\n *\n * Cross-site auth (augur-support pattern) is on exactly for the augur_info site\n * (owner 2026-11-16): an augur_info client's site also posts `siteId`, the site whose\n * password Joomla checks; the session stores that target and the user's token for it.\n * On any other site `siteId` is ignored and queryAction never reads the session (atlas#105).\n *\n * @example\n * ```ts\n * export const { handlers, signIn, signOut, auth } = NextAuth(\n * createAuthConfig({ augurClient, withoutCustomer: \"none\" }),\n * );\n * await signIn(\"credentials\", { username, password });\n * // augur_info site only:\n * await signIn(\"credentials\", { username, password, siteId: targetSiteId });\n * ```\n */\nasync function lookupCartHdr(\n siteCallbacks: AugurAuthCallbacks,\n profile: AugurUser,\n customerId: AddressId | null,\n defaultContactId?: string | number,\n): Promise<number | undefined> {\n // The session's customer (sessionCustomerOf): with none there is no cart to look up, never\n // one for customer 0 (atlas#95) or the default's on a \"none\" site (atlas#212).\n const lookup = siteCallbacks.cartHdrLookup;\n if (!cartLookupRuns(lookup !== undefined, !!profile.id, customerId)) {\n return undefined;\n }\n // Both set: cartLookupRuns refused the lookup above without either.\n const cartHdr = await (lookup as NonNullable<typeof lookup>)(\n profile.id,\n \"\",\n profile.contactId ?? defaultContactId ?? \"\",\n customerId as AddressId,\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: claimVerified(\n typeof token[\"isVerified\"] === \"boolean\",\n token[\"isVerified\"] === true,\n ),\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 // The site's choice is required (model NoSilentChoice): refused here for JavaScript callers\n // the type does not reach.\n const actsAsDefault = actsAsDefaultOf(options.withoutCustomer);\n if (actsAsDefault === null) {\n throw new Error(\n 'createAuthConfig requires `withoutCustomer: \"default\" | \"none\"`: whether a signed-in user with no customer of their own acts as the site\\'s default customer (atlas#212)',\n );\n }\n\n const siteCallbacks = resolveCallbacks(options);\n\n return {\n providers: [\n Credentials({\n name: \"Credentials\",\n // Only what a person types. Anything else a post carries (an id, a verified flag, a\n // token) is never read: the user comes from Joomla's answer alone (atlas#97, model\n // PostedFieldsNeverChooseTheUser).\n credentials: {\n username: { label: \"Username\", type: \"text\" },\n password: { label: \"Password\", type: \"password\" },\n siteId: { label: \"Site ID\", type: \"text\" },\n },\n async authorize(credentials) {\n const posted: Partial<Record<string, unknown>> = credentials ?? {};\n const username = typeof posted[\"username\"] === \"string\" ? posted[\"username\"] : \"\";\n const password = typeof posted[\"password\"] === \"string\" ? posted[\"password\"] : \"\";\n const postedSite = typeof posted[\"siteId\"] === \"string\" ? posted[\"siteId\"] : undefined;\n const crossSite = getCrossSite();\n // The target is read only on the augur_info site (rules.signInTarget, atlas#105).\n const targetSiteId = signInTarget(crossSite, postedSite);\n\n if (!asksJoomla(username, password)) return null;\n // Joomla checks the password on the server; its errors propagate (an outage is never\n // reported as a wrong password).\n const answer = await siteCallbacks.verifyPassword(username, password, targetSiteId);\n const answerId = typeof answer.id === \"number\" ? answer.id : 0;\n const answerToken = typeof answer.token === \"string\" ? answer.token : \"\";\n const outcome = signInOutcomeOf(\n true,\n answerId,\n answer.isVerified === true,\n answerToken !== \"\",\n crossSite,\n );\n if (outcome !== \"signed-in\") return null;\n\n return {\n id: String(answerId),\n isVerified: true,\n username: typeof answer.username === \"string\" ? answer.username : username,\n token: answerToken,\n targetSiteId,\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 // Exactly the keys the proved sessionKeys() names are added: the user's fields and the\n // target, never the Augur token, which stays in the JWT (model SessionHasNoBearer,\n // atlas#212).\n const buildSession = (userOverrides = {}) => {\n const fields: Record<string, unknown> = {\n user: { ...session.user, ...baseUser, ...userOverrides, targetSiteId },\n targetSiteId,\n };\n const added = Object.fromEntries(sessionKeys().map((key) => [key, fields[key]]));\n return { ...session, ...added } as typeof session;\n };\n\n try {\n const userProfile = await siteCallbacks.getUserProfile(baseUser.id);\n if (!userProfile) return buildSession();\n\n // The user's own usable customer, else the default only on a \"default\" site; never\n // \"\" or \"0\" (atlas#95, atlas#212). The cart is looked up for the same one.\n const customerId = sessionCustomerOf(\n addressIdOf(userProfile.customerId),\n addressIdOf(defaultCustomerId),\n actsAsDefault,\n );\n const cartHdrUid = await lookupCartHdr(\n siteCallbacks,\n userProfile,\n customerId,\n defaultContactId,\n );\n\n return buildSession({\n name: userProfile.name ?? session.user?.name,\n email: userProfile.email ?? session.user?.email,\n customerId: customerId ?? undefined,\n contactId: userProfile.contactId,\n cartHdrUid,\n });\n } catch {\n return buildSession();\n }\n },\n async jwt({ token, user, trigger }) {\n if (!user) {\n // A browser's `update()` never changes the JWT (model UpdateNeverChangesTheJwt).\n if (trigger === \"update\") return token;\n // Every session read re-reads the account: a blocked or deleted one has no session\n // (owner 2026-11-16; model SessionKept). Auth.js clears the cookie on null. A failed\n // read (the API down) keeps the session; the next good read decides.\n try {\n const profile = await siteCallbacks.getUserProfile(baseUserOf(token).id);\n if (!sessionKept(profile !== null, profile?.blocked === true)) return null;\n } catch {\n return token;\n }\n return token;\n }\n // Sign-in: the user authorize built from Joomla's answer.\n const typedUser = user as {\n id: string;\n isVerified: boolean;\n username: string;\n token?: string;\n targetSiteId?: string;\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 },\n secret,\n debug,\n // Auth.js's default logger prints an error's cause and its debug metadata: on an expired\n // session that cause is the decrypted JWT, the user's Augur token included. Log the error's\n // type and fixed text only (model AugurServerSecurity, \"every log line\").\n logger: authLogger,\n session: {\n strategy: \"jwt\",\n maxAge,\n },\n trustHost: true,\n };\n}\n\n/** Auth.js's logger, writing fixed text and an error's type only: never a cause or metadata. */\nconst authLogger: NonNullable<NextAuthConfig[\"logger\"]> = {\n error(error) {\n console.error(errorLogLine(\"[auth]\", error));\n },\n warn(code) {\n console.warn(logLineOf(\"[auth] warning\", code));\n },\n debug(message) {\n console.debug(logLineOf(\"[auth] debug\", message));\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA,SAAS,aAAa,cAAc,iBAAiB;AAErD,OAAO,iBAAiB;AA2HxB,SAAS,uBAAuB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AET,cAAI,YAAY,SAAU,QAAO;AAIjC,cAAI;AACF,kBAAM,UAAU,MAAM,cAAc,eAAe,WAAW,KAAK,EAAE,EAAE;AACvE,gBAAI,CAAC,YAAY,YAAY,MAAM,SAAS,YAAY,IAAI,EAAG,QAAO;AAAA,UACxE,QAAQ;AACN,mBAAO;AAAA,UACT;AACA,iBAAO;AAAA,QACT;AAEA,cAAM,YAAY;AAOlB,eAAO;AAAA,UACL,GAAG;AAAA,UACH,IAAI,UAAU;AAAA,UACd,YAAY,UAAU;AAAA,UACtB,UAAU,UAAU;AAAA,UACpB,OAAO,UAAU;AAAA,UACjB,cAAc,UAAU;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA,IAIA,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,UAAU;AAAA,MACV;AAAA,IACF;AAAA,IACA,WAAW;AAAA,EACb;AACF;AAGA,IAAM,aAAoD;AAAA,EACxD,MAAM,OAAO;AACX,YAAQ,MAAM,aAAa,UAAU,KAAK,CAAC;AAAA,EAC7C;AAAA,EACA,KAAK,MAAM;AACT,YAAQ,KAAK,UAAU,kBAAkB,IAAI,CAAC;AAAA,EAChD;AAAA,EACA,MAAM,SAAS;AACb,YAAQ,MAAM,UAAU,gBAAgB,OAAO,CAAC;AAAA,EAClD;AACF;","names":[]}
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
dataChainOf,
|
|
3
|
+
inRegistry,
|
|
4
|
+
registryRefuses,
|
|
5
|
+
segmentReachable
|
|
6
|
+
} from "./chunk-ILXNFJVM.js";
|
|
1
7
|
import {
|
|
2
8
|
clientFor,
|
|
3
9
|
clientIdSiteIdOf,
|
|
@@ -14,7 +20,7 @@ import {
|
|
|
14
20
|
scopedPrefix,
|
|
15
21
|
sessionCookieName,
|
|
16
22
|
usesCache
|
|
17
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-5DBFTSWY.js";
|
|
18
24
|
|
|
19
25
|
// src/query-action.ts
|
|
20
26
|
import {
|
|
@@ -117,15 +123,41 @@ function boundClient(client, options) {
|
|
|
117
123
|
}
|
|
118
124
|
return client.withRequest(options);
|
|
119
125
|
}
|
|
126
|
+
function refuseUnregistered(client, methodPath, segments) {
|
|
127
|
+
const has = Object(client).hasEndpoint;
|
|
128
|
+
const hasRegistry = typeof has === "function";
|
|
129
|
+
const known = (id) => hasRegistry && has.call(client, id) === true;
|
|
130
|
+
const chain = dataChainOf(segments[1] ?? "");
|
|
131
|
+
const viaData = chain !== "" && known([segments[0], chain, ...segments.slice(2)].join("."));
|
|
132
|
+
if (registryRefuses(hasRegistry, inRegistry(known(methodPath), viaData))) {
|
|
133
|
+
throw new Error(`"${methodPath}" is not an API route`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
120
136
|
function resolveMethod(client, methodPath) {
|
|
121
137
|
const segments = methodPath.split(".");
|
|
138
|
+
refuseUnregistered(client, methodPath, segments);
|
|
122
139
|
let current = client;
|
|
123
|
-
for (
|
|
140
|
+
for (let i = 0; i < segments.length; i++) {
|
|
141
|
+
const segment = segments[i];
|
|
124
142
|
if (current == null || typeof current !== "object" && typeof current !== "function") {
|
|
125
143
|
throw new Error(
|
|
126
144
|
`Cannot resolve "${methodPath}": "${segment}" is not accessible on ${typeof current}`
|
|
127
145
|
);
|
|
128
146
|
}
|
|
147
|
+
const own = Object.prototype.hasOwnProperty.call(current, segment);
|
|
148
|
+
let accessor = false;
|
|
149
|
+
let proto = own ? null : Object.getPrototypeOf(current);
|
|
150
|
+
while (proto !== null) {
|
|
151
|
+
const found = Object.getOwnPropertyDescriptor(proto, segment);
|
|
152
|
+
if (found !== void 0) {
|
|
153
|
+
accessor = found.get !== void 0;
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
proto = Object.getPrototypeOf(proto);
|
|
157
|
+
}
|
|
158
|
+
if (!segmentReachable(i === 0, own, accessor)) {
|
|
159
|
+
throw new Error(`"${methodPath}" is not an API route: "${segment}" cannot be called`);
|
|
160
|
+
}
|
|
129
161
|
current = current[segment];
|
|
130
162
|
}
|
|
131
163
|
if (typeof current !== "function") {
|
|
@@ -187,4 +219,4 @@ export {
|
|
|
187
219
|
queryActionRawWith,
|
|
188
220
|
resetSessionImports
|
|
189
221
|
};
|
|
190
|
-
//# sourceMappingURL=chunk-
|
|
222
|
+
//# sourceMappingURL=chunk-Y54RGILF.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 getCrossSite,\n getOrCreateScopedClient,\n getScopedCacheWrapper,\n parseMethodPath,\n type SessionCredentials,\n type ApprovedMethodPath,\n type SdkCallWrapper,\n type ScopedCacheWrapper,\n} from \"./sdk-client-store\";\nimport {\n isReadMethod,\n stripEdgeCacheForNoCachePaths,\n unwrapBaseResponse,\n type MethodArgs,\n type MethodData,\n type MethodPath,\n} from \"@simpleapps-com/augur-core\";\nimport {\n isSiteId,\n type AugurAPI,\n type BaseResponse,\n type CallOptions,\n} from \"@simpleapps-com/augur-api\";\nimport {\n clientFor,\n clientIdSiteIdOf,\n mintedCredentials,\n readsSession,\n resolutionOf,\n scopedPrefix,\n sessionCookieName,\n usesCache,\n} from \"./rules\";\nimport { dataChainOf, inRegistry, registryRefuses, segmentReachable } from \"./session-rules\";\n\n/** Auth.js v5's HTTPS session cookie; sessionCookieName (rules.ts) picks it or the plain one. */\nconst SECURE_COOKIE = \"__Secure-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 // The proved rule (rules.ts, AugurServer.SessionCookieName): the HTTPS cookie when present,\n // else the plain one; its name is the salt\n const name = sessionCookieName(Boolean(secureCookie));\n const cookie = secureCookie ?? cookieStore.get(name);\n if (!cookie?.value) return null;\n\n return _decode!({ token: cookie.value, secret, salt: name });\n}\n\n/**\n * Extract the siteId portion of an Augur bearer token's `client_id` claim.\n * Bearer tokens are JWTs whose payload contains `client_id: \"<numeric>|<siteId>\"`.\n * Returns null on any parse failure or unexpected shape.\n *\n * Uses jose.decodeJwt (no signature verification) — we trust the bearer\n * because the *outer* Auth.js cookie's signature was just verified upstream,\n * so the bearer's contents are trusted as session-issued. This check guards\n * against internal inconsistency between the session's `targetSiteId` and the\n * bearer's scope, not against a forged bearer (the auth provider's signature\n * does that).\n */\nfunction parseBearerClientSiteId(bearer: string): string | null {\n try {\n const payload = _decodeJwt!(bearer);\n const clientId = payload[\"client_id\"];\n if (typeof clientId !== \"string\") return null;\n return clientIdSiteIdOf(clientId);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve session credentials from the Auth.js JWT cookie.\n *\n * Trust-boundary mint point: this is the only function in the package that\n * produces {@link SessionCredentials} values. Bytes from a cookie become\n * typed, paired credentials here and only here. No other production code\n * constructs the branded pair, so a `SessionCredentials` that came through\n * this mint is JWT-validated and internally consistent. The brand is not\n * enforced by the compiler: an `as SessionCredentials` cast compiles (tests\n * do it), so audit casts (see \"Brand strength\" below).\n *\n * Returns null when:\n * - the site is not the cross-site (augur_info) site (its client's own siteId,\n * atlas#105, owner 2026-11-16): then nothing is imported and no\n * cookie is read, so pages using queryAction can render statically\n * - no AUTH_SECRET is configured\n * - next-auth/jwt, next/headers, or jose cannot be loaded\n * - no session cookie is present\n * - the JWT decode fails or returns null\n * - the decoded payload is missing `targetSiteId` or `token`, or either is\n * not a non-empty string (refuse to mint partial credentials)\n * - `targetSiteId` fails augur-api's `isSiteId` (`[a-z0-9_-]+`): siteIds are\n * lowercase by convention, and the scoped-client key's injectivity proof\n * (`scoped-client-key.ts`) needs a NUL-free siteId\n * - the bearer token's `client_id` siteId portion does not match\n * `targetSiteId` (defense-in-depth: refuses internally inconsistent sessions\n * before they reach the augur-api authority check)\n *\n * ## Verified preconditions for `result = some c`\n *\n * AUTH_SECRET configured\n * next-auth/jwt, next/headers, jose all loadable\n * session cookie present and decodable with the secret\n * typeof jwt.targetSiteId === \"string\" ∧ isSiteId(jwt.targetSiteId) // implies non-empty\n * typeof jwt.token === \"string\" ∧ jwt.token.length > 0\n * bearerClientSiteId(jwt.token) = some jwt.targetSiteId\n *\n * Lean equivalent: each clause becomes a `requires` on the function;\n * `result = none` is the disjunction of any failing.\n * F* equivalent: refinement on the option payload covering the\n * conjunction of these clauses.\n *\n * The bearer cross-check (`bearerClientSiteId(jwt.token) = some jwt.targetSiteId`)\n * is the substantive runtime invariant: it refuses sessions where the bearer's\n * encoded `client_id` siteId disagrees with the session's targetSiteId,\n * catching internal-inconsistency bugs before the call reaches augur-api.\n *\n * ## By construction (not independently verified)\n *\n * c.siteId === jwt.targetSiteId (assigned, not checked)\n * c.token === jwt.token (assigned, not checked)\n *\n * ## Brand strength\n *\n * `SessionCredentials` is a TS-level brand: there is no runtime tag on the\n * value. `value as SessionCredentials` casts compile, so the brand is a\n * code-review signal (audit `as SessionCredentials` usages — there should be\n * exactly one, in this function), not a hard type-system gate.\n */\nasync function getSessionCredentials(): Promise<SessionCredentials | null> {\n const secret = getAuthSecret();\n // Only an opted-in site with a secret looks for a session (rules.readsSession, atlas#105):\n // every other site returns here, before next/headers is imported or cookies() read, so its\n // pages can render statically.\n if (!readsSession(getCrossSite(), Boolean(secret))) return null;\n if (!(await ensureImports())) return null;\n\n try {\n // readsSession held, so the secret is present (Boolean(secret) above).\n const decoded = await decodeSessionJwt(secret as string);\n if (!decoded) return null;\n\n const targetSiteId = decoded[\"targetSiteId\"];\n const token = decoded[\"token\"];\n\n if (typeof targetSiteId !== \"string\" || typeof token !== \"string\") return null;\n\n // An empty or undecodable token has no client_id siteId (\"\").\n const bearerSiteId = parseBearerClientSiteId(token) ?? \"\";\n const mint = mintedCredentials(isSiteId(targetSiteId), targetSiteId, token, bearerSiteId);\n if (mint.kind === \"refused\") return null;\n\n return { siteId: mint.siteId, token: mint.token } as unknown as SessionCredentials;\n } catch {\n // Not in a request context (build time, tests), or decode failed\n }\n\n return null;\n}\n\n/**\n * Discriminated result of client resolution.\n *\n * Encodes two structural invariants at the type level:\n *\n * 1. session credentials exist iff this is the scoped path\n * (only `kind: \"scoped\"` carries `credentials`)\n * 2. a usable client exists iff this is NOT the uninit path\n * (`kind: \"scoped\" | \"global\"` always carry `client: object`)\n *\n * The `client: object` constraint replaces the previous `client: unknown` +\n * runtime null check. Anything narrowed to `kind: \"scoped\"` or `kind: \"global\"`\n * is guaranteed by the type system to have a non-null, traversable client —\n * downstream code that walks the SDK namespace path cannot accidentally\n * dereference null. The runtime check moves into `resolveClient` itself, where\n * `kind: \"uninit\"` is constructed when neither a scoped nor a global client is\n * available.\n *\n * Downstream code that wants to derive a cache prefix can only do so on the\n * scoped variant, and only from the credentials carried by that variant —\n * there is no way to construct a cache prefix from a different source without\n * crossing into the type.\n */\ntype ClientResolution =\n | { kind: \"scoped\"; client: object; credentials: SessionCredentials }\n | { kind: \"global\"; client: object }\n | { kind: \"uninit\" };\n\n/**\n * Resolve the SDK client for this request.\n *\n * - If the session JWT validates and a scoped client can be minted, returns\n * the scoped variant carrying the {@link SessionCredentials} that produced\n * the client. The cache prefix is derived at the use site from\n * `credentials.siteId`, structurally guaranteeing it matches the credentials\n * under which the SDK call is made.\n * - Otherwise returns the global variant. No credentials, no cache prefix.\n *\n * The previous return shape `{ client, cachePrefix: string | null }` made\n * \"cachePrefix exists iff scoped\" a runtime invariant; the tagged union\n * promotes it to a type-level one.\n */\nasync function resolveClient(): Promise<ClientResolution> {\n const creds = await getSessionCredentials();\n const scoped = creds ? getOrCreateScopedClient(creds) : null;\n const globalClient = getSdkClientOrNull();\n const kind = resolutionOf(creds !== null, isObject(scoped), isObject(globalClient));\n if (kind === \"scoped\") return { kind, client: scoped as object, credentials: creds! };\n if (kind === \"global\") return { kind, client: globalClient as object };\n return { kind };\n}\n\n/** A usable client: a non-null object. */\nfunction isObject(value: unknown): boolean {\n return value !== null && typeof value === \"object\";\n}\n\n/** A client offering call options (`AugurAPI.withRequest`, atlas#106). */\ntype BoundableClient = { withRequest: (options: CallOptions) => object };\n\nfunction canBeBounded(client: object): client is BoundableClient {\n return typeof (client as Partial<BoundableClient>).withRequest === \"function\";\n}\n\n/**\n * The client a call runs on (rules.ts `clientFor`, AugurServer.ClientFor): the resolved client\n * with no options; its `withRequest` view with options; and a refusal when it has no\n * `withRequest`, since a call the caller asked to bound must never run unbounded.\n */\nfunction boundClient(client: object, options: CallOptions | undefined): object {\n const choice = clientFor(options !== undefined, canBeBounded(client));\n if (choice === \"client\") return client;\n if (choice === \"refuse\") {\n throw new Error(\n \"queryActionWith: the SDK client has no withRequest; call options need a \" +\n \"@simpleapps-com/augur-api release that has AugurAPI.withRequest.\",\n );\n }\n return (client as BoundableClient).withRequest(options!);\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 refuseUnregistered(client: unknown, methodPath: string, segments: string[]): void {\n // The site's own SDK registry (`AugurAPI.hasEndpoint`, atlas#104): only a real route runs. A\n // data proxy's chain (`items.invMastData.list`) is checked as its route (`items.invMast.list`).\n // A client without it (an SDK before it, a test double) leaves the path to the walk below\n // (model AugurServerSecurity.RouteKnown).\n // Object() reads a property of any value, a null or a primitive client included (none has one)\n const has: unknown = (Object(client) as { hasEndpoint?: unknown }).hasEndpoint;\n const hasRegistry = typeof has === \"function\";\n const known = (id: string): boolean =>\n hasRegistry && (has as (id: string) => unknown).call(client, id) === true;\n const chain = dataChainOf(segments[1] ?? \"\");\n const viaData = chain !== \"\" && known([segments[0], chain, ...segments.slice(2)].join(\".\"));\n if (registryRefuses(hasRegistry, inRegistry(known(methodPath), viaData))) {\n throw new Error(`\"${methodPath}\" is not an API route`);\n }\n}\n\nfunction resolveMethod(\n client: unknown,\n methodPath: ApprovedMethodPath,\n): (...a: unknown[]) => Promise<unknown> {\n const segments = methodPath.split(\".\");\n refuseUnregistered(client, methodPath, segments);\n\n let current: unknown = client;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]!;\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 // Only API routes: a segment is followed when it is the object's own property, or, first,\n // an accessor (the SDK's services are getters). The client's own methods (`setAuthToken`,\n // `call`, `withRequest`, `constructor`) live on its prototype and are never reached\n // (session-rules `segmentReachable`, model AugurServerSecurity.SegmentReachable).\n const own = Object.prototype.hasOwnProperty.call(current, segment);\n let accessor = false;\n let proto: unknown = own ? null : Object.getPrototypeOf(current);\n while (proto !== null) {\n const found = Object.getOwnPropertyDescriptor(proto, segment);\n if (found !== undefined) {\n accessor = found.get !== undefined;\n break;\n }\n proto = Object.getPrototypeOf(proto);\n }\n if (!segmentReachable(i === 0, own, accessor)) {\n throw new Error(`\"${methodPath}\" is not an API route: \"${segment}\" cannot be called`);\n }\n current = (current as Record<string, unknown>)[segment];\n }\n\n if (typeof current !== \"function\") {\n throw new Error(`\"${methodPath}\" does not resolve to a function (got ${typeof current})`);\n }\n\n return current as (...a: unknown[]) => Promise<unknown>;\n}\n\n/**\n * Bind a scoped cache wrapper to a fixed prefix, producing an `SdkCallWrapper`\n * with the same signature as the global wrapper.\n *\n * On the scoped queryAction path, the cache prefix is derived structurally\n * from the `SessionCredentials` that minted the client (`${credentials.siteId}:`).\n * Capturing that prefix in a closure here lets queryAction's call site treat\n * scoped and global wrappers uniformly — the only thing that differs between\n * them is which prefix gets baked in, and that decision happens in exactly one\n * place per request.\n *\n * Returns null when no scoped wrapper is registered, so the caller falls\n * through to the unwrapped SDK call. The closure preserves the cross-tenant\n * invariant: prefix is captured at bind time from the same credentials value\n * used to mint the scoped client, and cannot be replaced or re-sourced later.\n *\n * ## Property\n *\n * bindScopedPrefix(null, _) = null\n * bindScopedPrefix(w, p)(methodPath, fn, ...args) = w(p, methodPath, fn, ...args)\n *\n * The bound wrapper forwards faithfully — it adds nothing, drops nothing,\n * and reorders nothing. Every effect (cache read, cache write, SDK call)\n * happens inside the underlying scopedWrapper exactly as if queryAction had\n * called it directly with the prefix as the first argument.\n */\nfunction bindScopedPrefix(\n scopedWrapper: ScopedCacheWrapper | null,\n prefix: string,\n): SdkCallWrapper | null {\n if (!scopedWrapper) return null;\n return (methodPath, sdkCall, ...keyArgs) =>\n scopedWrapper(prefix, methodPath, sdkCall, ...keyArgs);\n}\n\n/**\n * The one SDK call behind the two server actions, `queryAction` (the\n * envelope's data) and `queryActionRaw` (the result as returned): routes\n * any SDK method call through the raw SDK client with optional Redis\n * caching. `queryAction` is used internally by `createServerQueryProxy()`\n * to bridge client-side React Query hooks to server-side API calls.\n *\n * For read methods (get, list, lookup, search, suggest), the call is\n * wrapped in the registered cache wrapper (Redis) if one was registered\n * by createServerSite(). Write methods bypass caching.\n *\n * When the request has an active session with targetSiteId + token\n * (from cross-site auth), the call uses a scoped SDK client with those\n * credentials. Redis caching uses targetSiteId as the cache prefix so\n * users managing the same site share cached data.\n *\n * This is the chokepoint: every B2B site without a client-side SDK\n * routes EVERY data access through this one function. The invariants\n * below are load-bearing across every site, every request, every user.\n *\n * ## Preconditions (enforced at runtime via thrown Error)\n *\n * parseMethodPath(methodPath) ≠ null\n * resolveClient().client ≠ null\n *\n * First clause: methodPath is a non-empty string AND — if an allowlist\n * has been registered via `registerAllowedMethodPaths` — methodPath is\n * in the allowlist. Assumes the site opted into surface restriction\n * when narrower-than-augur-api authority is desired; otherwise any\n * non-empty string passes (transparent forwarder default).\n *\n * Second clause: createServerSite() ran during bootstrap OR\n * AUGUR_SITE_ID + AUGUR_JWT env vars are set so the registry can\n * auto-init. Assumes the caller has bootstrapped one of the two paths.\n *\n * Lean equivalent: `requires path : ApprovedMethodPath ∧ client : SDKClient`.\n *\n * ## Cross-tenant cache-prefix invariant (load-bearing)\n *\n * resolution.kind = \"scoped\" ⟹ cachePrefix = `${resolution.credentials.siteId}:`\n *\n * On the scoped path the cache prefix is derived structurally from the\n * same `SessionCredentials` value that minted the scoped client — they\n * cannot be sourced separately. This makes \"siteId from session A\n * combined with token from session B\" or \"siteId X with cache prefix Y\"\n * unrepresentable here. Assumes `getSessionCredentials` performed the\n * bearer/session siteId cross-check at mint time; see the brand-strength\n * caveat on `SessionCredentials`.\n *\n * A regression here would silently leak cached data across tenants.\n * The structural derivation is the only thing standing between the\n * request and that leak — do not reintroduce a separate `cachePrefix`\n * parameter or compute it from anything other than `resolution.credentials`.\n *\n * ### Sibling assumption — bearer is NOT in the cache key\n *\n * The cross-tenant invariant covers cross-SITE leaks. It does NOT cover\n * intra-site cross-USER leaks: the cache key is `(siteId, methodPath, args)`\n * and the bearer token is intentionally absent. Two users with different\n * bearers on the same site share cached data for cacheable namespaces.\n *\n * This is a deliberate design choice. The assumption is:\n *\n * ∀ namespace ∉ NO_CACHE_PATHS, ∀ siteId, ∀ args.\n * augur-api(bearer_A, siteId, args) = augur-api(bearer_B, siteId, args)\n *\n * i.e. for cacheable namespaces, augur-api's response is bearer-independent\n * within a site. augur-api remains the auth authority; `NO_CACHE_PATHS`\n * (commerce.*, payments.*) is the carve-out for namespaces whose responses\n * ARE bearer-coupled. If a future namespace produces bearer-dependent\n * responses (e.g. user-specific permissions affecting query results), it\n * MUST be added to `NO_CACHE_PATHS` or the bearer MUST become part of the\n * cache key — otherwise this assumption silently produces a permission leak.\n *\n * ## No-edge-cache defense-in-depth (load-bearing)\n *\n * ∀ a ∈ safeArgs. methodPath ∈ NO_CACHE_PATHS ⟹ \"edgeCache\" ∉ keys(a)\n *\n * `stripEdgeCacheForNoCachePaths` removes the `edgeCache` key from every\n * first-level object arg when methodPath belongs to a no-cache namespace\n * (currently `commerce.*`, `payments.*`). The augur-api SDK transforms\n * `edgeCache` into a Cloudflare `cacheSiteId{N}` query param; removing\n * it here guarantees no CDN edge-caching of identity-bound responses\n * even if a caller passed one explicitly or a legacy factory injected\n * one. Assumes `NO_CACHE_PATHS` enumerates every namespace whose\n * responses must not cross identity boundaries.\n *\n * ## Postcondition — the SDK's result as returned\n *\n * result = raw (the SDK's result, from the call or the raw cache)\n *\n * Assumes upstream cache wrappers do NOT themselves unwrap — they\n * return whatever the SDK returned (the raw key space, #98), so\n * `queryAction` unwraps exactly once and `queryActionRaw` never does\n * (model: AugurServer.QueryResult).\n *\n * ## Effects\n *\n * @mutates Redis (write-through on read methods when a wrapper is registered)\n * @io augur-api SDK (network request)\n * @throws Error when the allowlist gate fails or no client is initialised\n */\nasync function callSdk(\n methodPath: string,\n args: unknown[],\n options?: CallOptions,\n): 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 // The options bound the call through the client's view; they are never SDK arguments and\n // never part of the cache key, which stays `safeArgs` (AugurServer.OptionsNeverInTheKey)\n const resolvedMethod = resolveMethod(boundClient(resolution.client, options), approvedPath);\n const leafName = approvedPath.split(\".\").pop()!;\n // Defense in depth: strip `edgeCache` from no-cache paths before the SDK\n // sees it. The augur-api SDK transforms `edgeCache` into a Cloudflare\n // `cacheSiteId{N}` query param; removing it here guarantees no CDN edge\n // caching of identity-bound responses even if a caller explicitly passed\n // one. Also keeps cache keys consistent with what is actually sent.\n const safeArgs = stripEdgeCacheForNoCachePaths(approvedPath, args);\n\n // Pick the wrapper for this resolution's prefix policy. On the scoped path,\n // the prefix is structurally derived from `credentials.siteId` and bound into\n // a closure here — bindScopedPrefix is the only call site that builds it,\n // and the prefix cannot be re-sourced after binding. On the global path, the\n // prefix is closed over by the SdkCallWrapper that createServerSite registered.\n // Both paths now produce a uniform `SdkCallWrapper | null`, so the caching\n // and uncached branches collapse into a single shape below.\n const wrapper: SdkCallWrapper | null =\n resolution.kind === \"scoped\"\n ? bindScopedPrefix(getScopedCacheWrapper(), scopedPrefix(resolution.credentials.siteId))\n : getSdkCallWrapper();\n\n if (usesCache(wrapper !== null, isReadMethod(leafName))) {\n return wrapper!(approvedPath, () => resolvedMethod(...safeArgs), ...safeArgs);\n }\n return resolvedMethod(...safeArgs);\n}\n\n/**\n * The SDK call `callSdk` makes (everything above), answered as its envelope's data.\n *\n * ## Postcondition — BaseResponse pass-through (exactly-once unwrap)\n *\n * result = unwrapBaseResponse(raw)\n * = raw.data when raw is { data, status, message }\n * = raw otherwise\n *\n * Consumers receive `T` directly when the SDK returns\n * `{ data: T, status, message }`, and the original value otherwise.\n * Double-unwrap (caller + queryAction) would silently strip a layer of\n * legitimate `{data, status, message}` user data when that shape happens\n * to round-trip through the API. The envelope's paging (`total`,\n * `totalResults`, `count`) is not in `data`: read it with `queryActionRaw`.\n *\n * ## Typed by path (atlas#103)\n *\n * The path is one of the SDK's method paths, the arguments that method's own, the result the\n * envelope's data (model AugurQueryTypes: `IsTypedPath`, `TypedArgs`, `TypedResult`), so an\n * unknown path or arguments that no longer match an upgraded SDK fail `tsc` instead of a live\n * request. The runtime is unchanged: the allowlist still checks every path.\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<P extends MethodPath<AugurAPI>>(\n methodPath: P,\n ...args: MethodArgs<AugurAPI, P>\n): Promise<MethodData<AugurAPI, P>> {\n // The value is what unwrapBaseResponse gives; its type is the model's TypedResult\n return unwrapBaseResponse(await callSdk(methodPath, args)) as MethodData<AugurAPI, P>;\n}\n\n/**\n * The same call as `queryAction` (allowlist, client, `edgeCache` strip, Redis), answered as\n * the SDK returned it: augur-api's `BaseResponse<T>` envelope (every SDK method's result) with\n * `data`, `total`, `totalResults` and `count`, so client code can page a list (atlas#107). A\n * method path carries no type, so the caller names `T` (`queryActionRaw<Article[]>(…)`). A\n * `queryAction` and a `queryActionRaw` of one call share one Redis entry.\n *\n * MUST NOT run under a React Query key that also holds `queryAction`'s shape (an options\n * proxy's `queryKey`): give it its own key.\n *\n * @param methodPath Dot-separated SDK method path (e.g. \"joomla.content.list\")\n * @param args Arguments to pass to the resolved method\n * @returns The SDK method's result unchanged (possibly from Redis cache)\n */\nexport async function queryActionRaw<T = unknown>(\n methodPath: string,\n ...args: unknown[]\n): Promise<BaseResponse<T>> {\n return callSdk(methodPath, args) as Promise<BaseResponse<T>>;\n}\n\n/**\n * `queryAction`, bounded (atlas#106): `options.deadline` caps the whole call in milliseconds\n * (every retry and the waits between them), and `options.signal` lets the caller cancel it. At\n * the deadline the call rejects with a `TimeoutError` (the request is cancelled, nothing more is\n * retried, nothing is cached), so a server render can fall back to a client-side fetch.\n *\n * Server code (an SSR render) SHOULD set a deadline: with none, the SDK's retry budget (3 retries\n * at 30 s each, plus backoff) becomes page latency. Called as a server action from the browser,\n * only `deadline` crosses: an `AbortSignal` can't be serialized.\n *\n * The options are not SDK arguments and not part of the cache key, so a bounded call and an\n * unbounded one share one Redis entry. Needs an `@simpleapps-com/augur-api` with\n * `AugurAPI.withRequest`; with an older client the call is refused rather than run unbounded.\n *\n * @example\n * ```ts\n * const items = await queryActionWith({ deadline: 5000 }, \"items.categories.items.list\", uid, params)\n * .catch(() => undefined); // past 5 s: render without them, fetch on the client\n * ```\n */\nexport async function queryActionWith<P extends MethodPath<AugurAPI>>(\n options: CallOptions,\n methodPath: P,\n ...args: MethodArgs<AugurAPI, P>\n): Promise<MethodData<AugurAPI, P>> {\n // Typed as queryAction (atlas#103); the value is what unwrapBaseResponse gives\n return unwrapBaseResponse(await callSdk(methodPath, args, options)) as MethodData<AugurAPI, P>;\n}\n/** `queryActionRaw`, bounded: the same options as {@link queryActionWith}. */\nexport async function queryActionRawWith<T = unknown>(\n options: CallOptions,\n methodPath: string,\n ...args: unknown[]\n): Promise<BaseResponse<T>> {\n return callSdk(methodPath, args, options) as Promise<BaseResponse<T>>;\n}\n\n/** Reset lazy-loaded imports. Used in tests only. @internal */\nexport function resetSessionImports(): void {\n _decode = undefined;\n _cookies = undefined;\n _decodeJwt = undefined;\n}\n\nexport { unwrapBaseResponse, getSessionCredentials, resolveMethod };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,OAIK;AAcP,IAAM,gBAAgB;AAYtB,IAAI;AACJ,IAAI;AACJ,IAAI;AAGJ,eAAe,gBAAkC;AAC/C,MAAI,YAAY,QAAW;AACzB,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,eAAe;AACxC,gBAAU,IAAI;AAAA,IAChB,QAAQ;AAEN,gBAAU;AAAA,IACZ;AAAA,EACF;AACA,MAAI,aAAa,QAAW;AAC1B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,cAAc;AACvC,iBAAW,IAAI;AAAA,IACjB,QAAQ;AAEN,iBAAW;AAAA,IACb;AAAA,EACF;AACA,MAAI,eAAe,QAAW;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,MAAM;AAC/B,mBAAa,IAAI;AAAA,IACnB,QAAQ;AAEN,mBAAa;AAAA,IACf;AAAA,EACF;AACA,SAAO,CAAC,CAAC,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;AACtC;AAGA,eAAe,iBAAiB,QAAyD;AACvF,QAAM,cAAc,MAAM,SAAU;AACpC,QAAM,eAAe,YAAY,IAAI,aAAa;AAGlD,QAAM,OAAO,kBAAkB,QAAQ,YAAY,CAAC;AACpD,QAAM,SAAS,gBAAgB,YAAY,IAAI,IAAI;AACnD,MAAI,CAAC,QAAQ,MAAO,QAAO;AAE3B,SAAO,QAAS,EAAE,OAAO,OAAO,OAAO,QAAQ,MAAM,KAAK,CAAC;AAC7D;AAcA,SAAS,wBAAwB,QAA+B;AAC9D,MAAI;AACF,UAAM,UAAU,WAAY,MAAM;AAClC,UAAM,WA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AAQ;AAAA,EAC9E;AACA,SAAO,eAAe,GAAG,QAAQ;AACnC;AA6BA,eAAsB,YACpB,eACG,MAC+B;AAElC,SAAO,mBAAmB,MAAM,QAAQ,YAAY,IAAI,CAAC;AAC3D;AAgBA,eAAsB,eACpB,eACG,MACuB;AAC1B,SAAO,QAAQ,YAAY,IAAI;AACjC;AAsBA,eAAsB,gBACpB,SACA,eACG,MAC+B;AAElC,SAAO,mBAAmB,MAAM,QAAQ,YAAY,MAAM,OAAO,CAAC;AACpE;AAEA,eAAsB,mBACpB,SACA,eACG,MACuB;AAC1B,SAAO,QAAQ,YAAY,MAAM,OAAO;AAC1C;AAGO,SAAS,sBAA4B;AAC1C,YAAU;AACV,aAAW;AACX,eAAa;AACf;","names":[]}
|
package/dist/hooks.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import {
|
|
3
3
|
queryAction
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import "./chunk-
|
|
6
|
-
import "./chunk-
|
|
4
|
+
} from "./chunk-Y54RGILF.js";
|
|
5
|
+
import "./chunk-ILXNFJVM.js";
|
|
6
|
+
import "./chunk-5DBFTSWY.js";
|
|
7
|
+
import "./chunk-HGJF667G.js";
|
|
7
8
|
|
|
8
9
|
// src/hooks.ts
|
|
9
10
|
import { createQueryActionProxy } from "@simpleapps-com/augur-core";
|
package/dist/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks.ts"],"sourcesContent":["// \"use client\" banner is injected by tsup at build time.\n// Client-side proxy that generates React Query options backed by server actions.\n//\n// IMPORTANT: This file MUST NOT import from server-actions.ts or any module\n// that transitively depends on ioredis/withServerCache/action factories.\n// The queryAction import comes from query-action.ts which only depends on\n// site-actions-store.ts (a lightweight globalThis getter with zero deps).\n\nimport { createQueryActionProxy } from \"@simpleapps-com/augur-core\";\nimport type {\n AnyQueryAction,\n DeepQueryOptions,\n OptionsProxyConfig,\n QueryActionFn,\n} from \"@simpleapps-com/augur-core\";\nimport type { AugurAPI } from \"@simpleapps-com/augur-api\";\nimport { registerQueryAction } from \"@simpleapps-com/augur-hooks\";\nimport { queryAction as defaultQueryAction } from \"./query-action\";\n\n// Auto-register queryAction so augur-hooks provider and hooks can detect it.\n// This runs as a side effect when any site imports from augur-server/hooks.\nregisterQueryAction(defaultQueryAction);\n\n// The built-in query action, typed by AugurAPI's paths (atlas#103), untyped once here: a\n// QueryActionFn fits every TApi's slot, so createServerQueryProxy<TApi> takes it as its default\nconst untypedQueryAction = defaultQueryAction as AnyQueryAction as QueryActionFn;\n\n// Re-export for consumers who need the type\nexport type { QueryActionFn };\n\n/**\n * Creates a client-side proxy that mirrors the SDK namespace and routes\n * every method call through a server action function.\n *\n * The `queryAction` parameter is optional. If omitted, it uses the built-in\n * server action from `@simpleapps-com/augur-server/query-action`.\n *\n * @example\n * ```tsx\n * import { createServerQueryProxy } from \"@simpleapps-com/augur-server/hooks\";\n *\n * const q = createServerQueryProxy();\n *\n * // Reads — any SDK method, routed through server actions\n * const { data: item } = useQuery(q.items.invMast.doc.get(42));\n * const { data: price } = useQuery(q.pricing.priceEngine.list({ itemId, customerId }));\n *\n * // Infinite queries — spread and add infinite-specific options\n * const { data, fetchNextPage } = useInfiniteQuery({\n * ...q.items.categories.items.list(itemCategoryUid, filters),\n * getNextPageParam: (lastPage, pages) => nextOffset(lastPage, pages), // the site's paging rule\n * initialPageParam: 0,\n * });\n *\n * // Mutations — write methods return mutation options\n * const addToCart = useMutation(q.commerce.cartLine.add.create());\n * ```\n */\nexport function createServerQueryProxy<TApi extends object = AugurAPI>(\n queryActionOrConfig?: AnyQueryAction<TApi> | OptionsProxyConfig,\n config?: OptionsProxyConfig,\n): DeepQueryOptions<TApi> {\n const queryAction =\n typeof queryActionOrConfig === \"function\" ? queryActionOrConfig : untypedQueryAction;\n const resolvedConfig = typeof queryActionOrConfig === \"function\" ? config : queryActionOrConfig;\n\n return createQueryActionProxy<TApi>(queryAction, resolvedConfig);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/hooks.ts"],"sourcesContent":["// \"use client\" banner is injected by tsup at build time.\n// Client-side proxy that generates React Query options backed by server actions.\n//\n// IMPORTANT: This file MUST NOT import from server-actions.ts or any module\n// that transitively depends on ioredis/withServerCache/action factories.\n// The queryAction import comes from query-action.ts which only depends on\n// site-actions-store.ts (a lightweight globalThis getter with zero deps).\n\nimport { createQueryActionProxy } from \"@simpleapps-com/augur-core\";\nimport type {\n AnyQueryAction,\n DeepQueryOptions,\n OptionsProxyConfig,\n QueryActionFn,\n} from \"@simpleapps-com/augur-core\";\nimport type { AugurAPI } from \"@simpleapps-com/augur-api\";\nimport { registerQueryAction } from \"@simpleapps-com/augur-hooks\";\nimport { queryAction as defaultQueryAction } from \"./query-action\";\n\n// Auto-register queryAction so augur-hooks provider and hooks can detect it.\n// This runs as a side effect when any site imports from augur-server/hooks.\nregisterQueryAction(defaultQueryAction);\n\n// The built-in query action, typed by AugurAPI's paths (atlas#103), untyped once here: a\n// QueryActionFn fits every TApi's slot, so createServerQueryProxy<TApi> takes it as its default\nconst untypedQueryAction = defaultQueryAction as AnyQueryAction as QueryActionFn;\n\n// Re-export for consumers who need the type\nexport type { QueryActionFn };\n\n/**\n * Creates a client-side proxy that mirrors the SDK namespace and routes\n * every method call through a server action function.\n *\n * The `queryAction` parameter is optional. If omitted, it uses the built-in\n * server action from `@simpleapps-com/augur-server/query-action`.\n *\n * @example\n * ```tsx\n * import { createServerQueryProxy } from \"@simpleapps-com/augur-server/hooks\";\n *\n * const q = createServerQueryProxy();\n *\n * // Reads — any SDK method, routed through server actions\n * const { data: item } = useQuery(q.items.invMast.doc.get(42));\n * const { data: price } = useQuery(q.pricing.priceEngine.list({ itemId, customerId }));\n *\n * // Infinite queries — spread and add infinite-specific options\n * const { data, fetchNextPage } = useInfiniteQuery({\n * ...q.items.categories.items.list(itemCategoryUid, filters),\n * getNextPageParam: (lastPage, pages) => nextOffset(lastPage, pages), // the site's paging rule\n * initialPageParam: 0,\n * });\n *\n * // Mutations — write methods return mutation options\n * const addToCart = useMutation(q.commerce.cartLine.add.create());\n * ```\n */\nexport function createServerQueryProxy<TApi extends object = AugurAPI>(\n queryActionOrConfig?: AnyQueryAction<TApi> | OptionsProxyConfig,\n config?: OptionsProxyConfig,\n): DeepQueryOptions<TApi> {\n const queryAction =\n typeof queryActionOrConfig === \"function\" ? queryActionOrConfig : untypedQueryAction;\n const resolvedConfig = typeof queryActionOrConfig === \"function\" ? config : queryActionOrConfig;\n\n return createQueryActionProxy<TApi>(queryAction, resolvedConfig);\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,8BAA8B;AAQvC,SAAS,2BAA2B;AAKpC,oBAAoB,WAAkB;AAItC,IAAM,qBAAqB;AAiCpB,SAAS,uBACd,qBACA,QACwB;AACxB,QAAMA,eACJ,OAAO,wBAAwB,aAAa,sBAAsB;AACpE,QAAM,iBAAiB,OAAO,wBAAwB,aAAa,SAAS;AAE5E,SAAO,uBAA6BA,cAAa,cAAc;AACjE;","names":["queryAction"]}
|
package/dist/index.js
CHANGED
|
@@ -21,12 +21,12 @@ import {
|
|
|
21
21
|
unwrap,
|
|
22
22
|
unwrapOr,
|
|
23
23
|
withServerCache
|
|
24
|
-
} from "./chunk-
|
|
25
|
-
import "./chunk-
|
|
24
|
+
} from "./chunk-GKT4MAWC.js";
|
|
25
|
+
import "./chunk-IM7FDRER.js";
|
|
26
26
|
import {
|
|
27
27
|
recaptchaOk
|
|
28
|
-
} from "./chunk-
|
|
29
|
-
import "./chunk-
|
|
28
|
+
} from "./chunk-5DBFTSWY.js";
|
|
29
|
+
import "./chunk-HGJF667G.js";
|
|
30
30
|
|
|
31
31
|
// src/server-query-client.ts
|
|
32
32
|
import { cache } from "react";
|
|
@@ -51,6 +51,7 @@ function createServerQueryClient() {
|
|
|
51
51
|
var getServerQueryClient = cache(() => createServerQueryClient());
|
|
52
52
|
|
|
53
53
|
// src/recaptcha.ts
|
|
54
|
+
import { errorLogLine } from "@simpleapps-com/augur-utils";
|
|
54
55
|
async function verifyRecaptcha(token) {
|
|
55
56
|
try {
|
|
56
57
|
const secretKey = process.env["RECAPTCHA_SECRET_KEY"];
|
|
@@ -67,7 +68,7 @@ async function verifyRecaptcha(token) {
|
|
|
67
68
|
const result = await res.json();
|
|
68
69
|
return recaptchaOk(true, true, result.success);
|
|
69
70
|
} catch (error) {
|
|
70
|
-
console.error("reCAPTCHA verify error
|
|
71
|
+
console.error(errorLogLine("reCAPTCHA verify error", error));
|
|
71
72
|
return false;
|
|
72
73
|
}
|
|
73
74
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server-query-client.ts","../src/recaptcha.ts"],"sourcesContent":["import { cache } from \"react\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { CACHE_CONFIG } from \"@simpleapps-com/augur-utils\";\n\n/**\n * Creates a server-side query client optimised for prefetching.\n *\n * - No persistence (server-only)\n * - No GC timers (gcTime: Infinity), so the client is freed with the request\n * - No retries (fail fast on server)\n * - No refetching (server renders are one-shot)\n */\nexport function createServerQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: CACHE_CONFIG.STATIC.staleTime,\n // Infinity = no GC timer. A finite value pins this per-request client\n // (and its whole cache) in memory until the timer fires (#481).\n gcTime: Infinity,\n retry: 0,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n },\n },\n });\n}\n\n/**\n * Returns a per-request singleton QueryClient for React Server Components.\n *\n * React's `cache()` deduplicates calls within a single server request,\n * so each request gets its own QueryClient while avoiding the cross-request\n * state leakage that a module-level singleton would cause.\n */\nexport const getServerQueryClient = cache((): QueryClient => createServerQueryClient());\n","import { recaptchaOk } from \"./rules\";\n\n/**\n * Server-side Google reCAPTCHA v3 verification.\n * Used by API routes that accept public form submissions.\n */\nexport async function verifyRecaptcha(token: string): Promise<boolean> {\n try {\n const secretKey = process.env[\"RECAPTCHA_SECRET_KEY\"];\n if (!secretKey) return recaptchaOk(false, false, undefined);\n\n const res = await fetch(\"https://www.google.com/recaptcha/api/siteverify\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({ secret: secretKey, response: token }),\n });\n if (!res.ok) {\n console.error(\"reCAPTCHA verify failed:\", res.status);\n return recaptchaOk(true, false, undefined);\n }\n const result = (await res.json()) as { success?: boolean };\n return recaptchaOk(true, true, result.success);\n } catch (error) {\n console.error(\"reCAPTCHA verify error
|
|
1
|
+
{"version":3,"sources":["../src/server-query-client.ts","../src/recaptcha.ts"],"sourcesContent":["import { cache } from \"react\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { CACHE_CONFIG } from \"@simpleapps-com/augur-utils\";\n\n/**\n * Creates a server-side query client optimised for prefetching.\n *\n * - No persistence (server-only)\n * - No GC timers (gcTime: Infinity), so the client is freed with the request\n * - No retries (fail fast on server)\n * - No refetching (server renders are one-shot)\n */\nexport function createServerQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: CACHE_CONFIG.STATIC.staleTime,\n // Infinity = no GC timer. A finite value pins this per-request client\n // (and its whole cache) in memory until the timer fires (#481).\n gcTime: Infinity,\n retry: 0,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n },\n },\n });\n}\n\n/**\n * Returns a per-request singleton QueryClient for React Server Components.\n *\n * React's `cache()` deduplicates calls within a single server request,\n * so each request gets its own QueryClient while avoiding the cross-request\n * state leakage that a module-level singleton would cause.\n */\nexport const getServerQueryClient = cache((): QueryClient => createServerQueryClient());\n","import { errorLogLine } from \"@simpleapps-com/augur-utils\";\nimport { recaptchaOk } from \"./rules\";\n\n/**\n * Server-side Google reCAPTCHA v3 verification.\n * Used by API routes that accept public form submissions.\n */\nexport async function verifyRecaptcha(token: string): Promise<boolean> {\n try {\n const secretKey = process.env[\"RECAPTCHA_SECRET_KEY\"];\n if (!secretKey) return recaptchaOk(false, false, undefined);\n\n const res = await fetch(\"https://www.google.com/recaptcha/api/siteverify\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({ secret: secretKey, response: token }),\n });\n if (!res.ok) {\n console.error(\"reCAPTCHA verify failed:\", res.status);\n return recaptchaOk(true, false, undefined);\n }\n const result = (await res.json()) as { success?: boolean };\n return recaptchaOk(true, true, result.success);\n } catch (error) {\n // The error's type only: never its message or cause (model AugurServerSecurity).\n console.error(errorLogLine(\"reCAPTCHA verify error\", error));\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB;AAUtB,SAAS,0BAAuC;AACrD,SAAO,IAAI,YAAY;AAAA,IACrB,gBAAgB;AAAA,MACd,SAAS;AAAA,QACP,WAAW,aAAa,OAAO;AAAA;AAAA;AAAA,QAG/B,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,gBAAgB;AAAA,QAChB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AASO,IAAM,uBAAuB,MAAM,MAAmB,wBAAwB,CAAC;;;ACpCtF,SAAS,oBAAoB;AAO7B,eAAsB,gBAAgB,OAAiC;AACrE,MAAI;AACF,UAAM,YAAY,QAAQ,IAAI,sBAAsB;AACpD,QAAI,CAAC,UAAW,QAAO,YAAY,OAAO,OAAO,MAAS;AAE1D,UAAM,MAAM,MAAM,MAAM,mDAAmD;AAAA,MACzE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,MAC/D,MAAM,IAAI,gBAAgB,EAAE,QAAQ,WAAW,UAAU,MAAM,CAAC;AAAA,IAClE,CAAC;AACD,QAAI,CAAC,IAAI,IAAI;AACX,cAAQ,MAAM,4BAA4B,IAAI,MAAM;AACpD,aAAO,YAAY,MAAM,OAAO,MAAS;AAAA,IAC3C;AACA,UAAM,SAAU,MAAM,IAAI,KAAK;AAC/B,WAAO,YAAY,MAAM,MAAM,OAAO,OAAO;AAAA,EAC/C,SAAS,OAAO;AAEd,YAAQ,MAAM,aAAa,0BAA0B,KAAK,CAAC;AAC3D,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/query-action.d.ts
CHANGED
|
@@ -13,8 +13,8 @@ import { type AugurAPI, type BaseResponse, type CallOptions } from "@simpleapps-
|
|
|
13
13
|
* do it), so audit casts (see "Brand strength" below).
|
|
14
14
|
*
|
|
15
15
|
* Returns null when:
|
|
16
|
-
* - the site
|
|
17
|
-
*
|
|
16
|
+
* - the site is not the cross-site (augur_info) site (its client's own siteId,
|
|
17
|
+
* atlas#105, owner 2026-11-16): then nothing is imported and no
|
|
18
18
|
* cookie is read, so pages using queryAction can render statically
|
|
19
19
|
* - no AUTH_SECRET is configured
|
|
20
20
|
* - next-auth/jwt, next/headers, or jose cannot be loaded
|
|
@@ -61,12 +61,6 @@ import { type AugurAPI, type BaseResponse, type CallOptions } from "@simpleapps-
|
|
|
61
61
|
* exactly one, in this function), not a hard type-system gate.
|
|
62
62
|
*/
|
|
63
63
|
declare function getSessionCredentials(): Promise<SessionCredentials | null>;
|
|
64
|
-
/**
|
|
65
|
-
* Resolve a dot-separated method path on an object, returning the leaf function.
|
|
66
|
-
*
|
|
67
|
-
* Demands {@link ApprovedMethodPath} so callers must have run the path through
|
|
68
|
-
* `parseMethodPath` first — passing an unvalidated string is a compile error.
|
|
69
|
-
*/
|
|
70
64
|
declare function resolveMethod(client: unknown, methodPath: ApprovedMethodPath): (...a: unknown[]) => Promise<unknown>;
|
|
71
65
|
/**
|
|
72
66
|
* The SDK call `callSdk` makes (everything above), answered as its envelope's data.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-action.d.ts","sourceRoot":"","sources":["../src/query-action.ts"],"names":[],"mappings":"AAUA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,wBAAsB,cAAc,CAAC,CAAC,GAAG,OAAO,EAC9C,UAAU,EAAE,MAAM,EAClB,GAAG,IAAI,EAAE,OAAO,EAAE,GACjB,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAE1B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,eAAe,CAAC,CAAC,SAAS,UAAU,CAAC,QAAQ,CAAC,EAClE,OAAO,EAAE,WAAW,EACpB,UAAU,EAAE,CAAC,EACb,GAAG,IAAI,EAAE,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC,GAC/B,OAAO,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAGlC;AACD,8EAA8E;AAC9E,wBAAsB,kBAAkB,CAAC,CAAC,GAAG,OAAO,EAClD,OAAO,EAAE,WAAW,EACpB,UAAU,EAAE,MAAM,EAClB,GAAG,IAAI,EAAE,OAAO,EAAE,GACjB,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAE1B;AAED,+DAA+D;AAC/D,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,aAAa,EAAE,CAAC"}
|
package/dist/query-action.js
CHANGED
|
@@ -8,9 +8,10 @@ import {
|
|
|
8
8
|
resetSessionImports,
|
|
9
9
|
resolveMethod,
|
|
10
10
|
unwrapBaseResponse
|
|
11
|
-
} from "./chunk-
|
|
12
|
-
import "./chunk-
|
|
13
|
-
import "./chunk-
|
|
11
|
+
} from "./chunk-Y54RGILF.js";
|
|
12
|
+
import "./chunk-ILXNFJVM.js";
|
|
13
|
+
import "./chunk-5DBFTSWY.js";
|
|
14
|
+
import "./chunk-HGJF667G.js";
|
|
14
15
|
export {
|
|
15
16
|
getSessionCredentials,
|
|
16
17
|
queryAction,
|
package/dist/recaptcha.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recaptcha.d.ts","sourceRoot":"","sources":["../src/recaptcha.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"recaptcha.d.ts","sourceRoot":"","sources":["../src/recaptcha.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,wBAAsB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAqBrE"}
|