@redeemid/emdash 0.0.14 → 0.0.15

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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Shopify customer accounts, member levels and paywalls for [EmDash](https://github.com/emdash-cms/emdash) sites. Shopify runs the store and the customer account; EmDash runs the content.
4
4
 
5
- **Status: 0.0.14, early.** Runs on Node and Cloudflare Workers. Sign-in, the member mirror, webhooks, levels, rules, the meter and drip, teasers, paywall markup, badges, the page gate, the Shopify cart and checkout, the staff tools, preferences, protected files, privacy requests, AI agent tools, the command line, replacement text and outbound events are covered by an end-to-end test against a fake store.
5
+ **Status: 0.0.15, early.** Runs on Node and Cloudflare Workers. Sign-in, the member mirror, webhooks, levels, rules, the meter and drip, teasers, paywall markup, badges, the page gate, the Shopify cart and checkout, the staff tools, preferences, protected files, privacy requests, AI agent tools, the command line, replacement text and outbound events are covered by an end-to-end test against a fake store.
6
6
 
7
7
  ## What it does
8
8
 
@@ -296,7 +296,7 @@ With `REDEEMID_SHOPIFY_ADMIN_APP_CLIENT_ID` set (it also runs member preferences
296
296
 
297
297
  - **Member detail.** Open a member from the Members page to see their levels, tags and features, resync them from Shopify, or add and remove tags. Tag edits are made in Shopify, then read back; nothing is granted on the EmDash side.
298
298
  - **Bulk resync.** Reads the 25 members synced longest ago from Shopify in one request, few enough for the Workers Free limit of 50 database queries a request. Run it again for the next 25. It never runs on its own.
299
- - **Webhooks.** The Status page lists the store's subscriptions to this site and registers any that are missing (`customers/redact` stays in the app's own settings).
299
+ - **Webhooks.** The Status page lists the store's subscriptions to this site and registers any that are missing (`customers/redact` stays in the app's own settings). A topic Shopify refuses, such as `customers/merge` without the `read_customer_merge` scope, is named with the reason and doesn't stop the others.
300
300
  - **Recent deliveries.** The last webhooks the site took, with their topics and times.
301
301
  - **Access test.** Enter a collection, terms and a reader's tags to see what the entry needs and whether that reader gets in.
302
302
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redeemid/emdash",
3
- "version": "0.0.14",
3
+ "version": "0.0.15",
4
4
  "description": "Shopify customer accounts, member levels and paywalls for EmDash sites. Shopify runs commerce; EmDash runs content.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/admin-api.ts CHANGED
@@ -176,10 +176,22 @@ export async function webhookSubscriptions(config: RedeemIDConfig, fetcher: type
176
176
  return data.webhookSubscriptions.nodes.map((n) => ({ id: n.id, topic: n.topic, uri: n.uri ?? "" }));
177
177
  }
178
178
 
179
- /** Register the topics RedeemID needs that no subscription sends to `uri` yet. Returns the topics it added. */
180
- export async function registerWebhooks(config: RedeemIDConfig, uri: string, fetcher: typeof fetch = fetch): Promise<string[]> {
179
+ /** Scopes a topic needs beyond read_customers, to explain a refusal. */
180
+ const TOPIC_SCOPES: Partial<Record<(typeof WEBHOOK_TOPICS)[number], string>> = { CUSTOMERS_MERGE: "read_customer_merge" };
181
+
182
+ /**
183
+ * Register the topics RedeemID needs that no subscription sends to `uri` yet.
184
+ * A topic Shopify refuses doesn't stop the others: it comes back in `failed`.
185
+ */
186
+ export async function registerWebhooks(
187
+ config: RedeemIDConfig,
188
+ uri: string,
189
+ fetcher: typeof fetch = fetch,
190
+ ): Promise<{ added: string[]; failed: Array<{ topic: string; message: string }> }> {
181
191
  const have = await webhookSubscriptions(config, fetcher);
182
192
  const missing = WEBHOOK_TOPICS.filter((t) => !have.some((h) => h.topic === t && h.uri === uri));
193
+ const added: string[] = [];
194
+ const failed: Array<{ topic: string; message: string }> = [];
183
195
  for (const topic of missing) {
184
196
  const data = await admin<{ webhookSubscriptionCreate: { userErrors: Array<{ message: string }> } }>(
185
197
  config,
@@ -188,7 +200,8 @@ export async function registerWebhooks(config: RedeemIDConfig, uri: string, fetc
188
200
  fetcher,
189
201
  );
190
202
  const err = data.webhookSubscriptionCreate.userErrors[0];
191
- if (err) throw new AdminError(`${topic}: ${err.message}`);
203
+ if (!err) added.push(topic);
204
+ else failed.push({ topic, message: TOPIC_SCOPES[topic] ? `${err.message} (the app needs the ${TOPIC_SCOPES[topic]} scope)` : err.message });
192
205
  }
193
- return [...missing];
206
+ return { added, failed };
194
207
  }
@@ -16,6 +16,7 @@ const DEFAULTS: Record<string, string> = {
16
16
  sign_in_unavailable: "Sign-in isn't available right now. Try again in a few minutes.",
17
17
  sign_in_expired: "That sign-in took too long. Try again.",
18
18
  staff_account: "This account can't sign in here. Use a different email.",
19
+ account_disabled: "Your account is turned off. Contact the store for help.",
19
20
  site_not_ready: "This site isn't ready for sign-in yet.",
20
21
  email_required: "Your account needs an email address to sign in.",
21
22
  token_failed: "Sign-in didn't finish. Try again.",
package/src/guard.ts CHANGED
@@ -24,6 +24,7 @@ import { defineMiddleware } from "astro:middleware";
24
24
  import { signInUrl } from "./access.js";
25
25
  import { readCart } from "./cart.js";
26
26
  import { keysFromPath, pathAccess, refusal } from "./files.js";
27
+ import { AFTER_LOGOUT_COOKIE, readAfterLogout } from "./routes/shared.js";
27
28
  import { siteConfig } from "./site-config.js";
28
29
 
29
30
  const SUBSCRIBER = 10;
@@ -98,6 +99,16 @@ export const onRequest = defineMiddleware(async (context, next) => {
98
99
  }
99
100
  }
100
101
 
102
+ // Back from ending the store session after a refused sign-in.
103
+ if (url.pathname === "/" && !url.searchParams.has("redeemid_notice")) {
104
+ const after = readAfterLogout(context.cookies.get(AFTER_LOGOUT_COOKIE)?.value);
105
+ if (after) {
106
+ const sep = after.returnTo.includes("?") ? "&" : "?";
107
+ const location = `${after.returnTo}${sep}redeemid_notice=${encodeURIComponent(after.code)}`;
108
+ return new Response(null, { status: 302, headers: { location, "cache-control": "private, no-store", "set-cookie": `${AFTER_LOGOUT_COOKIE}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax` } });
109
+ }
110
+ }
111
+
101
112
  if (!url.pathname.startsWith("/_emdash")) {
102
113
  const own = Boolean(user) || Boolean(await readCart(context.session as never).catch(() => null));
103
114
  return own ? keepPrivate(context, await next()) : next();
package/src/plugin.ts CHANGED
@@ -342,8 +342,10 @@ async function action(
342
342
  }
343
343
  case "webhooks_register": {
344
344
  try {
345
- const added = await registerWebhooks(config, webhookUri(request));
346
- return { ...(await statusPage(config, request)), toast: { type: "success", message: added.length ? `Registered ${added.length} webhooks.` : "Nothing was missing." } };
345
+ const { added, failed } = await registerWebhooks(config, webhookUri(request));
346
+ const done = added.length ? `Registered ${added.length} webhooks.` : failed.length ? "" : "Nothing was missing.";
347
+ const refused = failed.map((f) => `Shopify refused ${f.topic}: ${f.message}`).join(" ");
348
+ return { ...(await statusPage(config, request)), toast: { type: failed.length ? "error" : "success", message: [done, refused].filter(Boolean).join(" ") } };
347
349
  } catch (e) {
348
350
  return { ...(await statusPage(config, request)), toast: fail(e) };
349
351
  }
@@ -12,15 +12,16 @@
12
12
  import { findOrCreateOAuthUser, OAuthError, Role } from "@emdash-cms/auth";
13
13
  import { createKyselyAdapter, type AuthTables } from "@emdash-cms/auth/adapters/kysely";
14
14
  import type { APIRoute } from "astro";
15
- import { OptionsRepository } from "emdash/api/route-utils";
16
15
  import type { Kysely } from "kysely";
17
16
 
18
17
  import { env, ENV, PROVIDER_ID, readConfig, storeDomain } from "../config.js";
19
18
  import { emit, levelChange } from "../events.js";
20
19
  import { levelsFor } from "../access.js";
21
- import { discover, exchangeCode, identity, ShopifyError, verifyIdToken } from "../shopify.js";
20
+ import { discover, exchangeCode, identity, logoutUrl, ShopifyError, verifyIdToken, type Discovery } from "../shopify.js";
22
21
  import { emptyMember, stampTags, stores } from "../storage.js";
23
- import { callbackUrl, fail, FLOW_TTL_MS, SESSION_FLOW, SESSION_ID_TOKEN, type Flow } from "./shared.js";
22
+ import { getPublicOrigin, OptionsRepository } from "emdash/api/route-utils";
23
+
24
+ import { afterLogoutCookie, callbackUrl, fail, FLOW_TTL_MS, SESSION_FLOW, SESSION_ID_TOKEN, type Flow } from "./shared.js";
24
25
 
25
26
  export const prerender = false;
26
27
 
@@ -63,10 +64,13 @@ export const GET: APIRoute = async ({ request, locals, session, redirect }) => {
63
64
  verifier: flow.verifier,
64
65
  });
65
66
  const claims = await verifyIdToken(d, tokens.idToken, { clientId, nonce: flow.nonce });
67
+ // Refusals from here on also end the store session, so the next Sign in
68
+ // asks for an email again instead of reusing this account.
69
+ const refuse = (code: string) => signedOut(d, tokens.idToken, url, emdash.config, returnTo, code) ?? fail(redirect, returnTo, code);
66
70
  const who = await identity(d, tokens.accessToken);
67
71
 
68
72
  const email = (typeof claims.email === "string" ? claims.email : who.email)?.toLowerCase() ?? null;
69
- if (!email) return fail(redirect, returnTo, "email_required");
73
+ if (!email) return refuse("email_required");
70
74
  const emailVerified = claims.email_verified === true;
71
75
 
72
76
  const adapter = createKyselyAdapter(emdash.db as Kysely<AuthTables>);
@@ -74,7 +78,7 @@ export const GET: APIRoute = async ({ request, locals, session, redirect }) => {
74
78
  // Staff accounts never sign in through the store, even with the same email.
75
79
  const linked = await adapter.getOAuthAccount(PROVIDER_ID, who.customerId);
76
80
  const existing = linked ? await adapter.getUserById(linked.userId) : await adapter.getUserByEmail(email);
77
- if (existing && existing.role > Role.SUBSCRIBER) return fail(redirect, returnTo, "staff_account");
81
+ if (existing && existing.role > Role.SUBSCRIBER) return refuse("staff_account");
78
82
 
79
83
  const name = [who.firstName, who.lastName].filter(Boolean).join(" ") || null;
80
84
  const user = await findOrCreateOAuthUser(
@@ -84,8 +88,8 @@ export const GET: APIRoute = async ({ request, locals, session, redirect }) => {
84
88
  async () => ({ allowed: true, role: Role.SUBSCRIBER }),
85
89
  { requireVerifiedEmail: true },
86
90
  );
87
- if (user.disabled) return fail(redirect, returnTo, "account_disabled");
88
- if (user.role > Role.SUBSCRIBER) return fail(redirect, returnTo, "staff_account");
91
+ if (user.disabled) return refuse("account_disabled");
92
+ if (user.role > Role.SUBSCRIBER) return refuse("staff_account");
89
93
 
90
94
  const s = stores(emdash.db);
91
95
  const found = await s.members.get(who.customerId);
@@ -123,3 +127,11 @@ export const GET: APIRoute = async ({ request, locals, session, redirect }) => {
123
127
  return fail(redirect, returnTo, code);
124
128
  }
125
129
  };
130
+
131
+ /** Ends the store session, then shows `code` on `returnTo` (see AFTER_LOGOUT_COOKIE). */
132
+ function signedOut(d: Discovery, idToken: string, url: URL, emdashConfig: unknown, returnTo: string, code: string): Response | null {
133
+ const origin = getPublicOrigin(url, emdashConfig as Parameters<typeof getPublicOrigin>[1]);
134
+ const to = logoutUrl(d, idToken, `${origin}/`);
135
+ if (!to) return null;
136
+ return new Response(null, { status: 302, headers: { location: to, "set-cookie": afterLogoutCookie(code, returnTo), "cache-control": "private, no-store" } });
137
+ }
@@ -26,3 +26,29 @@ export function fail(redirect: (to: string) => Response, returnTo: string, code:
26
26
  const sep = returnTo.includes("?") ? "&" : "?";
27
27
  return redirect(`${returnTo}${sep}redeemid_notice=${encodeURIComponent(code)}`);
28
28
  }
29
+
30
+ /**
31
+ * A refused sign-in also ends the store session, or the next Sign in would
32
+ * pass straight through with the same account. Shopify only returns to the
33
+ * site root after that, so this short cookie carries the notice and the page
34
+ * back; the guard middleware turns it into the usual `?redeemid_notice=`.
35
+ */
36
+ export const AFTER_LOGOUT_COOKIE = "redeemid_after_logout";
37
+ export const SIGNED_OUT_NOTICES = ["staff_account", "account_disabled", "email_required"] as const;
38
+
39
+ export function afterLogoutCookie(code: string, returnTo: string): string {
40
+ return `${AFTER_LOGOUT_COOKIE}=${encodeURIComponent(JSON.stringify([code, returnTo]))}; Path=/; Max-Age=600; HttpOnly; Secure; SameSite=Lax`;
41
+ }
42
+
43
+ /** The notice and page a refused sign-in left, or null. */
44
+ export function readAfterLogout(raw: string | undefined): { code: string; returnTo: string } | null {
45
+ if (!raw) return null;
46
+ try {
47
+ const [code, returnTo] = JSON.parse(decodeURIComponent(raw)) as [unknown, unknown];
48
+ if (typeof code !== "string" || !(SIGNED_OUT_NOTICES as readonly string[]).includes(code)) return null;
49
+ const to = typeof returnTo === "string" && returnTo.startsWith("/") && !returnTo.startsWith("//") && !returnTo.startsWith("/\\") ? returnTo : "/";
50
+ return { code, returnTo: to };
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
package/src/text.ts CHANGED
@@ -84,6 +84,7 @@ export const STRINGS = {
84
84
  "Sign-in isn't available right now. Try again in a few minutes.",
85
85
  "That sign-in took too long. Try again.",
86
86
  "This account can't sign in here. Use a different email.",
87
+ "Your account is turned off. Contact the store for help.",
87
88
  "This site isn't ready for sign-in yet.",
88
89
  "Your account needs an email address to sign in.",
89
90
  "Sign-in didn't finish. Try again.",
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.0.14";
1
+ export const VERSION = "0.0.15";