react-shopwave-connect 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +140 -21
- package/dist/core/index.cjs +46 -5
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +34 -6
- package/dist/core/index.d.ts +34 -6
- package/dist/core/index.js +44 -6
- package/dist/core/index.js.map +1 -1
- package/dist/hooks/index.cjs +50 -5
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +29 -1
- package/dist/hooks/index.d.ts +29 -1
- package/dist/hooks/index.js +50 -6
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +64 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +45 -6
- package/dist/index.d.ts +45 -6
- package/dist/index.js +61 -6
- package/dist/index.js.map +1 -1
- package/dist/next/index.cjs +585 -0
- package/dist/next/index.cjs.map +1 -0
- package/dist/next/index.d.cts +255 -0
- package/dist/next/index.d.ts +255 -0
- package/dist/next/index.js +556 -0
- package/dist/next/index.js.map +1 -0
- package/dist/server/index.cjs +260 -0
- package/dist/server/index.cjs.map +1 -0
- package/dist/server/index.d.cts +177 -0
- package/dist/server/index.d.ts +177 -0
- package/dist/server/index.js +248 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +41 -8
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
//#region src/server/errors.ts
|
|
2
|
+
var ShopwaveAuthError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
status;
|
|
5
|
+
/** Raw response body from the auth server, if any. Never contains our secret. */
|
|
6
|
+
body;
|
|
7
|
+
constructor(code, message, details = {}) {
|
|
8
|
+
super(message, details.cause !== void 0 ? { cause: details.cause } : void 0);
|
|
9
|
+
this.name = "ShopwaveAuthError";
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.status = details.status;
|
|
12
|
+
this.body = details.body;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* True when the auth server rejected the grant itself (bad/expired code or
|
|
16
|
+
* refresh token) rather than failing for a transient reason. Callers should
|
|
17
|
+
* treat the user as logged out.
|
|
18
|
+
*/
|
|
19
|
+
get isInvalidGrant() {
|
|
20
|
+
return (this.code === "token_exchange_failed" || this.code === "token_refresh_failed") && this.status !== void 0 && this.status >= 400 && this.status < 500;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/server/token.ts
|
|
26
|
+
/** Shopwave API error id meaning "access token expired / invalid". */
|
|
27
|
+
const SHOPWAVE_TOKEN_EXPIRED_ERROR_ID = 908;
|
|
28
|
+
/**
|
|
29
|
+
* Converts a token-endpoint response into a {@link ShopwaveToken}.
|
|
30
|
+
* Returns `null` when the response has no access token.
|
|
31
|
+
*
|
|
32
|
+
* @param previous the token being refreshed; its refresh token is kept when
|
|
33
|
+
* the server doesn't send a new one.
|
|
34
|
+
*/
|
|
35
|
+
function tokenFromResponse(response, previous, now = Date.now()) {
|
|
36
|
+
if (!response || typeof response.access_token !== "string" || !response.access_token) return null;
|
|
37
|
+
const expiresIn = Number(response.expires_in);
|
|
38
|
+
return {
|
|
39
|
+
accessToken: response.access_token,
|
|
40
|
+
refreshToken: typeof response.refresh_token === "string" && response.refresh_token || previous?.refreshToken,
|
|
41
|
+
tokenType: typeof response.token_type === "string" && response.token_type || "OAuth",
|
|
42
|
+
expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? now + expiresIn * 1e3 : void 0
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Reads a token from session storage. Accepts both the current shape and the
|
|
47
|
+
* legacy raw response that older apps (e.g. AdminUI ≤ 0.1) stored directly in
|
|
48
|
+
* the session, so existing sessions survive an upgrade.
|
|
49
|
+
*/
|
|
50
|
+
function normalizeStoredToken(raw) {
|
|
51
|
+
if (!raw || typeof raw !== "object") return null;
|
|
52
|
+
const t = raw;
|
|
53
|
+
if (typeof t.accessToken === "string" && t.accessToken) return {
|
|
54
|
+
accessToken: t.accessToken,
|
|
55
|
+
refreshToken: typeof t.refreshToken === "string" ? t.refreshToken : void 0,
|
|
56
|
+
tokenType: typeof t.tokenType === "string" && t.tokenType ? t.tokenType : "OAuth",
|
|
57
|
+
expiresAt: typeof t.expiresAt === "number" ? t.expiresAt : void 0
|
|
58
|
+
};
|
|
59
|
+
if (typeof t.access_token === "string" && t.access_token) return {
|
|
60
|
+
accessToken: t.access_token,
|
|
61
|
+
refreshToken: typeof t.refresh_token === "string" ? t.refresh_token : void 0,
|
|
62
|
+
tokenType: typeof t.token_type === "string" && t.token_type ? t.token_type : "OAuth"
|
|
63
|
+
};
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* True when the token has passed its expiry (minus `skewSeconds`).
|
|
68
|
+
* Tokens without a known expiry are treated as valid.
|
|
69
|
+
*
|
|
70
|
+
* Shopwave only issues a new access token once the old one has actually
|
|
71
|
+
* expired, so the default skew is 0 — refreshing early just returns the same
|
|
72
|
+
* token.
|
|
73
|
+
*/
|
|
74
|
+
function isTokenExpired(token, { skewSeconds = 0, now = Date.now() } = {}) {
|
|
75
|
+
if (token.expiresAt === void 0) return false;
|
|
76
|
+
return now >= token.expiresAt - skewSeconds * 1e3;
|
|
77
|
+
}
|
|
78
|
+
/** `Authorization` header value, e.g. `OAuth 111ad…`. */
|
|
79
|
+
function authorizationHeader(token) {
|
|
80
|
+
return `${token.tokenType || "OAuth"} ${token.accessToken}`;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* True when a Shopwave API response means "your access token is no longer
|
|
84
|
+
* valid": HTTP 401, or the API error 908 in the response envelope.
|
|
85
|
+
* Use it to trigger a forced refresh + a single retry.
|
|
86
|
+
*/
|
|
87
|
+
function isExpiredTokenResponse(status, body) {
|
|
88
|
+
if (status === 401) return true;
|
|
89
|
+
const errors = body?.api?.message?.errors;
|
|
90
|
+
if (!errors || typeof errors !== "object") return false;
|
|
91
|
+
return Object.entries(errors).some(([key, value]) => key === String(SHOPWAVE_TOKEN_EXPIRED_ERROR_ID) || Number(value?.id) === SHOPWAVE_TOKEN_EXPIRED_ERROR_ID);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region src/server/oauth.ts
|
|
96
|
+
const REQUIRED_KEYS = [
|
|
97
|
+
"authServerUrl",
|
|
98
|
+
"clientId",
|
|
99
|
+
"clientSecret",
|
|
100
|
+
"redirectUri"
|
|
101
|
+
];
|
|
102
|
+
/** Throws a readable error when required settings are missing. */
|
|
103
|
+
function assertOAuthConfig(config) {
|
|
104
|
+
const missing = REQUIRED_KEYS.filter((k) => !config?.[k]);
|
|
105
|
+
if (missing.length > 0) throw new ShopwaveAuthError("config_invalid", `Shopwave auth is missing required settings: ${missing.join(", ")}`);
|
|
106
|
+
}
|
|
107
|
+
function trimSlash(url) {
|
|
108
|
+
return url.replace(/\/+$/, "");
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Creates a framework-agnostic Shopwave OAuth client (authorization-code flow
|
|
112
|
+
* with a client secret — the Shopwave auth server does not support PKCE, so
|
|
113
|
+
* this must run on a server).
|
|
114
|
+
*
|
|
115
|
+
* Config is validated lazily on first use, so creating the client at module
|
|
116
|
+
* scope doesn't break builds where env vars aren't present.
|
|
117
|
+
*/
|
|
118
|
+
function createShopwaveOAuth(config) {
|
|
119
|
+
const endpoints = {
|
|
120
|
+
login: config.endpoints?.login ?? "/login",
|
|
121
|
+
token: config.endpoints?.token ?? "/oauth/token",
|
|
122
|
+
logout: config.endpoints?.logout ?? "/logout"
|
|
123
|
+
};
|
|
124
|
+
const base = () => {
|
|
125
|
+
assertOAuthConfig(config);
|
|
126
|
+
return trimSlash(config.authServerUrl);
|
|
127
|
+
};
|
|
128
|
+
const commonParams = (redirectUri) => new URLSearchParams({
|
|
129
|
+
access_type: config.accessType ?? "online",
|
|
130
|
+
redirect_uri: redirectUri,
|
|
131
|
+
response_type: "code",
|
|
132
|
+
client_id: config.clientId,
|
|
133
|
+
scope: config.scope ?? "application"
|
|
134
|
+
});
|
|
135
|
+
async function postToken(fields, errorCode) {
|
|
136
|
+
const url = `${base()}${endpoints.token}`;
|
|
137
|
+
const doFetch = config.fetch ?? globalThis.fetch;
|
|
138
|
+
let body;
|
|
139
|
+
if (config.tokenRequestFormat === "multipart") {
|
|
140
|
+
const fd = new FormData();
|
|
141
|
+
for (const [k, v] of Object.entries(fields)) fd.append(k, v);
|
|
142
|
+
body = fd;
|
|
143
|
+
} else body = new URLSearchParams(fields);
|
|
144
|
+
let response;
|
|
145
|
+
try {
|
|
146
|
+
response = await doFetch(url, {
|
|
147
|
+
method: "POST",
|
|
148
|
+
body,
|
|
149
|
+
headers: { Accept: "application/json" },
|
|
150
|
+
cache: "no-store"
|
|
151
|
+
});
|
|
152
|
+
} catch (cause) {
|
|
153
|
+
throw new ShopwaveAuthError("network_error", `Could not reach the Shopwave auth server`, { cause });
|
|
154
|
+
}
|
|
155
|
+
const text = await response.text();
|
|
156
|
+
if (!response.ok) throw new ShopwaveAuthError(errorCode, `Shopwave auth server returned ${response.status} for ${fields.grant_type}`, {
|
|
157
|
+
status: response.status,
|
|
158
|
+
body: text.slice(0, 2e3)
|
|
159
|
+
});
|
|
160
|
+
try {
|
|
161
|
+
return JSON.parse(text);
|
|
162
|
+
} catch (cause) {
|
|
163
|
+
throw new ShopwaveAuthError("token_response_invalid", "Token response was not JSON", {
|
|
164
|
+
status: response.status,
|
|
165
|
+
body: text.slice(0, 2e3),
|
|
166
|
+
cause
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
config,
|
|
172
|
+
buildLoginUrl({ state } = {}) {
|
|
173
|
+
const params = commonParams(config.redirectUri);
|
|
174
|
+
if (state) params.set("state", state);
|
|
175
|
+
return `${base()}${endpoints.login}?${params.toString()}`;
|
|
176
|
+
},
|
|
177
|
+
buildLogoutUrl({ redirectUri } = {}) {
|
|
178
|
+
const params = commonParams(redirectUri ?? config.postLogoutRedirectUri ?? config.redirectUri);
|
|
179
|
+
return `${base()}${endpoints.logout}?${params.toString()}`;
|
|
180
|
+
},
|
|
181
|
+
async exchangeCode(code) {
|
|
182
|
+
if (!code) throw new ShopwaveAuthError("token_exchange_failed", "Missing authorization code");
|
|
183
|
+
const token = tokenFromResponse(await postToken({
|
|
184
|
+
code,
|
|
185
|
+
redirect_uri: config.redirectUri,
|
|
186
|
+
client_id: config.clientId,
|
|
187
|
+
client_secret: config.clientSecret,
|
|
188
|
+
scope: config.scope ?? "application",
|
|
189
|
+
grant_type: "authorization_code"
|
|
190
|
+
}, "token_exchange_failed"));
|
|
191
|
+
if (!token) throw new ShopwaveAuthError("token_response_invalid", "Token response had no access_token");
|
|
192
|
+
return token;
|
|
193
|
+
},
|
|
194
|
+
async refreshToken(tokenOrRefreshToken) {
|
|
195
|
+
const previous = typeof tokenOrRefreshToken === "string" ? {
|
|
196
|
+
accessToken: "",
|
|
197
|
+
refreshToken: tokenOrRefreshToken,
|
|
198
|
+
tokenType: "OAuth"
|
|
199
|
+
} : tokenOrRefreshToken;
|
|
200
|
+
if (!previous.refreshToken) throw new ShopwaveAuthError("token_refresh_failed", "No refresh token available", { status: 400 });
|
|
201
|
+
const token = tokenFromResponse(await postToken({
|
|
202
|
+
refresh_token: previous.refreshToken,
|
|
203
|
+
redirect_uri: config.redirectUri,
|
|
204
|
+
client_id: config.clientId,
|
|
205
|
+
client_secret: config.clientSecret,
|
|
206
|
+
grant_type: "refresh_token"
|
|
207
|
+
}, "token_refresh_failed"), previous);
|
|
208
|
+
if (!token) throw new ShopwaveAuthError("token_response_invalid", "Refresh response had no access_token");
|
|
209
|
+
return token;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
//#endregion
|
|
215
|
+
//#region src/server/returnTo.ts
|
|
216
|
+
/**
|
|
217
|
+
* Helpers for the round trip through the auth server.
|
|
218
|
+
*/
|
|
219
|
+
/**
|
|
220
|
+
* Only allows same-origin relative paths ("/products?tab=1"). Anything that
|
|
221
|
+
* could send the user to another site after login — absolute URLs,
|
|
222
|
+
* protocol-relative "//evil.com", backslash tricks, control characters —
|
|
223
|
+
* falls back to `fallback`.
|
|
224
|
+
*/
|
|
225
|
+
function sanitizeReturnTo(value, fallback = "/") {
|
|
226
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 2048) return fallback;
|
|
227
|
+
if (!/^\/(?![/\\])/.test(value)) return fallback;
|
|
228
|
+
if (/[\u0000-\u001f\u007f]/.test(value)) return fallback;
|
|
229
|
+
if (value.includes("\\")) return fallback;
|
|
230
|
+
return value;
|
|
231
|
+
}
|
|
232
|
+
/** Random, URL-safe value for the OAuth `state` parameter (128 bits, hex). */
|
|
233
|
+
function createState() {
|
|
234
|
+
const bytes = new Uint8Array(16);
|
|
235
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
236
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
237
|
+
}
|
|
238
|
+
/** Constant-time string comparison for state values. */
|
|
239
|
+
function safeEqual(a, b) {
|
|
240
|
+
if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
|
|
241
|
+
let diff = 0;
|
|
242
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
243
|
+
return diff === 0;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
//#endregion
|
|
247
|
+
export { SHOPWAVE_TOKEN_EXPIRED_ERROR_ID, ShopwaveAuthError, assertOAuthConfig, authorizationHeader, createShopwaveOAuth, createState, isExpiredTokenResponse, isTokenExpired, normalizeStoredToken, safeEqual, sanitizeReturnTo, tokenFromResponse };
|
|
248
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["body: URLSearchParams | FormData","response: Response"],"sources":["../../src/server/errors.ts","../../src/server/token.ts","../../src/server/oauth.ts","../../src/server/returnTo.ts"],"sourcesContent":["/**\n * Error thrown by the server-side auth helpers.\n *\n * `code` is stable and safe to branch on; `status` is the HTTP status returned\n * by the Shopwave auth server when there was one.\n */\nexport type ShopwaveAuthErrorCode =\n | \"config_invalid\"\n | \"token_exchange_failed\"\n | \"token_refresh_failed\"\n | \"token_response_invalid\"\n | \"network_error\";\n\nexport class ShopwaveAuthError extends Error {\n readonly code: ShopwaveAuthErrorCode;\n readonly status?: number;\n /** Raw response body from the auth server, if any. Never contains our secret. */\n readonly body?: string;\n\n constructor(\n code: ShopwaveAuthErrorCode,\n message: string,\n details: { status?: number; body?: string; cause?: unknown } = {}\n ) {\n super(message, details.cause !== undefined ? { cause: details.cause } : undefined);\n this.name = \"ShopwaveAuthError\";\n this.code = code;\n this.status = details.status;\n this.body = details.body;\n }\n\n /**\n * True when the auth server rejected the grant itself (bad/expired code or\n * refresh token) rather than failing for a transient reason. Callers should\n * treat the user as logged out.\n */\n get isInvalidGrant(): boolean {\n return (\n (this.code === \"token_exchange_failed\" || this.code === \"token_refresh_failed\") &&\n this.status !== undefined &&\n this.status >= 400 &&\n this.status < 500\n );\n }\n}\n","/**\n * Token model + helpers shared by every server-side integration.\n *\n * The Shopwave auth server returns (snake_case):\n * { access_token, refresh_token, token_type: \"OAuth\", expires_in: 43200 }\n *\n * We store a normalised, camelCase shape with an absolute expiry so any\n * request can decide whether the token is still usable without extra state.\n */\n\nexport interface ShopwaveToken {\n accessToken: string;\n /** Long-lived; the Shopwave server does not rotate it on refresh. */\n refreshToken?: string;\n /** Scheme used in the Authorization header. Shopwave uses \"OAuth\". */\n tokenType: string;\n /** Absolute expiry, epoch milliseconds. Undefined if the server didn't say. */\n expiresAt?: number;\n}\n\n/** Raw token response from `POST {authServer}/oauth/token`. */\nexport interface ShopwaveTokenResponse {\n access_token?: string;\n refresh_token?: string;\n token_type?: string;\n expires_in?: number | string;\n [key: string]: unknown;\n}\n\n/** Shopwave API error id meaning \"access token expired / invalid\". */\nexport const SHOPWAVE_TOKEN_EXPIRED_ERROR_ID = 908;\n\n/**\n * Converts a token-endpoint response into a {@link ShopwaveToken}.\n * Returns `null` when the response has no access token.\n *\n * @param previous the token being refreshed; its refresh token is kept when\n * the server doesn't send a new one.\n */\nexport function tokenFromResponse(\n response: ShopwaveTokenResponse,\n previous?: ShopwaveToken,\n now: number = Date.now()\n): ShopwaveToken | null {\n if (!response || typeof response.access_token !== \"string\" || !response.access_token) {\n return null;\n }\n\n const expiresIn = Number(response.expires_in);\n\n return {\n accessToken: response.access_token,\n refreshToken:\n (typeof response.refresh_token === \"string\" && response.refresh_token) ||\n previous?.refreshToken,\n tokenType: (typeof response.token_type === \"string\" && response.token_type) || \"OAuth\",\n expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? now + expiresIn * 1000 : undefined,\n };\n}\n\n/**\n * Reads a token from session storage. Accepts both the current shape and the\n * legacy raw response that older apps (e.g. AdminUI ≤ 0.1) stored directly in\n * the session, so existing sessions survive an upgrade.\n */\nexport function normalizeStoredToken(raw: unknown): ShopwaveToken | null {\n if (!raw || typeof raw !== \"object\") return null;\n const t = raw as Record<string, unknown>;\n\n if (typeof t.accessToken === \"string\" && t.accessToken) {\n return {\n accessToken: t.accessToken,\n refreshToken: typeof t.refreshToken === \"string\" ? t.refreshToken : undefined,\n tokenType: typeof t.tokenType === \"string\" && t.tokenType ? t.tokenType : \"OAuth\",\n expiresAt: typeof t.expiresAt === \"number\" ? t.expiresAt : undefined,\n };\n }\n\n if (typeof t.access_token === \"string\" && t.access_token) {\n // Legacy shape: we don't know when it was issued, so no expiresAt.\n // It will be refreshed reactively when the API reports it expired.\n return {\n accessToken: t.access_token,\n refreshToken: typeof t.refresh_token === \"string\" ? t.refresh_token : undefined,\n tokenType: typeof t.token_type === \"string\" && t.token_type ? t.token_type : \"OAuth\",\n };\n }\n\n return null;\n}\n\n/**\n * True when the token has passed its expiry (minus `skewSeconds`).\n * Tokens without a known expiry are treated as valid.\n *\n * Shopwave only issues a new access token once the old one has actually\n * expired, so the default skew is 0 — refreshing early just returns the same\n * token.\n */\nexport function isTokenExpired(\n token: ShopwaveToken,\n { skewSeconds = 0, now = Date.now() }: { skewSeconds?: number; now?: number } = {}\n): boolean {\n if (token.expiresAt === undefined) return false;\n return now >= token.expiresAt - skewSeconds * 1000;\n}\n\n/** `Authorization` header value, e.g. `OAuth 111ad…`. */\nexport function authorizationHeader(token: ShopwaveToken): string {\n return `${token.tokenType || \"OAuth\"} ${token.accessToken}`;\n}\n\n/**\n * True when a Shopwave API response means \"your access token is no longer\n * valid\": HTTP 401, or the API error 908 in the response envelope.\n * Use it to trigger a forced refresh + a single retry.\n */\nexport function isExpiredTokenResponse(status: number, body?: unknown): boolean {\n if (status === 401) return true;\n const errors = (body as { api?: { message?: { errors?: Record<string, { id?: number }> } } })\n ?.api?.message?.errors;\n if (!errors || typeof errors !== \"object\") return false;\n return Object.entries(errors).some(\n ([key, value]) =>\n key === String(SHOPWAVE_TOKEN_EXPIRED_ERROR_ID) ||\n Number(value?.id) === SHOPWAVE_TOKEN_EXPIRED_ERROR_ID\n );\n}\n","import { ShopwaveAuthError } from \"./errors\";\nimport { tokenFromResponse, type ShopwaveToken, type ShopwaveTokenResponse } from \"./token\";\n\n/**\n * Per-app OAuth settings. Everything that differs between Shopwave apps lives\n * here; the flow itself is identical for all of them.\n */\nexport interface ShopwaveOAuthConfig {\n /** e.g. `https://secure.merchantstack.com` (no trailing slash needed). */\n authServerUrl: string;\n clientId: string;\n /** Server-side only. Never expose it to the browser. */\n clientSecret: string;\n /**\n * The callback URL registered for this client on the auth server, e.g.\n * `https://admin.example.com/auth`. Must match exactly.\n */\n redirectUri: string;\n /** Where the auth server sends the user after logout. Defaults to `redirectUri`. */\n postLogoutRedirectUri?: string;\n /** Defaults to `\"application\"`. */\n scope?: string;\n /** Defaults to `\"online\"`. */\n accessType?: string;\n /**\n * Body encoding for `POST /oauth/token`. Defaults to standard\n * `application/x-www-form-urlencoded`; `\"multipart\"` sends `FormData`.\n */\n tokenRequestFormat?: \"urlencoded\" | \"multipart\";\n /** Auth-server paths. Defaults match Shopwave: `/login`, `/oauth/token`, `/logout`. */\n endpoints?: { login?: string; token?: string; logout?: string };\n /** Custom fetch (tests, proxies). Defaults to global `fetch`. */\n fetch?: typeof fetch;\n}\n\nexport interface ShopwaveOAuthClient {\n readonly config: Readonly<ShopwaveOAuthConfig>;\n /** URL to send the browser to so the user can sign in. */\n buildLoginUrl(params?: { state?: string }): string;\n /** URL to send the browser to so the auth server ends its own session. */\n buildLogoutUrl(params?: { redirectUri?: string }): string;\n /** Exchanges the `?code=` from the callback for tokens (server-to-server). */\n exchangeCode(code: string): Promise<ShopwaveToken>;\n /**\n * Gets a fresh access token. Shopwave keeps the same refresh token, so the\n * returned token carries the previous refresh token when none is sent back.\n */\n refreshToken(token: ShopwaveToken | string): Promise<ShopwaveToken>;\n}\n\nconst REQUIRED_KEYS = [\"authServerUrl\", \"clientId\", \"clientSecret\", \"redirectUri\"] as const;\n\n/** Throws a readable error when required settings are missing. */\nexport function assertOAuthConfig(config: Partial<ShopwaveOAuthConfig>): asserts config is ShopwaveOAuthConfig {\n const missing = REQUIRED_KEYS.filter((k) => !config?.[k]);\n if (missing.length > 0) {\n throw new ShopwaveAuthError(\n \"config_invalid\",\n `Shopwave auth is missing required settings: ${missing.join(\", \")}`\n );\n }\n}\n\nfunction trimSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\n/**\n * Creates a framework-agnostic Shopwave OAuth client (authorization-code flow\n * with a client secret — the Shopwave auth server does not support PKCE, so\n * this must run on a server).\n *\n * Config is validated lazily on first use, so creating the client at module\n * scope doesn't break builds where env vars aren't present.\n */\nexport function createShopwaveOAuth(config: ShopwaveOAuthConfig): ShopwaveOAuthClient {\n const endpoints = {\n login: config.endpoints?.login ?? \"/login\",\n token: config.endpoints?.token ?? \"/oauth/token\",\n logout: config.endpoints?.logout ?? \"/logout\",\n };\n\n const base = () => {\n assertOAuthConfig(config);\n return trimSlash(config.authServerUrl);\n };\n\n const commonParams = (redirectUri: string) =>\n new URLSearchParams({\n access_type: config.accessType ?? \"online\",\n redirect_uri: redirectUri,\n response_type: \"code\",\n client_id: config.clientId,\n scope: config.scope ?? \"application\",\n });\n\n async function postToken(\n fields: Record<string, string>,\n errorCode: \"token_exchange_failed\" | \"token_refresh_failed\"\n ): Promise<ShopwaveTokenResponse> {\n const url = `${base()}${endpoints.token}`;\n const doFetch = config.fetch ?? globalThis.fetch;\n\n let body: URLSearchParams | FormData;\n if (config.tokenRequestFormat === \"multipart\") {\n const fd = new FormData();\n for (const [k, v] of Object.entries(fields)) fd.append(k, v);\n body = fd;\n } else {\n body = new URLSearchParams(fields);\n }\n\n let response: Response;\n try {\n response = await doFetch(url, {\n method: \"POST\",\n body,\n headers: { Accept: \"application/json\" },\n cache: \"no-store\",\n } as RequestInit);\n } catch (cause) {\n throw new ShopwaveAuthError(\"network_error\", `Could not reach the Shopwave auth server`, { cause });\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new ShopwaveAuthError(\n errorCode,\n `Shopwave auth server returned ${response.status} for ${fields.grant_type}`,\n { status: response.status, body: text.slice(0, 2000) }\n );\n }\n\n try {\n return JSON.parse(text) as ShopwaveTokenResponse;\n } catch (cause) {\n throw new ShopwaveAuthError(\"token_response_invalid\", \"Token response was not JSON\", {\n status: response.status,\n body: text.slice(0, 2000),\n cause,\n });\n }\n }\n\n return {\n config,\n\n buildLoginUrl({ state } = {}) {\n const params = commonParams(config.redirectUri);\n if (state) params.set(\"state\", state);\n return `${base()}${endpoints.login}?${params.toString()}`;\n },\n\n buildLogoutUrl({ redirectUri } = {}) {\n const params = commonParams(redirectUri ?? config.postLogoutRedirectUri ?? config.redirectUri);\n return `${base()}${endpoints.logout}?${params.toString()}`;\n },\n\n async exchangeCode(code) {\n if (!code) {\n throw new ShopwaveAuthError(\"token_exchange_failed\", \"Missing authorization code\");\n }\n const json = await postToken(\n {\n code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n client_secret: config.clientSecret,\n scope: config.scope ?? \"application\",\n grant_type: \"authorization_code\",\n },\n \"token_exchange_failed\"\n );\n const token = tokenFromResponse(json);\n if (!token) {\n throw new ShopwaveAuthError(\"token_response_invalid\", \"Token response had no access_token\");\n }\n return token;\n },\n\n async refreshToken(tokenOrRefreshToken) {\n const previous =\n typeof tokenOrRefreshToken === \"string\"\n ? ({ accessToken: \"\", refreshToken: tokenOrRefreshToken, tokenType: \"OAuth\" } as ShopwaveToken)\n : tokenOrRefreshToken;\n\n if (!previous.refreshToken) {\n throw new ShopwaveAuthError(\"token_refresh_failed\", \"No refresh token available\", { status: 400 });\n }\n\n const json = await postToken(\n {\n refresh_token: previous.refreshToken,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n client_secret: config.clientSecret,\n grant_type: \"refresh_token\",\n },\n \"token_refresh_failed\"\n );\n const token = tokenFromResponse(json, previous);\n if (!token) {\n throw new ShopwaveAuthError(\"token_response_invalid\", \"Refresh response had no access_token\");\n }\n return token;\n },\n };\n}\n","/**\n * Helpers for the round trip through the auth server.\n */\n\n/**\n * Only allows same-origin relative paths (\"/products?tab=1\"). Anything that\n * could send the user to another site after login — absolute URLs,\n * protocol-relative \"//evil.com\", backslash tricks, control characters —\n * falls back to `fallback`.\n */\nexport function sanitizeReturnTo(value: unknown, fallback = \"/\"): string {\n if (typeof value !== \"string\" || value.length === 0 || value.length > 2048) {\n return fallback;\n }\n // Must start with a single \"/\" not followed by \"/\" or \"\\\".\n if (!/^\\/(?![/\\\\])/.test(value)) return fallback;\n // No control characters (CR/LF header injection, tabs, NUL, …).\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(value)) return fallback;\n if (value.includes(\"\\\\\")) return fallback;\n return value;\n}\n\n/** Random, URL-safe value for the OAuth `state` parameter (128 bits, hex). */\nexport function createState(): string {\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Constant-time string comparison for state values. */\nexport function safeEqual(a: string, b: string): boolean {\n if (typeof a !== \"string\" || typeof b !== \"string\" || a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n"],"mappings":";AAaA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,AAAS;CACT,AAAS;;CAET,AAAS;CAET,YACE,MACA,SACA,UAA+D,EAAE,EACjE;AACA,QAAM,SAAS,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,OAAO,GAAG,OAAU;AAClF,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,OAAK,SAAS,QAAQ;AACtB,OAAK,OAAO,QAAQ;;;;;;;CAQtB,IAAI,iBAA0B;AAC5B,UACG,KAAK,SAAS,2BAA2B,KAAK,SAAS,2BACxD,KAAK,WAAW,UAChB,KAAK,UAAU,OACf,KAAK,SAAS;;;;;;;ACXpB,MAAa,kCAAkC;;;;;;;;AAS/C,SAAgB,kBACd,UACA,UACA,MAAc,KAAK,KAAK,EACF;AACtB,KAAI,CAAC,YAAY,OAAO,SAAS,iBAAiB,YAAY,CAAC,SAAS,aACtE,QAAO;CAGT,MAAM,YAAY,OAAO,SAAS,WAAW;AAE7C,QAAO;EACL,aAAa,SAAS;EACtB,cACG,OAAO,SAAS,kBAAkB,YAAY,SAAS,iBACxD,UAAU;EACZ,WAAY,OAAO,SAAS,eAAe,YAAY,SAAS,cAAe;EAC/E,WAAW,OAAO,SAAS,UAAU,IAAI,YAAY,IAAI,MAAM,YAAY,MAAO;EACnF;;;;;;;AAQH,SAAgB,qBAAqB,KAAoC;AACvE,KAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;CAC5C,MAAM,IAAI;AAEV,KAAI,OAAO,EAAE,gBAAgB,YAAY,EAAE,YACzC,QAAO;EACL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ACpE,QAAO;AAGT,KAAI,CAAC,eAAe,KAAK,MAAM,CAAE,QAAO;AAGxC,KAAI,wBAAwB,KAAK,MAAM,CAAE,QAAO;AAChD,KAAI,MAAM,SAAS,KAAK,CAAE,QAAO;AACjC,QAAO;;;AAIT,SAAgB,cAAsB;CACpC,MAAM,QAAQ,IAAI,WAAW,GAAG;AAChC,YAAW,OAAO,gBAAgB,MAAM;AACxC,QAAO,MAAM,KAAK,QAAQ,MAAM,EAAE,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,KAAK,GAAG;;;AAI3E,SAAgB,UAAU,GAAW,GAAoB;AACvD,KAAI,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,EAAE,WAAW,EAAE,OAAQ,QAAO;CACpF,IAAI,OAAO;AACX,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,IAAK,SAAQ,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,EAAE;AAC5E,QAAO,SAAS"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-shopwave-connect",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Shopwave API client
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Shopwave API client: framework-agnostic core, React hooks, and server-side OAuth (with a Next.js adapter).",
|
|
5
5
|
"author": "Yasir",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"type": "module",
|
|
@@ -39,6 +39,26 @@
|
|
|
39
39
|
"types": "./dist/hooks/index.d.cts",
|
|
40
40
|
"default": "./dist/hooks/index.cjs"
|
|
41
41
|
}
|
|
42
|
+
},
|
|
43
|
+
"./server": {
|
|
44
|
+
"import": {
|
|
45
|
+
"types": "./dist/server/index.d.ts",
|
|
46
|
+
"default": "./dist/server/index.js"
|
|
47
|
+
},
|
|
48
|
+
"require": {
|
|
49
|
+
"types": "./dist/server/index.d.cts",
|
|
50
|
+
"default": "./dist/server/index.cjs"
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
"./next": {
|
|
54
|
+
"import": {
|
|
55
|
+
"types": "./dist/next/index.d.ts",
|
|
56
|
+
"default": "./dist/next/index.js"
|
|
57
|
+
},
|
|
58
|
+
"require": {
|
|
59
|
+
"types": "./dist/next/index.d.cts",
|
|
60
|
+
"default": "./dist/next/index.cjs"
|
|
61
|
+
}
|
|
42
62
|
}
|
|
43
63
|
},
|
|
44
64
|
"files": [
|
|
@@ -51,12 +71,15 @@
|
|
|
51
71
|
"build": "tsdown",
|
|
52
72
|
"typecheck": "tsc --noEmit",
|
|
53
73
|
"prepublishOnly": "npm run build",
|
|
54
|
-
"test": "vitest run",
|
|
55
|
-
"test:integration": "vitest run --config vitest.config.ts"
|
|
74
|
+
"test": "vitest run --config vitest.unit.config.ts",
|
|
75
|
+
"test:integration": "vitest run --config vitest.config.ts",
|
|
76
|
+
"test:unit": "vitest run --config vitest.unit.config.ts"
|
|
56
77
|
},
|
|
57
78
|
"peerDependencies": {
|
|
58
79
|
"react": ">=17.0.0",
|
|
59
|
-
"react-dom": ">=17.0.0"
|
|
80
|
+
"react-dom": ">=17.0.0",
|
|
81
|
+
"next": ">=14.0.0",
|
|
82
|
+
"iron-session": ">=8.0.0 <10"
|
|
60
83
|
},
|
|
61
84
|
"peerDependenciesMeta": {
|
|
62
85
|
"react": {
|
|
@@ -64,11 +87,19 @@
|
|
|
64
87
|
},
|
|
65
88
|
"react-dom": {
|
|
66
89
|
"optional": true
|
|
90
|
+
},
|
|
91
|
+
"next": {
|
|
92
|
+
"optional": true
|
|
93
|
+
},
|
|
94
|
+
"iron-session": {
|
|
95
|
+
"optional": true
|
|
67
96
|
}
|
|
68
97
|
},
|
|
69
98
|
"devDependencies": {
|
|
70
99
|
"@types/node": "^22.0.0",
|
|
71
100
|
"@types/react": "^19.0.0",
|
|
101
|
+
"iron-session": "^8.0.4",
|
|
102
|
+
"next": "^16.3.6",
|
|
72
103
|
"react": "^19.0.0",
|
|
73
104
|
"react-dom": "^19.0.0",
|
|
74
105
|
"tsdown": "^0.15.6",
|
|
@@ -76,10 +107,12 @@
|
|
|
76
107
|
"vitest": "^3.1.0"
|
|
77
108
|
},
|
|
78
109
|
"keywords": [
|
|
79
|
-
"shopwave",
|
|
80
|
-
"react",
|
|
81
|
-
"hooks",
|
|
82
110
|
"api",
|
|
111
|
+
"hooks",
|
|
112
|
+
"nextjs",
|
|
113
|
+
"oauth",
|
|
114
|
+
"react",
|
|
115
|
+
"shopwave",
|
|
83
116
|
"typescript"
|
|
84
117
|
]
|
|
85
118
|
}
|