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.
@@ -0,0 +1,585 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ let next_headers = require("next/headers");
25
+ next_headers = __toESM(next_headers);
26
+ let next_server = require("next/server");
27
+ next_server = __toESM(next_server);
28
+ let iron_session = require("iron-session");
29
+ iron_session = __toESM(iron_session);
30
+
31
+ //#region src/server/errors.ts
32
+ var ShopwaveAuthError = class extends Error {
33
+ code;
34
+ status;
35
+ /** Raw response body from the auth server, if any. Never contains our secret. */
36
+ body;
37
+ constructor(code, message, details = {}) {
38
+ super(message, details.cause !== void 0 ? { cause: details.cause } : void 0);
39
+ this.name = "ShopwaveAuthError";
40
+ this.code = code;
41
+ this.status = details.status;
42
+ this.body = details.body;
43
+ }
44
+ /**
45
+ * True when the auth server rejected the grant itself (bad/expired code or
46
+ * refresh token) rather than failing for a transient reason. Callers should
47
+ * treat the user as logged out.
48
+ */
49
+ get isInvalidGrant() {
50
+ return (this.code === "token_exchange_failed" || this.code === "token_refresh_failed") && this.status !== void 0 && this.status >= 400 && this.status < 500;
51
+ }
52
+ };
53
+
54
+ //#endregion
55
+ //#region src/server/token.ts
56
+ /** Shopwave API error id meaning "access token expired / invalid". */
57
+ const SHOPWAVE_TOKEN_EXPIRED_ERROR_ID = 908;
58
+ /**
59
+ * Converts a token-endpoint response into a {@link ShopwaveToken}.
60
+ * Returns `null` when the response has no access token.
61
+ *
62
+ * @param previous the token being refreshed; its refresh token is kept when
63
+ * the server doesn't send a new one.
64
+ */
65
+ function tokenFromResponse(response, previous, now = Date.now()) {
66
+ if (!response || typeof response.access_token !== "string" || !response.access_token) return null;
67
+ const expiresIn = Number(response.expires_in);
68
+ return {
69
+ accessToken: response.access_token,
70
+ refreshToken: typeof response.refresh_token === "string" && response.refresh_token || previous?.refreshToken,
71
+ tokenType: typeof response.token_type === "string" && response.token_type || "OAuth",
72
+ expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? now + expiresIn * 1e3 : void 0
73
+ };
74
+ }
75
+ /**
76
+ * Reads a token from session storage. Accepts both the current shape and the
77
+ * legacy raw response that older apps (e.g. AdminUI ≤ 0.1) stored directly in
78
+ * the session, so existing sessions survive an upgrade.
79
+ */
80
+ function normalizeStoredToken(raw) {
81
+ if (!raw || typeof raw !== "object") return null;
82
+ const t = raw;
83
+ if (typeof t.accessToken === "string" && t.accessToken) return {
84
+ accessToken: t.accessToken,
85
+ refreshToken: typeof t.refreshToken === "string" ? t.refreshToken : void 0,
86
+ tokenType: typeof t.tokenType === "string" && t.tokenType ? t.tokenType : "OAuth",
87
+ expiresAt: typeof t.expiresAt === "number" ? t.expiresAt : void 0
88
+ };
89
+ if (typeof t.access_token === "string" && t.access_token) return {
90
+ accessToken: t.access_token,
91
+ refreshToken: typeof t.refresh_token === "string" ? t.refresh_token : void 0,
92
+ tokenType: typeof t.token_type === "string" && t.token_type ? t.token_type : "OAuth"
93
+ };
94
+ return null;
95
+ }
96
+ /**
97
+ * True when the token has passed its expiry (minus `skewSeconds`).
98
+ * Tokens without a known expiry are treated as valid.
99
+ *
100
+ * Shopwave only issues a new access token once the old one has actually
101
+ * expired, so the default skew is 0 — refreshing early just returns the same
102
+ * token.
103
+ */
104
+ function isTokenExpired(token, { skewSeconds = 0, now = Date.now() } = {}) {
105
+ if (token.expiresAt === void 0) return false;
106
+ return now >= token.expiresAt - skewSeconds * 1e3;
107
+ }
108
+ /** `Authorization` header value, e.g. `OAuth 111ad…`. */
109
+ function authorizationHeader(token) {
110
+ return `${token.tokenType || "OAuth"} ${token.accessToken}`;
111
+ }
112
+ /**
113
+ * True when a Shopwave API response means "your access token is no longer
114
+ * valid": HTTP 401, or the API error 908 in the response envelope.
115
+ * Use it to trigger a forced refresh + a single retry.
116
+ */
117
+ function isExpiredTokenResponse(status, body) {
118
+ if (status === 401) return true;
119
+ const errors = body?.api?.message?.errors;
120
+ if (!errors || typeof errors !== "object") return false;
121
+ return Object.entries(errors).some(([key, value]) => key === String(SHOPWAVE_TOKEN_EXPIRED_ERROR_ID) || Number(value?.id) === SHOPWAVE_TOKEN_EXPIRED_ERROR_ID);
122
+ }
123
+
124
+ //#endregion
125
+ //#region src/server/oauth.ts
126
+ const REQUIRED_KEYS = [
127
+ "authServerUrl",
128
+ "clientId",
129
+ "clientSecret",
130
+ "redirectUri"
131
+ ];
132
+ /** Throws a readable error when required settings are missing. */
133
+ function assertOAuthConfig(config) {
134
+ const missing = REQUIRED_KEYS.filter((k) => !config?.[k]);
135
+ if (missing.length > 0) throw new ShopwaveAuthError("config_invalid", `Shopwave auth is missing required settings: ${missing.join(", ")}`);
136
+ }
137
+ function trimSlash(url) {
138
+ return url.replace(/\/+$/, "");
139
+ }
140
+ /**
141
+ * Creates a framework-agnostic Shopwave OAuth client (authorization-code flow
142
+ * with a client secret — the Shopwave auth server does not support PKCE, so
143
+ * this must run on a server).
144
+ *
145
+ * Config is validated lazily on first use, so creating the client at module
146
+ * scope doesn't break builds where env vars aren't present.
147
+ */
148
+ function createShopwaveOAuth(config) {
149
+ const endpoints = {
150
+ login: config.endpoints?.login ?? "/login",
151
+ token: config.endpoints?.token ?? "/oauth/token",
152
+ logout: config.endpoints?.logout ?? "/logout"
153
+ };
154
+ const base = () => {
155
+ assertOAuthConfig(config);
156
+ return trimSlash(config.authServerUrl);
157
+ };
158
+ const commonParams = (redirectUri) => new URLSearchParams({
159
+ access_type: config.accessType ?? "online",
160
+ redirect_uri: redirectUri,
161
+ response_type: "code",
162
+ client_id: config.clientId,
163
+ scope: config.scope ?? "application"
164
+ });
165
+ async function postToken(fields, errorCode) {
166
+ const url = `${base()}${endpoints.token}`;
167
+ const doFetch = config.fetch ?? globalThis.fetch;
168
+ let body;
169
+ if (config.tokenRequestFormat === "multipart") {
170
+ const fd = new FormData();
171
+ for (const [k, v] of Object.entries(fields)) fd.append(k, v);
172
+ body = fd;
173
+ } else body = new URLSearchParams(fields);
174
+ let response;
175
+ try {
176
+ response = await doFetch(url, {
177
+ method: "POST",
178
+ body,
179
+ headers: { Accept: "application/json" },
180
+ cache: "no-store"
181
+ });
182
+ } catch (cause) {
183
+ throw new ShopwaveAuthError("network_error", `Could not reach the Shopwave auth server`, { cause });
184
+ }
185
+ const text = await response.text();
186
+ if (!response.ok) throw new ShopwaveAuthError(errorCode, `Shopwave auth server returned ${response.status} for ${fields.grant_type}`, {
187
+ status: response.status,
188
+ body: text.slice(0, 2e3)
189
+ });
190
+ try {
191
+ return JSON.parse(text);
192
+ } catch (cause) {
193
+ throw new ShopwaveAuthError("token_response_invalid", "Token response was not JSON", {
194
+ status: response.status,
195
+ body: text.slice(0, 2e3),
196
+ cause
197
+ });
198
+ }
199
+ }
200
+ return {
201
+ config,
202
+ buildLoginUrl({ state } = {}) {
203
+ const params = commonParams(config.redirectUri);
204
+ if (state) params.set("state", state);
205
+ return `${base()}${endpoints.login}?${params.toString()}`;
206
+ },
207
+ buildLogoutUrl({ redirectUri } = {}) {
208
+ const params = commonParams(redirectUri ?? config.postLogoutRedirectUri ?? config.redirectUri);
209
+ return `${base()}${endpoints.logout}?${params.toString()}`;
210
+ },
211
+ async exchangeCode(code) {
212
+ if (!code) throw new ShopwaveAuthError("token_exchange_failed", "Missing authorization code");
213
+ const token = tokenFromResponse(await postToken({
214
+ code,
215
+ redirect_uri: config.redirectUri,
216
+ client_id: config.clientId,
217
+ client_secret: config.clientSecret,
218
+ scope: config.scope ?? "application",
219
+ grant_type: "authorization_code"
220
+ }, "token_exchange_failed"));
221
+ if (!token) throw new ShopwaveAuthError("token_response_invalid", "Token response had no access_token");
222
+ return token;
223
+ },
224
+ async refreshToken(tokenOrRefreshToken) {
225
+ const previous = typeof tokenOrRefreshToken === "string" ? {
226
+ accessToken: "",
227
+ refreshToken: tokenOrRefreshToken,
228
+ tokenType: "OAuth"
229
+ } : tokenOrRefreshToken;
230
+ if (!previous.refreshToken) throw new ShopwaveAuthError("token_refresh_failed", "No refresh token available", { status: 400 });
231
+ const token = tokenFromResponse(await postToken({
232
+ refresh_token: previous.refreshToken,
233
+ redirect_uri: config.redirectUri,
234
+ client_id: config.clientId,
235
+ client_secret: config.clientSecret,
236
+ grant_type: "refresh_token"
237
+ }, "token_refresh_failed"), previous);
238
+ if (!token) throw new ShopwaveAuthError("token_response_invalid", "Refresh response had no access_token");
239
+ return token;
240
+ }
241
+ };
242
+ }
243
+
244
+ //#endregion
245
+ //#region src/server/returnTo.ts
246
+ /**
247
+ * Helpers for the round trip through the auth server.
248
+ */
249
+ /**
250
+ * Only allows same-origin relative paths ("/products?tab=1"). Anything that
251
+ * could send the user to another site after login — absolute URLs,
252
+ * protocol-relative "//evil.com", backslash tricks, control characters —
253
+ * falls back to `fallback`.
254
+ */
255
+ function sanitizeReturnTo(value, fallback = "/") {
256
+ if (typeof value !== "string" || value.length === 0 || value.length > 2048) return fallback;
257
+ if (!/^\/(?![/\\])/.test(value)) return fallback;
258
+ if (/[\u0000-\u001f\u007f]/.test(value)) return fallback;
259
+ if (value.includes("\\")) return fallback;
260
+ return value;
261
+ }
262
+ /** Random, URL-safe value for the OAuth `state` parameter (128 bits, hex). */
263
+ function createState() {
264
+ const bytes = new Uint8Array(16);
265
+ globalThis.crypto.getRandomValues(bytes);
266
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
267
+ }
268
+ /** Constant-time string comparison for state values. */
269
+ function safeEqual(a, b) {
270
+ if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
271
+ let diff = 0;
272
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
273
+ return diff === 0;
274
+ }
275
+
276
+ //#endregion
277
+ //#region src/next/index.ts
278
+ function normalizePath(p) {
279
+ const withSlash = p.startsWith("/") ? p : `/${p}`;
280
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
281
+ }
282
+ function pathMatches(pathname, list) {
283
+ return list.some((raw) => {
284
+ const p = normalizePath(raw);
285
+ if (p === "/") return pathname === "/";
286
+ return pathname === p || pathname.startsWith(`${p}/`);
287
+ });
288
+ }
289
+ function escapeHtml(s) {
290
+ return s.replace(/[&<>"']/g, (c) => ({
291
+ "&": "&amp;",
292
+ "<": "&lt;",
293
+ ">": "&gt;",
294
+ "\"": "&quot;",
295
+ "'": "&#39;"
296
+ })[c]);
297
+ }
298
+ function readCookie(request, name) {
299
+ const fromNext = request.cookies?.get?.(name)?.value;
300
+ if (fromNext) return fromNext;
301
+ const header = request.headers.get("cookie");
302
+ if (!header) return void 0;
303
+ for (const part of header.split(";")) {
304
+ const idx = part.indexOf("=");
305
+ if (idx === -1) continue;
306
+ if (part.slice(0, idx).trim() === name) {
307
+ const value = part.slice(idx + 1).trim();
308
+ try {
309
+ return decodeURIComponent(value);
310
+ } catch {
311
+ return value;
312
+ }
313
+ }
314
+ }
315
+ }
316
+ let warnedAboutReadOnlyCookies = false;
317
+ /**
318
+ * Creates the Shopwave auth instance for one Next.js app. Call once at module
319
+ * scope (e.g. `lib/auth.ts`) and reuse. Config is validated on first use, so
320
+ * a missing env var doesn't fail `next build`.
321
+ */
322
+ function createShopwaveAuth(config) {
323
+ if (typeof window !== "undefined") throw new Error("react-shopwave-connect/next is server-only. Import it from route handlers, server code or proxy.ts.");
324
+ const oauth = createShopwaveOAuth(config);
325
+ const authPath = normalizePath(config.authPath ?? "/auth");
326
+ const logoutPath = normalizePath(config.logoutPath ?? `${authPath}/logout`);
327
+ const sessionPath = normalizePath(config.sessionPath ?? "/api/session");
328
+ const defaultReturnTo = sanitizeReturnTo(config.defaultReturnTo, "/");
329
+ const requireState = config.requireState ?? true;
330
+ const skewSeconds = config.refreshSkewSeconds ?? 0;
331
+ const loginTimeoutMs = (config.loginTimeoutSeconds ?? 600) * 1e3;
332
+ const cookieName = config.session?.cookieName ?? "shopwave_session";
333
+ /**
334
+ * Refresh de-duplication, per server instance. Requests that read the same
335
+ * (old) token share one refresh while it's in flight, and for a short while
336
+ * afterwards reuse its result instead of refreshing again.
337
+ */
338
+ const inflightRefresh = /* @__PURE__ */ new Map();
339
+ const recentRefresh = /* @__PURE__ */ new Map();
340
+ const RECENT_REFRESH_MS = 3e4;
341
+ function sessionOptions() {
342
+ const password = config.session?.password;
343
+ const passwords = typeof password === "string" ? [password] : Object.values(password ?? {});
344
+ if (passwords.length === 0 || passwords.some((p) => typeof p !== "string" || p.length < 32)) throw new ShopwaveAuthError("config_invalid", "Shopwave auth: session.password must be at least 32 characters (set a long random secret in your env).");
345
+ const cookieOptions = {
346
+ httpOnly: true,
347
+ secure: config.session.secure ?? process.env.NODE_ENV === "production",
348
+ sameSite: config.session.sameSite ?? "lax",
349
+ path: "/"
350
+ };
351
+ if (config.session.domain) cookieOptions.domain = config.session.domain;
352
+ const options = {
353
+ cookieName,
354
+ password,
355
+ cookieOptions
356
+ };
357
+ if (typeof config.session.ttl === "number") options.ttl = config.session.ttl;
358
+ return options;
359
+ }
360
+ async function getSession() {
361
+ return (0, iron_session.getIronSession)(await (0, next_headers.cookies)(), sessionOptions());
362
+ }
363
+ /**
364
+ * Cookies can only be written from route handlers, server actions and proxy.
365
+ * From a Server Component the token is still usable for this request; it will
366
+ * simply be refreshed again next time.
367
+ */
368
+ async function trySave(session) {
369
+ try {
370
+ await session.save();
371
+ } catch (error) {
372
+ if (!warnedAboutReadOnlyCookies) {
373
+ warnedAboutReadOnlyCookies = true;
374
+ console.warn("[react-shopwave-connect] Could not update the session cookie (called outside a route handler / server action?).", error?.message);
375
+ }
376
+ }
377
+ }
378
+ function tryDestroy(session) {
379
+ try {
380
+ session.destroy();
381
+ } catch {}
382
+ }
383
+ function refreshOnce(token) {
384
+ const key = `${token.refreshToken}\u0000${token.accessToken}`;
385
+ const now = Date.now();
386
+ const recent = recentRefresh.get(key);
387
+ if (recent && now - recent.at < RECENT_REFRESH_MS) return Promise.resolve(recent.token);
388
+ let pending = inflightRefresh.get(key);
389
+ if (!pending) {
390
+ pending = oauth.refreshToken(token).then((fresh) => {
391
+ for (const [k, v] of recentRefresh) if (now - v.at >= RECENT_REFRESH_MS) recentRefresh.delete(k);
392
+ recentRefresh.set(key, {
393
+ token: fresh,
394
+ at: Date.now()
395
+ });
396
+ return fresh;
397
+ }).finally(() => inflightRefresh.delete(key));
398
+ inflightRefresh.set(key, pending);
399
+ }
400
+ return pending;
401
+ }
402
+ async function getToken({ forceRefresh = false } = {}) {
403
+ const session = await getSession();
404
+ const token = normalizeStoredToken(session.token);
405
+ if (!token) return null;
406
+ const expired = isTokenExpired(token, { skewSeconds });
407
+ if (!forceRefresh && !expired) return token;
408
+ if (!token.refreshToken) {
409
+ if (expired || forceRefresh) {
410
+ tryDestroy(session);
411
+ return null;
412
+ }
413
+ return token;
414
+ }
415
+ try {
416
+ const refreshed = await refreshOnce(token);
417
+ session.token = refreshed;
418
+ await trySave(session);
419
+ return refreshed;
420
+ } catch (error) {
421
+ if (error instanceof ShopwaveAuthError && error.isInvalidGrant) {
422
+ tryDestroy(session);
423
+ return null;
424
+ }
425
+ throw error;
426
+ }
427
+ }
428
+ function loginPath(returnTo) {
429
+ if (!returnTo) return authPath;
430
+ const safe = sanitizeReturnTo(returnTo, defaultReturnTo);
431
+ return `${authPath}?returnTo=${encodeURIComponent(safe)}`;
432
+ }
433
+ function redirectTo(location, request) {
434
+ return next_server.NextResponse.redirect(new URL(location, request.url), 302);
435
+ }
436
+ function errorPage(status, message, retryHref) {
437
+ return new next_server.NextResponse(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign-in problem</title></head><body style="font-family:system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1rem;line-height:1.5"><h1 style="font-size:1.25rem">Sign-in didn’t complete</h1><p>${escapeHtml(message)}</p><p><a href="${escapeHtml(retryHref)}">Try again</a></p></body></html>`, {
438
+ status,
439
+ headers: {
440
+ "Content-Type": "text/html; charset=utf-8",
441
+ "Cache-Control": "no-store"
442
+ }
443
+ });
444
+ }
445
+ async function authHandler(request) {
446
+ const url = new URL(request.url);
447
+ const session = await getSession();
448
+ const pending = session.pendingLogin;
449
+ const oauthError = url.searchParams.get("error");
450
+ if (oauthError) {
451
+ delete session.pendingLogin;
452
+ await trySave(session);
453
+ return errorPage(400, `Shopwave sign-in reported: ${url.searchParams.get("error_description") || oauthError}.`, loginPath(pending?.returnTo));
454
+ }
455
+ const code = url.searchParams.get("code");
456
+ if (!code) {
457
+ const returnTo$1 = sanitizeReturnTo(url.searchParams.get("returnTo"), defaultReturnTo);
458
+ const state = createState();
459
+ session.pendingLogin = {
460
+ state,
461
+ returnTo: returnTo$1,
462
+ createdAt: Date.now()
463
+ };
464
+ await session.save();
465
+ return next_server.NextResponse.redirect(oauth.buildLoginUrl({ state }), 302);
466
+ }
467
+ const returnedState = url.searchParams.get("state");
468
+ const isFresh = !!pending && Date.now() - pending.createdAt <= loginTimeoutMs;
469
+ const stateMatches = !!pending && !!returnedState && safeEqual(returnedState, pending.state);
470
+ if (requireState ? !(stateMatches && isFresh) : !!pending && !!returnedState && !stateMatches) {
471
+ delete session.pendingLogin;
472
+ await trySave(session);
473
+ return errorPage(400, "This sign-in link has expired or didn’t start from this browser. Please sign in again.", loginPath(pending?.returnTo));
474
+ }
475
+ let token;
476
+ try {
477
+ token = await oauth.exchangeCode(code);
478
+ } catch (error) {
479
+ console.error("[react-shopwave-connect] Code exchange failed:", error?.message);
480
+ delete session.pendingLogin;
481
+ await trySave(session);
482
+ return errorPage(error instanceof ShopwaveAuthError && error.isInvalidGrant ? 400 : 502, "We couldn’t complete sign-in with Shopwave.", loginPath(pending?.returnTo));
483
+ }
484
+ const returnTo = pending?.returnTo ?? defaultReturnTo;
485
+ delete session.pendingLogin;
486
+ session.token = token;
487
+ await session.save();
488
+ return redirectTo(returnTo, request);
489
+ }
490
+ async function logoutHandler(_request) {
491
+ (await getSession()).destroy();
492
+ return next_server.NextResponse.redirect(oauth.buildLogoutUrl(), 302);
493
+ }
494
+ async function getStatus() {
495
+ const token = normalizeStoredToken((await getSession()).token);
496
+ if (!token) return { loggedIn: false };
497
+ return !isTokenExpired(token) || !!token.refreshToken ? {
498
+ loggedIn: true,
499
+ expiresAt: token.expiresAt
500
+ } : { loggedIn: false };
501
+ }
502
+ async function isAuthenticated(request) {
503
+ const value = readCookie(request, cookieName);
504
+ if (!value) return false;
505
+ try {
506
+ const { password, ttl } = sessionOptions();
507
+ const token = normalizeStoredToken((await (0, iron_session.unsealData)(value, {
508
+ password,
509
+ ttl
510
+ }))?.token);
511
+ return !!token && (!isTokenExpired(token) || !!token.refreshToken);
512
+ } catch {
513
+ return false;
514
+ }
515
+ }
516
+ const noStore = { "Cache-Control": "no-store" };
517
+ return {
518
+ oauth,
519
+ logoutPath,
520
+ loginPath,
521
+ getSession,
522
+ getStatus,
523
+ getToken,
524
+ async getAccessToken(options) {
525
+ return (await getToken(options))?.accessToken ?? null;
526
+ },
527
+ async getAuthorizationHeader(options) {
528
+ const token = await getToken(options);
529
+ return token ? authorizationHeader(token) : null;
530
+ },
531
+ withAuth(handler) {
532
+ return async (request, context) => {
533
+ const token = await getToken();
534
+ if (!token) return next_server.NextResponse.json({ error: "unauthorized" }, {
535
+ status: 401,
536
+ headers: noStore
537
+ });
538
+ return handler(request, context, {
539
+ accessToken: token.accessToken,
540
+ authorization: authorizationHeader(token),
541
+ token
542
+ });
543
+ };
544
+ },
545
+ isAuthenticated,
546
+ async protect(request, options = {}) {
547
+ const { pathname, search } = new URL(request.url);
548
+ if (pathMatches(pathname, [
549
+ authPath,
550
+ logoutPath,
551
+ sessionPath,
552
+ ...options.publicPaths ?? []
553
+ ])) return;
554
+ if (await isAuthenticated(request)) return void 0;
555
+ if (pathMatches(pathname, options.apiPaths ?? ["/api"])) return next_server.NextResponse.json({ error: "unauthorized" }, {
556
+ status: 401,
557
+ headers: noStore
558
+ });
559
+ return redirectTo(loginPath(pathname + search), request);
560
+ },
561
+ handlers: {
562
+ auth: authHandler,
563
+ logout: logoutHandler,
564
+ session: {
565
+ async GET() {
566
+ return next_server.NextResponse.json(await getStatus(), { headers: noStore });
567
+ },
568
+ async DELETE() {
569
+ (await getSession()).destroy();
570
+ return new next_server.NextResponse(null, {
571
+ status: 204,
572
+ headers: noStore
573
+ });
574
+ }
575
+ }
576
+ }
577
+ };
578
+ }
579
+
580
+ //#endregion
581
+ exports.ShopwaveAuthError = ShopwaveAuthError;
582
+ exports.authorizationHeader = authorizationHeader;
583
+ exports.createShopwaveAuth = createShopwaveAuth;
584
+ exports.isExpiredTokenResponse = isExpiredTokenResponse;
585
+ //# sourceMappingURL=index.cjs.map