Skip to content

Commit

Permalink
update: packages
Browse files Browse the repository at this point in the history
  • Loading branch information
chr33s committed Jan 7, 2024
1 parent 58eae63 commit 8bfe9b7
Show file tree
Hide file tree
Showing 18 changed files with 1,090 additions and 1,988 deletions.
2 changes: 1 addition & 1 deletion functions/api/auth/callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const onRequestGet: PagesFunction<Env> = async (context) => {
if (config.isOnline) {
shopify(context).logger.debug(
"Completing offline token OAuth, redirecting to online token OAuth",
{ shop: session.shop }
{ shop: session.shop },
);

return redirectToAuth(context, true);
Expand Down
4 changes: 2 additions & 2 deletions functions/api/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const resolvers = {
plan: string;
};
},
context: any
context: any,
) => {
const confirmationUrl = await saveBillingPlan(context, args.input.plan);
return { confirmationUrl };
Expand All @@ -30,7 +30,7 @@ const resolvers = {
...(v as any),
name: k,
}),
[]
[],
);
return billingPlans;
},
Expand Down
28 changes: 2 additions & 26 deletions functions/api/proxy/graphql/storefront.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,9 @@
import type { Env } from "@/functions/types";
import { config, getSession, shopify } from "@/lib/shopify";
import { getSession, shopify } from "@/lib/shopify";

export const onRequestPost: PagesFunction<Env> = async (context) => {
const session: any = await getSession(context, true);

const admin = new (shopify(context).clients.Rest)({ session });
const storefrontAccessToken = await admin
.get<{
storefront_access_tokens: {
access_token: string;
title: string;
}[];
}>({
path: "storefront_access_tokens",
})
.then(
(res) =>
res.body.storefront_access_tokens.find(
(v) => v.title === config.storefrontAccessTokenTitle
)?.access_token
);
if (!storefrontAccessToken) {
return new Response("No storefront token found", { status: 403 });
}

const storefront = new (shopify(context).clients.Storefront)({
domain: session?.shop,
storefrontAccessToken,
});
const storefront = new (shopify(context).clients.Storefront)({ session });
const data: string = await context.request.json();
const response: any = await storefront.query({ data });

Expand Down
4 changes: 2 additions & 2 deletions functions/api/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ export const onRequestPost: PagesFunction<Env> = async (context) => {
prorate: config.billingProrate,
session,
subscriptionId: subscription.id,
})
)
}),
),
);

await deleteSessionsFromStorage(context, shop);
Expand Down
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
Expand Down
2 changes: 1 addition & 1 deletion lib/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const errorHandling: PagesFunction<Env> = async (context) => {
stack: err.stack,
status: "nok",
}),
{ status: 500 }
{ status: 500 },
);
}
};
60 changes: 30 additions & 30 deletions lib/shopify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function addSessionToStorage(context: Context, session: Session) {
await context.env.SHOPFLARE_KV.put(
getSessionKey(session.id),
JSON.stringify(session.toObject()),
{ metadata: { shop: session.shop } }
{ metadata: { shop: session.shop } },
);
}

Expand All @@ -76,22 +76,22 @@ export async function checkBillingPlan(context: Context) {

export async function deleteSessionsFromStorage(
context: Context,
shop: string
shop: string,
) {
const sessions = await context.env.SHOPFLARE_KV.list({
prefix: getSessionKey(""),
}).then(({ keys }) =>
keys.filter((session) => (session.metadata as any)?.shop === shop)
keys.filter((session) => (session.metadata as any)?.shop === shop),
);

return await Promise.all(
sessions.map((session) => context.env.SHOPFLARE_KV.delete(session.name))
sessions.map((session) => context.env.SHOPFLARE_KV.delete(session.name)),
);
}

async function embedAppIntoShopify(
context: Context,
shop: string
shop: string,
): Promise<Response> {
let embeddedUrl: string;
try {
Expand All @@ -101,15 +101,15 @@ async function embedAppIntoShopify(
} catch (error) {
shopify(context).logger.error(
`ensureInstalledOnShop did not receive a host query argument`,
{ shop }
{ shop },
);

return new Response("No host provided", { status: 400 });
}

shopify(context).logger.debug(
`Request is not embedded but app is. Redirecting to ${embeddedUrl} to embed the app`,
{ shop }
{ shop },
);

const { pathname } = new URL(context.request.url);
Expand All @@ -134,7 +134,7 @@ export async function ensureInstalledOnShop(context: Context) {

if (!config.isEmbeddedApp) {
shopify(context).logger.warning(
"ensureInstalledOnShop() should only be used in embedded apps; calling validateAuthenticatedSession() instead"
"ensureInstalledOnShop() should only be used in embedded apps; calling validateAuthenticatedSession() instead",
);

return validateAuthenticatedSession(context);
Expand Down Expand Up @@ -163,7 +163,7 @@ export async function ensureInstalledOnShop(context: Context) {
const session = await getSessionFromStorage(context, sessionId);
if (!session && context.request.url === config.exitIframePath) {
shopify(context).logger.debug(
"ensureInstalledOnShop() should only be used in embedded apps; calling validateAuthenticatedSession() instead"
"ensureInstalledOnShop() should only be used in embedded apps; calling validateAuthenticatedSession() instead",
);

return redirectToAuth(context);
Expand All @@ -176,7 +176,7 @@ export async function ensureInstalledOnShop(context: Context) {

shopify(context).logger.info(
"Found a session, but it is not valid. Redirecting to auth",
{ shop }
{ shop },
);

return redirectToAuth(context);
Expand All @@ -186,8 +186,8 @@ export async function ensureInstalledOnShop(context: Context) {
response.headers.set(
"Content-Security-Policy",
`frame-ancestors https://${encodeURIComponent(
shop
)} https://admin.shopify.com;`
shop,
)} https://admin.shopify.com;`,
);
} else {
response.headers.set("Content-Security-Policy", "frame-ancestors 'none';");
Expand All @@ -211,7 +211,7 @@ export async function getBillingPlanConfig(context: Context) {

export async function getSession(
context: Context,
isOnline: boolean = config.isOnline
isOnline: boolean = config.isOnline,
) {
const sessionId = await shopify(context).session.getCurrentId({
isOnline,
Expand All @@ -236,7 +236,7 @@ function getSessionKey(id: string) {

export async function getSessionFromStorage(
context: Context,
sessionId: string
sessionId: string,
): Promise<Session | undefined> {
const params = await context.env.SHOPFLARE_KV.get(getSessionKey(sessionId), {
type: "json",
Expand All @@ -253,20 +253,20 @@ function redirect(url: string, status = 302, headers: Headers = [] as any) {

export async function redirectToAuth(
context: Context,
isOnline: boolean = config.isOnline
isOnline: boolean = config.isOnline,
) {
const { searchParams } = new URL(context.request.url);

const shop = shopify(context).utils.sanitizeShop(
searchParams.get("shop") ?? ""
searchParams.get("shop") ?? "",
);
if (!shop) {
return new Response("No shop provided", { status: 500 });
}

async function clientSideRedirect() {
const host = shopify(context).utils.sanitizeHost(
searchParams.get("host") ?? ""
searchParams.get("host") ?? "",
);
if (!host) {
return new Response("No host provided", { status: 500 });
Expand All @@ -285,12 +285,12 @@ export async function redirectToAuth(
queryParams.set("shop", shop ?? "");
queryParams.set(
"redirectUri",
`${appHost}${config.authPath}?${redirectUriParams}`
`${appHost}${config.authPath}?${redirectUriParams}`,
);

shopify(context).logger.debug(
`Redirecting to auth while embedded, going to ${config.exitIframePath}`,
{ shop }
{ shop },
);

return redirect(`${config.exitIframePath}?${queryParams.toString()}`);
Expand All @@ -302,7 +302,7 @@ export async function redirectToAuth(
async function serverSideRedirect() {
shopify(context).logger.debug(
`Redirecting to auth at ${config.authPath}, with callback ${config.authCallbackPath}`,
{ shop, isOnline }
{ shop, isOnline },
);

return await shopify(context).auth.begin({
Expand All @@ -317,14 +317,14 @@ export async function redirectToAuth(

export async function registerWebhookHandlers(
context: Context,
session: Session
session: Session,
) {
shopify(context).webhooks.addHandlers(webhooks);
const response = await shopify(context).webhooks.register({
session,
});
const success = Object.values(response).every((res: any) =>
res.every((v: any) => v.success)
res.every((v: any) => v.success),
);
if (!success) {
const error = "Registering registerWebhookHandlers() failed";
Expand All @@ -344,7 +344,7 @@ export async function saveBillingPlan(context: Context, plan: string) {

async function sessionHasValidAccessToken(
context: Context,
session: Session | undefined
session: Session | undefined,
) {
if (!session) {
shopify(context).logger.debug("Request session not found");
Expand Down Expand Up @@ -384,7 +384,7 @@ async function sessionHasValidAccessToken(
`Could not check if session was valid: ${error}`,
{
shop: session.shop,
}
},
);

if (error instanceof HttpResponseError && error.response.code === 401) {
Expand Down Expand Up @@ -450,7 +450,7 @@ export async function validateAuthenticatedSession(context: Context) {
});
} catch (error: any) {
shopify(context).logger.error(
`Error when loading session from storage: ${error}`
`Error when loading session from storage: ${error}`,
);

switch (true) {
Expand All @@ -467,7 +467,7 @@ export async function validateAuthenticatedSession(context: Context) {
session = await getSessionFromStorage(context, sessionId ?? "");
} catch (error: any) {
shopify(context).logger.error(
`Error when loading session from storage: ${error}`
`Error when loading session from storage: ${error}`,
);

return new Response(error.message, { status: 500 });
Expand All @@ -476,12 +476,12 @@ export async function validateAuthenticatedSession(context: Context) {

const { searchParams } = new URL(context.request.url);
let shop = shopify(context).utils.sanitizeShop(
searchParams.get("shop") ?? ""
searchParams.get("shop") ?? "",
);
if (session && shop && session?.shop !== shop) {
shopify(context).logger.debug(
"Found a session for a different shop in the request",
{ currentShop: session.shop, requestShop: shop }
{ currentShop: session.shop, requestShop: shop },
);

return redirectToAuth(context);
Expand All @@ -500,14 +500,14 @@ export async function validateAuthenticatedSession(context: Context) {
shop = session.shop;
} else if (config.isEmbeddedApp) {
const payload = await shopify(context).session.decodeSessionToken(
bearerPresent?.[1]
bearerPresent?.[1],
);
shop = payload.dest.replace("https://", "");
}
}

const host = shopify(context).utils.sanitizeHost(
searchParams.get("host") ?? ""
searchParams.get("host") ?? "",
);
const redirectParams = new URLSearchParams({ host, shop } as any).toString();
const redirectUrl = `${config.authPath}?${redirectParams}`;
Expand Down

0 comments on commit 8bfe9b7

Please sign in to comment.