@wix/astro 0.3.4 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.d.ts +5 -0
- package/build/index.js +124854 -0
- package/build/index.js.map +1 -0
- package/build/xdg-open +1267 -0
- package/build/yoga.wasm +0 -0
- package/build-runtime/auth.d.ts +5 -0
- package/build-runtime/auth.js +3557 -0
- package/package.json +37 -47
- package/runtime/entry.astro +26 -0
- package/src/directories.ts +10 -0
- package/src/env.d.ts +3 -0
- package/src/index.ts +217 -0
- package/src/middleware/auth.ts +115 -0
- package/src/plugins/patchGlobal.ts +20 -0
- package/src/utils/authStrategyAsyncLocalStorage.ts +6 -0
- package/src/utils/createProjectModel.ts +77 -0
- package/src/utils/generateAppManifest.ts +32 -0
- package/src/utils/isValidBackofficeComponent.ts +15 -0
- package/src/utils/loadExtension.ts +59 -0
- package/src/utils/sessionCookieJson.ts +9 -0
- package/src/utils/writeVirtualExtensionFiles.ts +54 -0
- package/tsconfig.json +8 -0
- package/tsup.config.mjs +28 -0
- package/README.md +0 -121
- package/dist/auth-context.d.ts +0 -5
- package/dist/auth-context.js +0 -2
- package/dist/client.d.ts +0 -15
- package/dist/client.js +0 -16
- package/dist/components/login-helpers/bi-header-generator.d.ts +0 -11
- package/dist/components/login-helpers/bi-header-generator.js +0 -17
- package/dist/components/login-helpers/iframeUtils.d.ts +0 -4
- package/dist/components/login-helpers/iframeUtils.js +0 -43
- package/dist/components/login-helpers/login-helpers.d.ts +0 -42
- package/dist/components/login-helpers/login-helpers.js +0 -119
- package/dist/components/login.astro +0 -872
- package/dist/entrypoints/server.d.ts +0 -13
- package/dist/entrypoints/server.js +0 -36
- package/dist/helpers/index.d.ts +0 -1
- package/dist/helpers/index.js +0 -1
- package/dist/index.d.ts +0 -5
- package/dist/index.js +0 -4
- package/dist/integration.d.ts +0 -22
- package/dist/integration.js +0 -233
- package/dist/loaders/blog.d.ts +0 -2
- package/dist/loaders/blog.js +0 -48
- package/dist/loaders/index.d.ts +0 -2
- package/dist/loaders/index.js +0 -2
- package/dist/middleware.d.ts +0 -2
- package/dist/middleware.js +0 -89
- package/dist/routes/auth/callback.d.ts +0 -3
- package/dist/routes/auth/callback.js +0 -52
- package/dist/routes/auth/constants.d.ts +0 -5
- package/dist/routes/auth/constants.js +0 -5
- package/dist/routes/auth/login.d.ts +0 -3
- package/dist/routes/auth/login.js +0 -26
- package/dist/routes/auth/logout-callback.d.ts +0 -3
- package/dist/routes/auth/logout-callback.js +0 -9
- package/dist/routes/auth/logout.d.ts +0 -3
- package/dist/routes/auth/logout.js +0 -10
- package/dist/routes/auth/runtime.d.ts +0 -5
- package/dist/routes/auth/runtime.js +0 -7
- package/dist/runtime-client.d.ts +0 -3
- package/dist/runtime-client.js +0 -4
- package/dist/runtime.client.d.ts +0 -2
- package/dist/runtime.client.js +0 -4
- package/dist/runtime.d.ts +0 -5
- package/dist/runtime.js +0 -12
- package/dist/runtime.server.d.ts +0 -2
- package/dist/runtime.server.js +0 -8
- package/dist/vite-plugins/sdk-context.d.ts +0 -4
- package/dist/vite-plugins/sdk-context.js +0 -67
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import type { Request as CLOUDFLARE_REQUEST, ExecutionContext } from "@cloudflare/workers-types";
|
|
2
|
-
import type { SSRManifest } from "astro";
|
|
3
|
-
export interface Runtime<T extends object = object> {
|
|
4
|
-
runtime: {
|
|
5
|
-
env: T;
|
|
6
|
-
ctx: ExecutionContext;
|
|
7
|
-
};
|
|
8
|
-
}
|
|
9
|
-
export declare function createExports(manifest: SSRManifest): {
|
|
10
|
-
default: {
|
|
11
|
-
fetch: (request: Request & CLOUDFLARE_REQUEST, env: Record<string, unknown>) => Promise<Response>;
|
|
12
|
-
};
|
|
13
|
-
};
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { createClient } from "@wix/sdk";
|
|
2
|
-
import { App } from "astro/app";
|
|
3
|
-
import { setGetEnv } from "astro/env/setup";
|
|
4
|
-
export function createExports(manifest) {
|
|
5
|
-
const app = new App(manifest);
|
|
6
|
-
const client = createClient({});
|
|
7
|
-
const fetch = async (request, env) => {
|
|
8
|
-
setGetEnv((key) => typeof env[key] === "string" ? env[key] : JSON.stringify(env[key]));
|
|
9
|
-
const { pathname } = new URL(request.url);
|
|
10
|
-
if (request.method === "POST" && pathname.startsWith("/_wix/events")) {
|
|
11
|
-
await client.webhooks.processRequest(request);
|
|
12
|
-
return new Response(null, { status: 200 });
|
|
13
|
-
}
|
|
14
|
-
if (request.method === "POST" &&
|
|
15
|
-
pathname.startsWith("/_wix/service-plugins")) {
|
|
16
|
-
return client.servicePlugins.processRequest(request);
|
|
17
|
-
}
|
|
18
|
-
Reflect.set(request, Symbol.for("astro.clientAddress"), request.headers.get("cf-connecting-ip"));
|
|
19
|
-
const response = await app.render(request);
|
|
20
|
-
// Thats to handle the quirk where Astro calls prerender 404s via fetch() to itself, and CF will return 522.
|
|
21
|
-
if (response.status === 404) {
|
|
22
|
-
const targetStatusURL = new URL(request.url);
|
|
23
|
-
const errorRoute = app.match({ url: `${targetStatusURL.origin}/${response.status}${manifest.trailingSlash === "always" ? '/' : null}` });
|
|
24
|
-
if (errorRoute && errorRoute.prerender) {
|
|
25
|
-
return await env['ASSETS'].fetch(request);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
if (app.setCookieHeaders) {
|
|
29
|
-
for (const setCookieHeader of app.setCookieHeaders(response)) {
|
|
30
|
-
response.headers.append("Set-Cookie", setCookieHeader);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
return response;
|
|
34
|
-
};
|
|
35
|
-
return { default: { fetch } };
|
|
36
|
-
}
|
package/dist/helpers/index.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/helpers/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/index.d.ts
DELETED
package/dist/index.js
DELETED
package/dist/integration.d.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import type { AstroIntegration } from "astro";
|
|
2
|
-
import { wixBlogLoader } from "./loaders/blog.js";
|
|
3
|
-
export { wixBlogLoader };
|
|
4
|
-
export type { Runtime } from "./entrypoints/server.js";
|
|
5
|
-
export interface WixAstroIntegrationOptions {
|
|
6
|
-
/**
|
|
7
|
-
* Name of the cookie used for the Wix session
|
|
8
|
-
* @default "wixSession"
|
|
9
|
-
*/
|
|
10
|
-
sessionCookieName?: string;
|
|
11
|
-
/**
|
|
12
|
-
* Whether to pre-warm the redirect session by injecting an iframe to cookie.wix.com
|
|
13
|
-
* @default false
|
|
14
|
-
*/
|
|
15
|
-
preWarmRedirectSession?: boolean;
|
|
16
|
-
/***
|
|
17
|
-
* Wether to inect routes for Wix Auth
|
|
18
|
-
* @default true
|
|
19
|
-
*/
|
|
20
|
-
useWixAuth?: boolean;
|
|
21
|
-
}
|
|
22
|
-
export declare function createIntegration(opts?: WixAstroIntegrationOptions): AstroIntegration;
|
package/dist/integration.js
DELETED
|
@@ -1,233 +0,0 @@
|
|
|
1
|
-
import { appendForwardSlash, prependForwardSlash, } from "@astrojs/internal-helpers/path";
|
|
2
|
-
import { createRequire } from "node:module";
|
|
3
|
-
import { passthroughImageService } from "astro/config";
|
|
4
|
-
import { buildResolver } from "esm-resolve";
|
|
5
|
-
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { wixBlogLoader } from "./loaders/blog.js";
|
|
7
|
-
import { loadEnv } from "vite";
|
|
8
|
-
import chalk from "chalk";
|
|
9
|
-
import { outdent } from "outdent";
|
|
10
|
-
import { promises as fs } from "node:fs";
|
|
11
|
-
import path from "node:path";
|
|
12
|
-
import { wixSDKContext } from "./vite-plugins/sdk-context.js";
|
|
13
|
-
export { wixBlogLoader };
|
|
14
|
-
export function createIntegration(opts = {
|
|
15
|
-
sessionCookieName: "wixSession",
|
|
16
|
-
useWixAuth: true,
|
|
17
|
-
preWarmRedirectSession: false,
|
|
18
|
-
}) {
|
|
19
|
-
const sessionCookieName = opts.sessionCookieName ?? "wixSession";
|
|
20
|
-
const preWarmRedirectSession = opts.preWarmRedirectSession ?? false;
|
|
21
|
-
let _config;
|
|
22
|
-
let _buildOutput;
|
|
23
|
-
return {
|
|
24
|
-
name: "@wix/astro",
|
|
25
|
-
hooks: {
|
|
26
|
-
"astro:config:setup": async ({ config, updateConfig, addMiddleware, injectRoute, injectScript, logger, }) => {
|
|
27
|
-
const aRequire = buildResolver(fileURLToPath(import.meta.url), {
|
|
28
|
-
resolveToAbsolute: true,
|
|
29
|
-
});
|
|
30
|
-
if (opts.useWixAuth) {
|
|
31
|
-
injectRoute({
|
|
32
|
-
entrypoint: aRequire("./routes/auth/login"),
|
|
33
|
-
pattern: "/api/auth/login",
|
|
34
|
-
prerender: false,
|
|
35
|
-
});
|
|
36
|
-
injectRoute({
|
|
37
|
-
entrypoint: aRequire("./routes/auth/logout"),
|
|
38
|
-
pattern: "/api/auth/logout",
|
|
39
|
-
prerender: false,
|
|
40
|
-
});
|
|
41
|
-
injectRoute({
|
|
42
|
-
entrypoint: aRequire("./routes/auth/callback"),
|
|
43
|
-
pattern: "/api/auth/callback",
|
|
44
|
-
prerender: false,
|
|
45
|
-
});
|
|
46
|
-
injectRoute({
|
|
47
|
-
entrypoint: aRequire("./routes/auth/logout-callback"),
|
|
48
|
-
pattern: "/api/auth/logout-callback",
|
|
49
|
-
prerender: false,
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
addMiddleware({
|
|
53
|
-
entrypoint: aRequire("./middleware"),
|
|
54
|
-
order: "pre",
|
|
55
|
-
});
|
|
56
|
-
const userEnv = loadEnv(process.env["NODE_ENV"] ?? "development", process.cwd(), "");
|
|
57
|
-
if (!userEnv["WIX_CLIENT_ID"]) {
|
|
58
|
-
logger.error(outdent `
|
|
59
|
-
Missing environment variable ${chalk.blueBright(`WIX_CLIENT_ID`)}
|
|
60
|
-
To use the Wix SDK, you must provide the ${chalk.blueBright("WIX_CLIENT_ID")} environment variable.
|
|
61
|
-
|
|
62
|
-
💡 To pull the required environment variables from Wix, run:
|
|
63
|
-
${chalk.magenta("npx wix edge env --env local pull")}
|
|
64
|
-
|
|
65
|
-
🔍 Need Help?
|
|
66
|
-
- Visit our docs: https://dev.wix.com/docs/go-headless
|
|
67
|
-
- Join the community: https://discord.com/channels/1114269395317968906/1288424190969511987
|
|
68
|
-
|
|
69
|
-
`);
|
|
70
|
-
throw new Error(`${chalk.magenta(`WIX_CLIENT_ID`)} not found in loaded environment variables`);
|
|
71
|
-
}
|
|
72
|
-
if (preWarmRedirectSession) {
|
|
73
|
-
injectScript('page', `import { getAuth } from '@wix/astro/runtime/client'; getAuth().syncToWixPages();`);
|
|
74
|
-
}
|
|
75
|
-
updateConfig({
|
|
76
|
-
env: {
|
|
77
|
-
schema: {
|
|
78
|
-
WIX_CLIENT_ID: {
|
|
79
|
-
type: "string",
|
|
80
|
-
access: "public",
|
|
81
|
-
context: "client",
|
|
82
|
-
},
|
|
83
|
-
WIX_CLIENT_SECRET: {
|
|
84
|
-
type: "string",
|
|
85
|
-
access: "secret",
|
|
86
|
-
context: "server",
|
|
87
|
-
optional: true,
|
|
88
|
-
},
|
|
89
|
-
WIX_CLIENT_PUBLIC_KEY: {
|
|
90
|
-
type: "string",
|
|
91
|
-
access: "secret",
|
|
92
|
-
context: "server",
|
|
93
|
-
optional: true,
|
|
94
|
-
},
|
|
95
|
-
WIX_CLIENT_INSTANCE_ID: {
|
|
96
|
-
type: "string",
|
|
97
|
-
access: "secret",
|
|
98
|
-
context: "server",
|
|
99
|
-
optional: true,
|
|
100
|
-
},
|
|
101
|
-
ENV_NAME: {
|
|
102
|
-
type: "string",
|
|
103
|
-
access: "public",
|
|
104
|
-
context: "client",
|
|
105
|
-
},
|
|
106
|
-
WIX_SESSION_COOKIE_NAME: {
|
|
107
|
-
type: "string",
|
|
108
|
-
access: "public",
|
|
109
|
-
context: "server",
|
|
110
|
-
optional: true,
|
|
111
|
-
default: opts.sessionCookieName,
|
|
112
|
-
},
|
|
113
|
-
},
|
|
114
|
-
},
|
|
115
|
-
build: {
|
|
116
|
-
client: new URL(`./client${prependForwardSlash(appendForwardSlash(config.base))}`, config.outDir),
|
|
117
|
-
server: new URL("./server/", config.outDir),
|
|
118
|
-
serverEntry: "index.js",
|
|
119
|
-
redirects: false,
|
|
120
|
-
},
|
|
121
|
-
vite: {
|
|
122
|
-
plugins: [
|
|
123
|
-
// The plugin is used to inject the Wix SDK context into the client bundle
|
|
124
|
-
// It's currently commented out because there are some issues with the current implementation
|
|
125
|
-
// (currently the magic import is injected into any type of module, not only JS)
|
|
126
|
-
// not sure if it's necessary to inject the Wix SDK context into the client bundle
|
|
127
|
-
wixSDKContext({
|
|
128
|
-
sessionCookieName,
|
|
129
|
-
}),
|
|
130
|
-
],
|
|
131
|
-
},
|
|
132
|
-
image: {
|
|
133
|
-
service: passthroughImageService(),
|
|
134
|
-
domains: ["static.wixstatic.com"],
|
|
135
|
-
},
|
|
136
|
-
});
|
|
137
|
-
},
|
|
138
|
-
"astro:config:done": async ({ setAdapter, config, buildOutput }) => {
|
|
139
|
-
_config = config;
|
|
140
|
-
_buildOutput = buildOutput;
|
|
141
|
-
if (_buildOutput === "static") {
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
144
|
-
setAdapter({
|
|
145
|
-
name: "@wix/astro",
|
|
146
|
-
serverEntrypoint: createRequire(import.meta.url).resolve("./entrypoints/server"),
|
|
147
|
-
exports: ["default"],
|
|
148
|
-
adapterFeatures: {
|
|
149
|
-
edgeMiddleware: false,
|
|
150
|
-
buildOutput: "server",
|
|
151
|
-
},
|
|
152
|
-
supportedAstroFeatures: {
|
|
153
|
-
serverOutput: "stable",
|
|
154
|
-
hybridOutput: "stable",
|
|
155
|
-
staticOutput: "unsupported",
|
|
156
|
-
i18nDomains: "experimental",
|
|
157
|
-
sharpImageService: "unsupported",
|
|
158
|
-
envGetSecret: "stable",
|
|
159
|
-
},
|
|
160
|
-
});
|
|
161
|
-
},
|
|
162
|
-
"astro:build:setup": ({ vite, target }) => {
|
|
163
|
-
if (_buildOutput === "static") {
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
if (target === "server") {
|
|
167
|
-
vite.resolve ||= {};
|
|
168
|
-
vite.resolve.alias ||= {};
|
|
169
|
-
vite.resolve.conditions ||= [];
|
|
170
|
-
// We need those conditions, previous these conditions where applied at the esbuild step which we removed
|
|
171
|
-
// https://github.com/withastro/astro/pull/7092
|
|
172
|
-
vite.resolve.conditions.push("workerd", "worker");
|
|
173
|
-
vite.ssr ||= {};
|
|
174
|
-
vite.ssr.target = "webworker";
|
|
175
|
-
vite.ssr.noExternal = true;
|
|
176
|
-
if (typeof _config.vite.ssr?.external === "undefined")
|
|
177
|
-
vite.ssr.external = ["node:async_hooks"];
|
|
178
|
-
if (typeof _config.vite.ssr?.external === "boolean")
|
|
179
|
-
vite.ssr.external = _config.vite.ssr?.external;
|
|
180
|
-
if (Array.isArray(_config.vite.ssr?.external)) {
|
|
181
|
-
// `@astrojs/vue` sets `@vue/server-renderer` to external
|
|
182
|
-
// https://github.com/withastro/astro/blob/e648c5575a8774af739231cfa9fc27a32086aa5f/packages/integrations/vue/src/index.ts#L119
|
|
183
|
-
// the cloudflare adapter needs to get all dependencies inlined, we use `noExternal` for that, but any `external` config overrides that
|
|
184
|
-
// therefore we need to remove `@vue/server-renderer` from the external config again
|
|
185
|
-
vite.ssr.external = _config.vite.ssr?.external.filter((entry) => entry !== "@vue/server-renderer");
|
|
186
|
-
vite.ssr.external.push("node:async_hooks");
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
// we thought that vite config inside `if (target === 'server')` would not apply for client
|
|
190
|
-
// but it seems like the same `vite` reference is used for both
|
|
191
|
-
// so we need to reset the previous conflicting setting
|
|
192
|
-
// in the future we should look into a more robust solution
|
|
193
|
-
if (target === "client") {
|
|
194
|
-
vite.resolve ||= {};
|
|
195
|
-
vite.resolve.conditions ||= [];
|
|
196
|
-
vite.resolve.conditions = vite.resolve.conditions.filter((c) => c !== "workerd" && c !== "worker");
|
|
197
|
-
}
|
|
198
|
-
},
|
|
199
|
-
"astro:build:done": async (buildResult) => {
|
|
200
|
-
const hasPages = buildResult.pages.length > 0;
|
|
201
|
-
const buildOutputType = _buildOutput === "static"
|
|
202
|
-
? "static"
|
|
203
|
-
: hasPages
|
|
204
|
-
? "hybrid"
|
|
205
|
-
: "server-only";
|
|
206
|
-
const moveToClientDir = async () => {
|
|
207
|
-
const clientDir = path.join(_config.outDir.pathname, "client");
|
|
208
|
-
await fs.mkdir(clientDir, { recursive: true });
|
|
209
|
-
// Move all files except "client" directory
|
|
210
|
-
const files = await fs.readdir(_config.outDir.pathname);
|
|
211
|
-
await Promise.all(files
|
|
212
|
-
.filter((file) => file !== "client")
|
|
213
|
-
.map((file) => fs.rename(path.join(_config.outDir.pathname, file), path.join(clientDir, file))));
|
|
214
|
-
};
|
|
215
|
-
if (_buildOutput === "static") {
|
|
216
|
-
try {
|
|
217
|
-
await moveToClientDir();
|
|
218
|
-
}
|
|
219
|
-
catch (ex) {
|
|
220
|
-
console.error(`@wix/astro failed to move files to client directory: ${ex.message}`);
|
|
221
|
-
throw ex;
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
const metadata = {
|
|
225
|
-
envName: process.env["ENV_NAME"],
|
|
226
|
-
buildOutputType,
|
|
227
|
-
};
|
|
228
|
-
await fs.writeFile(path.join(_config.outDir.pathname, ".wix-build-metadata.json"), JSON.stringify(metadata, null, 2) // More conventional JSON formatting
|
|
229
|
-
);
|
|
230
|
-
},
|
|
231
|
-
},
|
|
232
|
-
};
|
|
233
|
-
}
|
package/dist/loaders/blog.d.ts
DELETED
package/dist/loaders/blog.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { categories, posts, tags } from "@wix/blog";
|
|
2
|
-
import { media } from "@wix/sdk";
|
|
3
|
-
import { getWixClient } from "../client.js";
|
|
4
|
-
var PostFieldField;
|
|
5
|
-
(function (PostFieldField) {
|
|
6
|
-
PostFieldField["RICH_CONTENT"] = "RICH_CONTENT";
|
|
7
|
-
PostFieldField["CONTENT_TEXT"] = "CONTENT_TEXT";
|
|
8
|
-
})(PostFieldField || (PostFieldField = {}));
|
|
9
|
-
export function wixBlogLoader(transform = (item) => item) {
|
|
10
|
-
return {
|
|
11
|
-
name: "wix-blog-loader",
|
|
12
|
-
load: async (context) => {
|
|
13
|
-
const { items } = await getWixClient()
|
|
14
|
-
.use(posts)
|
|
15
|
-
.queryPosts({
|
|
16
|
-
fieldsets: [PostFieldField.RICH_CONTENT, PostFieldField.CONTENT_TEXT],
|
|
17
|
-
})
|
|
18
|
-
.find();
|
|
19
|
-
const useCategories = getWixClient().use(categories);
|
|
20
|
-
const useTags = getWixClient().use(tags);
|
|
21
|
-
for (const item of items) {
|
|
22
|
-
const categories = await Promise.all((item.categoryIds || []).map(async (categoryId) => {
|
|
23
|
-
const { category } = await useCategories.getCategory(categoryId);
|
|
24
|
-
return category;
|
|
25
|
-
}));
|
|
26
|
-
const { items: tags } = await useTags.queryTags().find();
|
|
27
|
-
const data = transform({
|
|
28
|
-
...item,
|
|
29
|
-
// Additions
|
|
30
|
-
...(item.media?.wixMedia?.image && {
|
|
31
|
-
mediaUrl: media.getImageUrl(item.media?.wixMedia?.image).url,
|
|
32
|
-
}),
|
|
33
|
-
categories,
|
|
34
|
-
tags,
|
|
35
|
-
});
|
|
36
|
-
const digest = context.generateDigest(data);
|
|
37
|
-
context.store.set({
|
|
38
|
-
id: data.id,
|
|
39
|
-
data,
|
|
40
|
-
digest,
|
|
41
|
-
rendered: {
|
|
42
|
-
html: item.contentText || "",
|
|
43
|
-
},
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
},
|
|
47
|
-
};
|
|
48
|
-
}
|
package/dist/loaders/index.d.ts
DELETED
package/dist/loaders/index.js
DELETED
package/dist/middleware.d.ts
DELETED
package/dist/middleware.js
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
/// <reference types="astro/client" />
|
|
2
|
-
import { OAuthStrategy, TokenRole, createClient } from "@wix/sdk";
|
|
3
|
-
import { z } from "astro/zod";
|
|
4
|
-
import { WIX_CLIENT_ID } from "astro:env/client";
|
|
5
|
-
import { defineMiddleware } from "astro:middleware";
|
|
6
|
-
import { authStrategyAsyncLocalStorage } from "./auth-context.js";
|
|
7
|
-
import { sessionCookieJson } from "./routes/auth/runtime.js";
|
|
8
|
-
const sessionClient = createClient({
|
|
9
|
-
auth: {
|
|
10
|
-
async getAuthHeaders() {
|
|
11
|
-
const auth = authStrategyAsyncLocalStorage.getStore()?.auth;
|
|
12
|
-
if (!auth) {
|
|
13
|
-
throw new Error("No authentication strategy found in the current context");
|
|
14
|
-
}
|
|
15
|
-
return auth.getAuthHeaders();
|
|
16
|
-
},
|
|
17
|
-
},
|
|
18
|
-
});
|
|
19
|
-
sessionClient.enableContext("global");
|
|
20
|
-
/**
|
|
21
|
-
* Checks if the incoming request is a request for a dynamic (server-side rendered) page.
|
|
22
|
-
* We can check this by looking at the middleware's `clientAddress` context property because accessing
|
|
23
|
-
* this prop in a static route will throw an error which we can conveniently catch.
|
|
24
|
-
*/
|
|
25
|
-
function checkIsDynamicPageRequest(context) {
|
|
26
|
-
try {
|
|
27
|
-
return context.clientAddress != null;
|
|
28
|
-
}
|
|
29
|
-
catch {
|
|
30
|
-
return false;
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
function getSessionTokensFromCookie(context) {
|
|
34
|
-
if (!checkIsDynamicPageRequest(context)) {
|
|
35
|
-
return;
|
|
36
|
-
}
|
|
37
|
-
const rawCookie = context.cookies.get("wixSession")?.json();
|
|
38
|
-
if (rawCookie) {
|
|
39
|
-
const tokensParseResult = z
|
|
40
|
-
.object({
|
|
41
|
-
clientId: z.string(),
|
|
42
|
-
tokens: z.object({
|
|
43
|
-
accessToken: z.object({
|
|
44
|
-
value: z.string(),
|
|
45
|
-
expiresAt: z.number(),
|
|
46
|
-
}),
|
|
47
|
-
refreshToken: z.object({
|
|
48
|
-
value: z.string(),
|
|
49
|
-
role: z.nativeEnum(TokenRole),
|
|
50
|
-
}),
|
|
51
|
-
}),
|
|
52
|
-
})
|
|
53
|
-
.safeParse(rawCookie);
|
|
54
|
-
if (tokensParseResult.success &&
|
|
55
|
-
tokensParseResult.data.clientId === WIX_CLIENT_ID) {
|
|
56
|
-
return tokensParseResult.data;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
function saveSessionTokensToCookie(context, tokens) {
|
|
61
|
-
context.cookies.set("wixSession", sessionCookieJson(tokens), {
|
|
62
|
-
secure: true,
|
|
63
|
-
path: "/",
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
export const onRequest = defineMiddleware(async (context, next) => {
|
|
67
|
-
if (!WIX_CLIENT_ID) {
|
|
68
|
-
return next();
|
|
69
|
-
}
|
|
70
|
-
const sessionTokensFromCookie = getSessionTokensFromCookie(context);
|
|
71
|
-
const auth = OAuthStrategy({
|
|
72
|
-
clientId: WIX_CLIENT_ID,
|
|
73
|
-
});
|
|
74
|
-
if (sessionTokensFromCookie) {
|
|
75
|
-
auth.setTokens(sessionTokensFromCookie.tokens);
|
|
76
|
-
}
|
|
77
|
-
else {
|
|
78
|
-
auth.setTokens(await auth.generateVisitorTokens());
|
|
79
|
-
}
|
|
80
|
-
const response = await authStrategyAsyncLocalStorage.run({
|
|
81
|
-
auth,
|
|
82
|
-
}, () => next());
|
|
83
|
-
if (checkIsDynamicPageRequest(context) &&
|
|
84
|
-
sessionTokensFromCookie?.tokens.accessToken.expiresAt !==
|
|
85
|
-
auth.getTokens().accessToken.expiresAt) {
|
|
86
|
-
saveSessionTokensToCookie(context, auth.getTokens());
|
|
87
|
-
}
|
|
88
|
-
return response;
|
|
89
|
-
});
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import pRetry from "p-retry";
|
|
2
|
-
import { getAuth } from "../../runtime.server.js";
|
|
3
|
-
import { OAUTH_COOKIE_STATE, WIX_LOGIN_REDIRECT } from "./constants.js";
|
|
4
|
-
import { sessionCookieJson } from "./runtime.js";
|
|
5
|
-
export const prerender = false;
|
|
6
|
-
export async function GET({ url, cookies, redirect }) {
|
|
7
|
-
// Retrieve the OauthData from cookies
|
|
8
|
-
const oauthStateCookie = cookies.get(OAUTH_COOKIE_STATE);
|
|
9
|
-
const oauthData = oauthStateCookie ? JSON.parse(oauthStateCookie.value) : {};
|
|
10
|
-
// Determine the original URL or default to home
|
|
11
|
-
const originalUrl = oauthData.originalUri || "/";
|
|
12
|
-
// Check for error in the request URL
|
|
13
|
-
if (url.href.includes("error=")) {
|
|
14
|
-
return new Response(null, {
|
|
15
|
-
status: 302,
|
|
16
|
-
headers: {
|
|
17
|
-
Location: originalUrl,
|
|
18
|
-
},
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
// Parse state and code from the request URL
|
|
22
|
-
const parsedUrl = new URL(url);
|
|
23
|
-
const state = parsedUrl.searchParams.get("state") || "";
|
|
24
|
-
const code = parsedUrl.searchParams.get("code") || "";
|
|
25
|
-
try {
|
|
26
|
-
// Retrieve member tokens using the code, state, and oauthData
|
|
27
|
-
const auth = getAuth();
|
|
28
|
-
const memberTokens = await pRetry(() => auth.getMemberTokens(code, state, oauthData), {
|
|
29
|
-
retries: 3,
|
|
30
|
-
onFailedAttempt: (error) => {
|
|
31
|
-
console.error("Error getting member tokens", error);
|
|
32
|
-
},
|
|
33
|
-
});
|
|
34
|
-
cookies.delete(OAUTH_COOKIE_STATE);
|
|
35
|
-
cookies.delete(WIX_LOGIN_REDIRECT);
|
|
36
|
-
cookies.set("wixSession", sessionCookieJson(memberTokens), {
|
|
37
|
-
maxAge: 60 * 60 * 24 * 2,
|
|
38
|
-
path: "/",
|
|
39
|
-
secure: true,
|
|
40
|
-
});
|
|
41
|
-
return redirect(originalUrl);
|
|
42
|
-
}
|
|
43
|
-
catch (error) {
|
|
44
|
-
console.error("Authentication error:", error);
|
|
45
|
-
return new Response(null, {
|
|
46
|
-
status: 302,
|
|
47
|
-
headers: {
|
|
48
|
-
Location: "/?authError=true",
|
|
49
|
-
},
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
}
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
export declare const PROMPT_QUERY_PARAM = "prompt";
|
|
2
|
-
export declare const AUTH_LOGIN_CALLBACK_PARAM = "returnToUrl";
|
|
3
|
-
export declare const OAUTH_COOKIE_STATE = "oAuthState";
|
|
4
|
-
export declare const AUTH_CALLBACK_PATHNAME = "/api/auth/callback";
|
|
5
|
-
export declare const WIX_LOGIN_REDIRECT = "wixLoginRedirect";
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { AUTH_CALLBACK_PATHNAME, AUTH_LOGIN_CALLBACK_PARAM, OAUTH_COOKIE_STATE, PROMPT_QUERY_PARAM, } from "./constants.js";
|
|
2
|
-
import { getAuth } from "../../runtime.server.js";
|
|
3
|
-
export const prerender = false;
|
|
4
|
-
export async function GET({ url }) {
|
|
5
|
-
// Extract search parameters from the URL
|
|
6
|
-
const searchParams = new URL(url).searchParams;
|
|
7
|
-
const originalUrl = searchParams.get(AUTH_LOGIN_CALLBACK_PARAM) || "/";
|
|
8
|
-
const prompt = searchParams.get(PROMPT_QUERY_PARAM) ??
|
|
9
|
-
"login";
|
|
10
|
-
// Generate OAuth data and authorization URL
|
|
11
|
-
const redirectUrl = new URL(AUTH_CALLBACK_PATHNAME, url).toString();
|
|
12
|
-
const oauthData = await getAuth().generateOAuthData(redirectUrl, originalUrl);
|
|
13
|
-
const { authUrl } = await getAuth().getAuthUrl(oauthData, {
|
|
14
|
-
prompt,
|
|
15
|
-
responseMode: "query",
|
|
16
|
-
});
|
|
17
|
-
// Create a response that redirects to the authorization URL
|
|
18
|
-
const response = new Response(null, {
|
|
19
|
-
status: 302,
|
|
20
|
-
headers: {
|
|
21
|
-
Location: authUrl,
|
|
22
|
-
"Set-Cookie": `${OAUTH_COOKIE_STATE}=${JSON.stringify(oauthData)}; Max-Age=1800; Path=/; HttpOnly; SameSite=Lax`,
|
|
23
|
-
},
|
|
24
|
-
});
|
|
25
|
-
return response;
|
|
26
|
-
}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { getAuth } from "../../runtime.server.js";
|
|
2
|
-
import { sessionCookieJson } from "./runtime.js";
|
|
3
|
-
export const prerender = false;
|
|
4
|
-
export const GET = async ({ request, redirect, cookies }) => {
|
|
5
|
-
const returnTo = new URL(request.url).searchParams.get("returnTo") ?? "/";
|
|
6
|
-
const tokens = await getAuth().generateVisitorTokens();
|
|
7
|
-
cookies.set("wixSession", sessionCookieJson(tokens));
|
|
8
|
-
return redirect(returnTo);
|
|
9
|
-
};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { getAuth } from "../../runtime.server.js";
|
|
2
|
-
export const prerender = false;
|
|
3
|
-
export async function GET({ request, redirect }) {
|
|
4
|
-
const returnTo = request.headers.get("Referer") ?? "/";
|
|
5
|
-
const baseUrl = new URL(request.url).origin + "/" + import.meta.env.BASE_URL;
|
|
6
|
-
const postFlowUrl = new URL("/api/auth/logout-callback", baseUrl);
|
|
7
|
-
postFlowUrl.searchParams.set("returnTo", returnTo);
|
|
8
|
-
const { logoutUrl } = await getAuth().logout(postFlowUrl.toString());
|
|
9
|
-
return redirect(logoutUrl);
|
|
10
|
-
}
|
package/dist/runtime-client.d.ts
DELETED
package/dist/runtime-client.js
DELETED
package/dist/runtime.client.d.ts
DELETED
package/dist/runtime.client.js
DELETED