@aglyn/plugins-commerce 1.23.1 → 1.25.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.
@@ -130,7 +130,9 @@ const alreadyExists = (error)=>{
130
130
  // Owed to the recipient by their own order: the phishing
131
131
  // screen's soft rules never hold it (AGL-3356).
132
132
  owedFor: 'order'
133
- })).then(()=>true).catch(()=>false);
133
+ }))// A refused send (a sending limit, the outbound screen) RESOLVES with
134
+ // `sent: false`; it is not an emailed card (AGL-4227).
135
+ .then((outcome)=>Boolean(outcome == null ? void 0 : outcome.sent)).catch(()=>false);
134
136
  if (sent) {
135
137
  // Cost meter (AGL-1438). Transactional: the card has already been
136
138
  // minted and the recipient is owed the code, so a quota may count
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/gift-card-issue.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { randomBytes } from 'crypto'\nimport {\n hostSendingIdentity,\n logHostActivity,\n meterHostEmail,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport {\n GIFT_CARD_ISSUE_MAX_CENTS,\n giftCardAmountProblem,\n giftCardCodeProblem,\n} from '../model/commerce-gift-cards'\nimport { giftCardSearchTokens } from '../model/gift-card-search'\n\n/*\n * ISSUING A GIFT CARD (AGL-2226, AGL-3551): the one path a card comes into\n * being by a merchant's hand — the Gift cards card's Issue, one card at a\n * time, and the gift card import, one card per row. A sale's cards are\n * minted by the billing webhook from the order.\n *\n * What issuing is, wherever it is asked from:\n *\n * - the amount is above zero and at most {@link GIFT_CARD_ISSUE_MAX_CENTS};\n * - the code is minted, or a code the merchant brings (an import carries\n * the codes shoppers already hold) — and a code another card holds is\n * refused, never overwritten: the document is CREATED, so two issues of\n * one code cannot both land;\n * - the card records who issued it (`issuedBy`) and for how much\n * (`initialCents`), and the site's activity log gets a line naming it;\n * - the recipient is emailed the code only when asked, and the answer says\n * whether the email actually went.\n */\n\n/** A refusal the person can act on, with the status a route answers it with. */\nexport class GiftCardIssueRefusal extends Error {\n constructor(\n readonly status: number,\n readonly reason: 'amount' | 'code' | 'taken',\n message: string,\n ) {\n super(message)\n this.name = 'GiftCardIssueRefusal'\n }\n}\n\n/** `GC-` + 12 uppercase hex, the shape `billing-webhook.ts` also mints. */\nexport function mintGiftCardCode(): string {\n return `GC-${randomBytes(6).toString('hex').toUpperCase()}`\n}\n\n/** Where an imported card came from, so a retried row finds the card it already issued. */\nexport interface GiftCardIssueSource {\n importJobId: string\n importRow: number\n}\n\nexport interface IssueGiftCardInput {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n amountCents: number\n recipientEmail?: string | null\n note?: string | null\n /** A code the merchant brings; one is minted when absent. */\n code?: string | null\n /** Who issued it, for the card and the activity line. */\n issuer: { uid: string; email?: string | null }\n /** Email the recipient their code (when there is a recipient and mail is set up). */\n email: boolean\n /** The workspace that owns the site, for the email's sender name. */\n ownerOrg?: unknown\n source?: GiftCardIssueSource\n}\n\n/** What the activity log names a card by: never the whole code, which spends it. */\nexport function giftCardActivityName(code: string): string {\n return `Gift card ending ${code.slice(-4)}`\n}\n\n/** The activity target a card is filed under (`pluginId:noun`, AGL-2978). */\nexport const GIFT_CARD_ACTIVITY_TYPE = 'commerce:giftCard' as const\n\nconst alreadyExists = (error: unknown): boolean => {\n const code = (error as { code?: unknown } | null)?.code\n return code === 6 || code === 'already-exists' || code === 'ALREADY_EXISTS'\n}\n\n/** Issues one card. Throws {@link GiftCardIssueRefusal} for what the person can fix. */\nexport async function issueGiftCard(input: IssueGiftCardInput): Promise<{ code: string; emailed: boolean }> {\n const { firestore, hostId } = input\n const amountCents = Math.round(Number(input.amountCents))\n const amountProblem = giftCardAmountProblem(amountCents)\n if (amountProblem) throw new GiftCardIssueRefusal(400, 'amount', amountProblem)\n const brought = input.code ?? null\n if (brought) {\n const codeProblem = giftCardCodeProblem(brought)\n if (codeProblem) throw new GiftCardIssueRefusal(400, 'code', codeProblem)\n }\n const code = brought ?? mintGiftCardCode()\n const recipientEmail = String(input.recipientEmail ?? '').trim().slice(0, 200)\n const note = String(input.note ?? '').trim().slice(0, 200)\n try {\n await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('giftCards')\n .doc(code)\n .create({\n initialCents: amountCents,\n balanceCents: amountCents,\n recipientEmail: recipientEmail || null,\n // Null rather than absent: the field is what tells a reader whether a\n // card came from a sale or from the console, and `undefined` would\n // make an issued-by-hand card indistinguishable from a legacy row.\n orderId: null,\n issuedBy: input.issuer.uid,\n ...(note ? { note } : {}),\n ...(input.source ? { importJobId: input.source.importJobId, importRow: input.source.importRow } : {}),\n // What the console's Gift cards search asks (AGL-3321).\n searchTokens: giftCardSearchTokens(code, recipientEmail || null),\n createdAtMs: Date.now(),\n })\n } catch (error) {\n if (alreadyExists(error)) {\n throw new GiftCardIssueRefusal(409, 'taken', `A gift card with the code ${code} already exists.`)\n }\n throw error\n }\n\n await logHostActivity(\n hostId,\n { uid: input.issuer.uid, email: input.issuer.email ?? null },\n input.source ? 'Issued gift card from an import' : 'Issued gift card',\n { type: GIFT_CARD_ACTIVITY_TYPE, id: code, name: giftCardActivityName(code) },\n )\n\n let emailed = false\n if (input.email && recipientEmail && isEmailConfigured()) {\n const value = `$${(amountCents / 100).toFixed(2)}`\n // The same site-designed template the purchase path uses (AGL-771), so\n // a hand-issued card arrives looking like a bought one — with the\n // merchant's note (AGL-3432). A card sent by hand often goes to someone\n // who has never visited the site, and the note is the only part of the\n // message the merchant wrote.\n const designed = await renderHostEmailWithTokens(firestore, hostId, 'gift-card', {\n 'giftcard.code': code,\n 'giftcard.value': value,\n 'giftcard.note': note,\n })\n const sent = await sendEmail({\n to: recipientEmail,\n subject: designed?.subject ?? 'Your gift card',\n text:\n designed?.text ||\n (note ? `${note}\\n\\n` : '') +\n `Gift card code: ${code}\\nValue: ${value}\\n\\n` +\n 'Enter it at checkout to apply the balance.',\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: Aglyn.resolveBrandingProfile(input.ownerOrg as never).fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'gift card',\n // Owed to the recipient by their own order: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'order',\n })\n .then(() => true)\n .catch(() => false)\n if (sent) {\n // Cost meter (AGL-1438). Transactional: the card has already been\n // minted and the recipient is owed the code, so a quota may count\n // this send but never refuse it. Metered on the SUCCESS path only,\n // matching every other sender — a send the provider rejected costs\n // nothing, and a meter that counted it would inflate the COGS figure\n // exactly when mail was broken.\n await meterHostEmail(hostId)\n }\n // The truth, not the intent: the console shows this back to whoever\n // issued the card, and reporting a delivered email for a send that\n // threw is how a customer ends up waiting for a code that is not\n // coming.\n emailed = sent\n }\n return { code, emailed }\n}\n"],"names":["Aglyn","randomBytes","hostSendingIdentity","logHostActivity","meterHostEmail","renderHostEmailWithTokens","isEmailConfigured","sendEmail","giftCardAmountProblem","giftCardCodeProblem","giftCardSearchTokens","GiftCardIssueRefusal","Error","status","reason","message","name","mintGiftCardCode","toString","toUpperCase","giftCardActivityName","code","slice","GIFT_CARD_ACTIVITY_TYPE","alreadyExists","error","issueGiftCard","input","firestore","hostId","amountCents","Math","round","Number","amountProblem","brought","codeProblem","recipientEmail","String","trim","note","collection","doc","create","initialCents","balanceCents","orderId","issuedBy","issuer","uid","source","importJobId","importRow","searchTokens","createdAtMs","Date","now","email","type","id","emailed","value","toFixed","designed","sent","to","subject","text","html","fromName","resolveBrandingProfile","ownerOrg","sendingIdentity","audience","context","owedFor","then","catch"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SAASC,WAAW,QAAQ,SAAQ;AACpC,SACEC,mBAAmB,EACnBC,eAAe,EACfC,cAAc,EACdC,yBAAyB,QACpB,2BAA0B;AACjC,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAEEC,qBAAqB,EACrBC,mBAAmB,QACd,kCAA8B;AACrC,SAASC,oBAAoB,QAAQ,+BAA2B;AAEhE;;;;;;;;;;;;;;;;;CAiBC,GAED,8EAA8E,GAC9E,OAAO,MAAMC,6BAA6BC;IACxC,YACE,AAASC,MAAc,EACvB,AAASC,MAAmC,EAC5CC,OAAe,CACf;QACA,KAAK,CAACA,eAJGF,SAAAA,aACAC,SAAAA;QAIT,IAAI,CAACE,IAAI,GAAG;IACd;AACF;AAEA,yEAAyE,GACzE,OAAO,SAASC;IACd,OAAO,CAAC,GAAG,EAAEhB,YAAY,GAAGiB,QAAQ,CAAC,OAAOC,WAAW,IAAI;AAC7D;AAyBA,kFAAkF,GAClF,OAAO,SAASC,qBAAqBC,IAAY;IAC/C,OAAO,CAAC,iBAAiB,EAAEA,KAAKC,KAAK,CAAC,CAAC,IAAI;AAC7C;AAEA,2EAA2E,GAC3E,OAAO,MAAMC,0BAA0B,oBAA4B;AAEnE,MAAMC,gBAAgB,CAACC;IACrB,MAAMJ,OAAQI,yBAAD,AAACA,MAAqCJ,IAAI;IACvD,OAAOA,SAAS,KAAKA,SAAS,oBAAoBA,SAAS;AAC7D;AAEA,sFAAsF,GACtF,OAAO,eAAeK,cAAcC,KAAyB;QAK3CA,aAMcA,uBACVA,aA+BcA;IA1ClC,MAAM,EAAEC,SAAS,EAAEC,MAAM,EAAE,GAAGF;IAC9B,MAAMG,cAAcC,KAAKC,KAAK,CAACC,OAAON,MAAMG,WAAW;IACvD,MAA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YACnE,qEAAqE;YACrE,gCAAgC;YAChC,MAAM5D,eAAeyB;QACvB;QACA,oEAAoE;QACpE,mEAAmE;QACnE,iEAAiE;QACjE,UAAU;QACV+B,UAAUI;IACZ;IACA,OAAO;QAAE3C;QAAMuC;IAAQ;AACzB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/gift-card-issue.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { randomBytes } from 'crypto'\nimport {\n hostSendingIdentity,\n logHostActivity,\n meterHostEmail,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport {\n GIFT_CARD_ISSUE_MAX_CENTS,\n giftCardAmountProblem,\n giftCardCodeProblem,\n} from '../model/commerce-gift-cards'\nimport { giftCardSearchTokens } from '../model/gift-card-search'\n\n/*\n * ISSUING A GIFT CARD (AGL-2226, AGL-3551): the one path a card comes into\n * being by a merchant's hand — the Gift cards card's Issue, one card at a\n * time, and the gift card import, one card per row. A sale's cards are\n * minted by the billing webhook from the order.\n *\n * What issuing is, wherever it is asked from:\n *\n * - the amount is above zero and at most {@link GIFT_CARD_ISSUE_MAX_CENTS};\n * - the code is minted, or a code the merchant brings (an import carries\n * the codes shoppers already hold) — and a code another card holds is\n * refused, never overwritten: the document is CREATED, so two issues of\n * one code cannot both land;\n * - the card records who issued it (`issuedBy`) and for how much\n * (`initialCents`), and the site's activity log gets a line naming it;\n * - the recipient is emailed the code only when asked, and the answer says\n * whether the email actually went.\n */\n\n/** A refusal the person can act on, with the status a route answers it with. */\nexport class GiftCardIssueRefusal extends Error {\n constructor(\n readonly status: number,\n readonly reason: 'amount' | 'code' | 'taken',\n message: string,\n ) {\n super(message)\n this.name = 'GiftCardIssueRefusal'\n }\n}\n\n/** `GC-` + 12 uppercase hex, the shape `billing-webhook.ts` also mints. */\nexport function mintGiftCardCode(): string {\n return `GC-${randomBytes(6).toString('hex').toUpperCase()}`\n}\n\n/** Where an imported card came from, so a retried row finds the card it already issued. */\nexport interface GiftCardIssueSource {\n importJobId: string\n importRow: number\n}\n\nexport interface IssueGiftCardInput {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n amountCents: number\n recipientEmail?: string | null\n note?: string | null\n /** A code the merchant brings; one is minted when absent. */\n code?: string | null\n /** Who issued it, for the card and the activity line. */\n issuer: { uid: string; email?: string | null }\n /** Email the recipient their code (when there is a recipient and mail is set up). */\n email: boolean\n /** The workspace that owns the site, for the email's sender name. */\n ownerOrg?: unknown\n source?: GiftCardIssueSource\n}\n\n/** What the activity log names a card by: never the whole code, which spends it. */\nexport function giftCardActivityName(code: string): string {\n return `Gift card ending ${code.slice(-4)}`\n}\n\n/** The activity target a card is filed under (`pluginId:noun`, AGL-2978). */\nexport const GIFT_CARD_ACTIVITY_TYPE = 'commerce:giftCard' as const\n\nconst alreadyExists = (error: unknown): boolean => {\n const code = (error as { code?: unknown } | null)?.code\n return code === 6 || code === 'already-exists' || code === 'ALREADY_EXISTS'\n}\n\n/** Issues one card. Throws {@link GiftCardIssueRefusal} for what the person can fix. */\nexport async function issueGiftCard(input: IssueGiftCardInput): Promise<{ code: string; emailed: boolean }> {\n const { firestore, hostId } = input\n const amountCents = Math.round(Number(input.amountCents))\n const amountProblem = giftCardAmountProblem(amountCents)\n if (amountProblem) throw new GiftCardIssueRefusal(400, 'amount', amountProblem)\n const brought = input.code ?? null\n if (brought) {\n const codeProblem = giftCardCodeProblem(brought)\n if (codeProblem) throw new GiftCardIssueRefusal(400, 'code', codeProblem)\n }\n const code = brought ?? mintGiftCardCode()\n const recipientEmail = String(input.recipientEmail ?? '').trim().slice(0, 200)\n const note = String(input.note ?? '').trim().slice(0, 200)\n try {\n await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('giftCards')\n .doc(code)\n .create({\n initialCents: amountCents,\n balanceCents: amountCents,\n recipientEmail: recipientEmail || null,\n // Null rather than absent: the field is what tells a reader whether a\n // card came from a sale or from the console, and `undefined` would\n // make an issued-by-hand card indistinguishable from a legacy row.\n orderId: null,\n issuedBy: input.issuer.uid,\n ...(note ? { note } : {}),\n ...(input.source ? { importJobId: input.source.importJobId, importRow: input.source.importRow } : {}),\n // What the console's Gift cards search asks (AGL-3321).\n searchTokens: giftCardSearchTokens(code, recipientEmail || null),\n createdAtMs: Date.now(),\n })\n } catch (error) {\n if (alreadyExists(error)) {\n throw new GiftCardIssueRefusal(409, 'taken', `A gift card with the code ${code} already exists.`)\n }\n throw error\n }\n\n await logHostActivity(\n hostId,\n { uid: input.issuer.uid, email: input.issuer.email ?? null },\n input.source ? 'Issued gift card from an import' : 'Issued gift card',\n { type: GIFT_CARD_ACTIVITY_TYPE, id: code, name: giftCardActivityName(code) },\n )\n\n let emailed = false\n if (input.email && recipientEmail && isEmailConfigured()) {\n const value = `$${(amountCents / 100).toFixed(2)}`\n // The same site-designed template the purchase path uses (AGL-771), so\n // a hand-issued card arrives looking like a bought one — with the\n // merchant's note (AGL-3432). A card sent by hand often goes to someone\n // who has never visited the site, and the note is the only part of the\n // message the merchant wrote.\n const designed = await renderHostEmailWithTokens(firestore, hostId, 'gift-card', {\n 'giftcard.code': code,\n 'giftcard.value': value,\n 'giftcard.note': note,\n })\n const sent = await sendEmail({\n to: recipientEmail,\n subject: designed?.subject ?? 'Your gift card',\n text:\n designed?.text ||\n (note ? `${note}\\n\\n` : '') +\n `Gift card code: ${code}\\nValue: ${value}\\n\\n` +\n 'Enter it at checkout to apply the balance.',\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: Aglyn.resolveBrandingProfile(input.ownerOrg as never).fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'gift card',\n // Owed to the recipient by their own order: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'order',\n })\n // A refused send (a sending limit, the outbound screen) RESOLVES with\n // `sent: false`; it is not an emailed card (AGL-4227).\n .then((outcome) => Boolean(outcome?.sent))\n .catch(() => false)\n if (sent) {\n // Cost meter (AGL-1438). Transactional: the card has already been\n // minted and the recipient is owed the code, so a quota may count\n // this send but never refuse it. Metered on the SUCCESS path only,\n // matching every other sender — a send the provider rejected costs\n // nothing, and a meter that counted it would inflate the COGS figure\n // exactly when mail was broken.\n await meterHostEmail(hostId)\n }\n // The truth, not the intent: the console shows this back to whoever\n // issued the card, and reporting a delivered email for a send that\n // threw is how a customer ends up waiting for a code that is not\n // coming.\n emailed = sent\n }\n return { code, emailed }\n}\n"],"names":["Aglyn","randomBytes","hostSendingIdentity","logHostActivity","meterHostEmail","renderHostEmailWithTokens","isEmailConfigured","sendEmail","giftCardAmountProblem","giftCardCodeProblem","giftCardSearchTokens","GiftCardIssueRefusal","Error","status","reason","message","name","mintGiftCardCode","toString","toUpperCase","giftCardActivityName","code","slice","GIFT_CARD_ACTIVITY_TYPE","alreadyExists","error","issueGiftCard","input","firestore","hostId","amountCents","Math","round","Number","amountProblem","brought","codeProblem","recipientEmail","String","trim","note","collection","doc","create","initialCents","balanceCents","orderId","issuedBy","issuer","uid","source","importJobId","importRow","searchTokens","createdAtMs","Date","now","email","type","id","emailed","value","toFixed","designed","sent","to","subject","text","html","fromName","resolveBrandingProfile","ownerOrg","sendingIdentity","audience","context","owedFor","then","outcome","Boolean","catch"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SAASC,WAAW,QAAQ,SAAQ;AACpC,SACEC,mBAAmB,EACnBC,eAAe,EACfC,cAAc,E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;QAAMuC;IAAQ;AACzB"}
@@ -230,7 +230,7 @@ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
230
230
  }, siteBase ? {
231
231
  origin: siteBase
232
232
  } : {}).catch(()=>null);
233
- await sendEmail(_extends({
233
+ const emailOutcome = await sendEmail(_extends({
234
234
  to: email,
235
235
  subject: (designed == null ? void 0 : designed.subject) || `Reset your ${siteName} password`,
236
236
  text: (designed == null ? void 0 : designed.text) || `${intro.replace(/\.$/, '')}. If that was you, set a new password here:\n\n` + `${resetUrl}\n\n${note}`
@@ -248,7 +248,8 @@ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
248
248
  // Cost meter (AGL-1438). Transactional, and the clearest case for why a
249
249
  // quota may not refuse one: this email is how the member gets back into
250
250
  // their account.
251
- await meterHostEmail(hostId);
251
+ // Only a sent email is metered (AGL-4227).
252
+ if (emailOutcome == null ? void 0 : emailOutcome.sent) await meterHostEmail(hostId);
252
253
  return res.status(200).json({
253
254
  ok: true
254
255
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-recover.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport { hostPublicOrigin } from '@aglyn/aglyn/server'\nimport {\n consumeMembershipRecoverAttempt,\n consumeMembershipRecoverSend,\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n isEmailSuppressed,\n meterHostEmail,\n RECOVER_MIN_MEMBER_AGE_MS,\n} from '@aglyn/tenant-data-admin'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { renderHostEmailWithTokens } from '@aglyn/tenant-data-admin/server/host-email-tokens'\nimport { mintPasswordResetToken } from './membership'\nimport { readMemberPasswordHash } from './member-credentials'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Password-recovery request (AGL-552). ALWAYS answers `200 {ok:true}` once\n * the input validates and the caller is inside its rate budget — whether or\n * not the email belongs to a member — so the endpoint can't be used to probe\n * account existence. When a member matches, a single-use one-hour token\n * (bound to the current password hash, see membership.ts) is mailed via\n * Resend with a link to the site's `/recover` route.\n *\n * ## Abuse controls (AGL-1966)\n *\n * This is an unauthenticated endpoint that makes us send mail from\n * `noreply@aglyn.com` to an address the caller chose, and it composes with\n * `membership/register` — which admits arbitrary addresses because member\n * accounts are unlimited on every plan (AGL-889) — into a mail relay. The\n * bounces from that land on the sending reputation shared by every customer's\n * transactional mail.\n *\n * Four controls, in the order they run, and the ORDER is part of each:\n *\n * 1. **Attempt caps** — per recipient and per IP, durable\n * (`membership-recover-throttle.ts`). Consumed BEFORE the member lookup so\n * a member and a non-member spend the identical budget and receive the\n * identical answer; a visible 429 from here therefore leaks nothing. The\n * per-instance `Map` this replaced reset on every cold start and was kept\n * per instance, which on Vercel is close to no limit at all (AGL-794).\n * 2. **The young-member guard** — a member row created inside\n * `RECOVER_MIN_MEMBER_AGE_MS` is not worth a reset mail. Register-then-\n * recover is the whole attack and nobody forgets a password ten minutes\n * after choosing it. Silent-success exit.\n * 3. **The platform suppression list** — see the note on the call below.\n * Silent-success exit.\n * 4. **The per-site daily send ceiling** — consumed only when a message is\n * actually about to go out. Because that branch is reachable only for real\n * members, its refusal MUST be the silent-success exit rather than an\n * error, or the ceiling becomes the oracle everything else avoids.\n *\n * What remains unbounded is stated rather than papered over: a genuine botnet\n * still gets `RECOVER_ATTEMPTS_PER_IP` per source, and an attacker who can\n * create many sites gets the per-site ceiling once per site. Host creation is\n * itself rate-limited, and bounding the botnet case needs an edge WAF, not an\n * application limiter — the same conclusion `plugin-api-rate-limit.ts` reaches.\n */\nexport const membershipRecoverHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const email = String(req.body?.email ?? '')\n .trim()\n .toLowerCase()\n if (!hostId || !EMAIL_PATTERN.test(email)) {\n return res.status(400).json({ error: 'Invalid request' })\n }\n // Null when nothing readable names the caller; the throttle then skips its\n // per-source cap and the per-recipient one carries the control alone.\n const ip = readClientIp(req.headers, {\n remoteAddress: req.socket?.remoteAddress,\n })\n // Control 1. Before the lookup, so both branches spend the same budget.\n // A store failure degrades to the in-process cap rather than refusing\n // (`consumeRateLimit` fails soft on an unreachable store, closed on\n // contention) — a Firestore blip must not lock every site's members out of\n // their own password reset.\n const attempt = await consumeMembershipRecoverAttempt({ email, ip })\n if (!attempt.allowed) {\n res.setHeader('Retry-After', String(attempt.retryAfterSeconds))\n return res.status(429).json({ error: 'Too many attempts' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [hostSnapshot, membersQuery] = await Promise.all([\n hostRef.get(),\n hostRef\n .collection('siteMembers')\n .where('email', '==', email)\n .limit(1)\n .get(),\n ])\n const memberDoc = membersQuery.docs[0]\n // Unknown site, unknown email, suspended account (AGL-546): all take\n // the same silent-success exit — the response never distinguishes.\n if (\n !hostSnapshot.exists ||\n !memberDoc ||\n memberDoc.get('suspended') === true\n ) {\n return res.status(200).json({ ok: true })\n }\n // Control 2 — the register-then-recover composition (AGL-1966).\n //\n // `createdAt` is a server timestamp written by `membership-register.ts`.\n // A row that has none is a legacy member, not a fresh one: rows predating\n // the field must NOT be refused, so an unreadable or absent value reads as\n // \"old enough\". This guard exists to refuse a member created seconds ago,\n // which is a case where the field is always present by construction.\n const createdAtMs = (() => {\n const raw = memberDoc.get('createdAt') as\n | { toMillis?: () => number }\n | undefined\n try {\n return typeof raw?.toMillis === 'function' ? raw.toMillis() : null\n } catch {\n return null\n }\n })()\n if (\n createdAtMs !== null &&\n Date.now() - createdAtMs < RECOVER_MIN_MEMBER_AGE_MS\n ) {\n return res.status(200).json({ ok: true })\n }\n // Control 3 — the platform suppression list (AGL-1918 / AGL-2407).\n //\n // `email-suppression.ts` argues that TRANSACTIONAL mail deliberately does\n // not consult this list, because refusing a password reset over an\n // unrelated old bounce locks a real customer out of their own account.\n // That argument is about mail a signed-in human just asked us for. It does\n // not reach here, and this is the exception it does not cover:\n //\n // - The address is chosen by an ANONYMOUS caller, not by the account\n // holder. \"The human just did something\" is exactly the premise that is\n // missing on an unauthenticated endpoint.\n // - The list holds PERMANENT bounces and spam complaints only — transient\n // bounces are excluded at the webhook. A permanent bounce means the\n // mailbox does not exist, so the send cannot reach anyone; all it can do\n // is tell a provider that `aglyn.com` re-mails dead addresses. There is\n // no locked-out customer on the other side of it to protect.\n // - The reputational cost is shared by every customer's transactional\n // mail, which is precisely what AGL-1966 is about.\n //\n // The HOST list (`hosts/{hostId}/suppressions`) is deliberately NOT\n // consulted: it also holds marketing unsubscribes, and unsubscribing from\n // a store's newsletter must never stop that store's password resets.\n //\n // `isEmailSuppressed` fails CLOSED — a read that throws answers \"treat as\n // suppressed\". That adds no new outage mode here: the member lookup above\n // is a Firestore read on the same database, so a Firestore outage has\n // already taken this handler to its silent-success catch.\n if (await isEmailSuppressed(email)) {\n return res.status(200).json({ ok: true })\n }\n if (!isEmailConfigured()) {\n // Config gaps must not become an existence oracle either; log for\n // the operator and keep the visitor-facing contract.\n console.error('membership/recover: email is not configured')\n return res.status(200).json({ ok: true })\n }\n // Bound to the hash sign-in checks, the credential document's (AGL-3308).\n const token = mintPasswordResetToken(\n hostId,\n memberDoc.id,\n await readMemberPasswordHash(hostRef, memberDoc),\n )\n // `hostPublicOrigin`, not a hand-rolled apex (AGL-2195). This URL is\n // minted server-side and mailed out, so a wrong apex is not a display\n // bug — it is a live link on somebody else's domain.\n const siteBase =\n hostPublicOrigin({\n cname: hostSnapshot.get('cname'),\n subdomain: hostSnapshot.get('subdomain'),\n }) ?? ''\n const resetUrl = `${siteBase}/recover?token=${encodeURIComponent(token)}`\n const siteName = String(\n hostSnapshot.get('displayName') ?? hostSnapshot.get('subdomain') ?? 'your site',\n )\n // White-label sender identity (White-Label Phase 3): the store's brand via\n // the one shared resolver (the copy already uses the site name).\n const branding = resolveBrandingProfile(\n (await getOrgForHost(hostId).catch(() => null))?.org as never,\n )\n // Control 4 — the per-site daily ceiling on recovery mail (AGL-1966).\n //\n // Consumed here, as late as possible, because it counts MESSAGES and not\n // requests: everything above this line can refuse without having decided\n // to send, and a counter that ticked for those would exhaust a site's\n // budget on traffic that never cost a message.\n //\n // The refusal is the silent-success exit, NOT a 429. This branch is\n // reachable only for an address that really is a member, so a visible\n // error here would be the existence oracle the whole handler is built to\n // avoid — the one place where the cheap answer is the wrong one.\n //\n // The accepted cost: during an attack on a site, a genuine member can get\n // no mail and no error. The ceiling is sized more than an order of\n // magnitude above any real site's daily resets so that reaching it is\n // evidence of the attack rather than of a busy Tuesday.\n const sendBudget = await consumeMembershipRecoverSend({ hostId })\n if (!sendBudget.allowed) {\n console.error('membership/recover: daily send ceiling reached', {\n hostId,\n retryAfterSeconds: sendBudget.retryAfterSeconds,\n })\n return res.status(200).json({ ok: true })\n }\n const intro = `Someone asked to reset the password for your ${siteName} account.`\n const note =\n 'The link works once and expires in 1 hour. If you did not ' +\n 'ask for this, you can safely ignore this email — your ' +\n 'password is unchanged.'\n // The `member-password-reset` site email (AGL-3370): the site's design,\n // or the built-in copy in its header and footer.\n const designed = await renderHostEmailWithTokens(\n firestore,\n hostId,\n 'member-password-reset',\n { 'site.name': siteName, 'reset.intro': intro, resetUrl, 'reset.note': note },\n siteBase ? { origin: siteBase } : {},\n ).catch(() => null)\n await sendEmail({\n to: email,\n subject: designed?.subject || `Reset your ${siteName} password`,\n text:\n designed?.text ||\n `${intro.replace(/\\.$/, '')}. If that was you, set a new password here:\\n\\n` +\n `${resetUrl}\\n\\n${note}`,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'membership recovery',\n // Owed to the recipient by their own account: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'account',\n })\n // Cost meter (AGL-1438). Transactional, and the clearest case for why a\n // quota may not refuse one: this email is how the member gets back into\n // their account.\n await meterHostEmail(hostId)\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n // Even a backend failure stays silent-success: the enumeration\n // contract beats the visitor's error visibility here, and the send is\n // best-effort by design.\n return res.status(200).json({ ok: true })\n }\n}\n"],"names":["resolveBrandingProfile","hostPublicOrigin","consumeMembershipRecoverAttempt","consumeMembershipRecoverSend","firebaseAdmin","getOrgForHost","hostSendingIdentity","isEmailSuppressed","meterHostEmail","RECOVER_MIN_MEMBER_AGE_MS","isEmailConfigured","sendEmail","renderHostEmailWithTokens","mintPasswordResetToken","readMemberPasswordHash","readClientIp","EMAIL_PATTERN","membershipRecoverHandler","req","res","method","status","json","error","hostId","String","body","email","trim","toLowerCase","test","ip","headers","remoteAddress","socket","attempt","allowed","setHeader","retryAfterSeconds","hostSnapshot","firestore","app","hostRef","collection","doc","membersQuery","Promise","all","get","where","limit","memberDoc","docs","exists","ok","createdAtMs","raw","toMillis","Date","now","console","token","id","siteBase","cname","subdomain","resetUrl","encodeURIComponent","siteName","branding","catch","org","sendBudget","intro","note","designed","origin","to","subject","text","replace","html","fromName","sendingIdentity","audience","context","owedFor"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,sBAAsB,QAAQ,sBAAqB;AAC5D,SAASC,gBAAgB,QAAQ,sBAAqB;AACtD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wEAAwE;QACxE,iBAAiB;QACjB,MAAM9E,eAAegB;QACrB,OAAOL,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEgC,IAAI;QAAK;IACzC,EAAE,OAAO/B,OAAO;QACdqC,QAAQrC,KAAK,CAACA;QACd,+DAA+D;QAC/D,sEAAsE;QACtE,yBAAyB;QACzB,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEgC,IAAI;QAAK;IACzC;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-recover.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport { hostPublicOrigin } from '@aglyn/aglyn/server'\nimport {\n consumeMembershipRecoverAttempt,\n consumeMembershipRecoverSend,\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n isEmailSuppressed,\n meterHostEmail,\n RECOVER_MIN_MEMBER_AGE_MS,\n} from '@aglyn/tenant-data-admin'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { renderHostEmailWithTokens } from '@aglyn/tenant-data-admin/server/host-email-tokens'\nimport { mintPasswordResetToken } from './membership'\nimport { readMemberPasswordHash } from './member-credentials'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Password-recovery request (AGL-552). ALWAYS answers `200 {ok:true}` once\n * the input validates and the caller is inside its rate budget — whether or\n * not the email belongs to a member — so the endpoint can't be used to probe\n * account existence. When a member matches, a single-use one-hour token\n * (bound to the current password hash, see membership.ts) is mailed via\n * Resend with a link to the site's `/recover` route.\n *\n * ## Abuse controls (AGL-1966)\n *\n * This is an unauthenticated endpoint that makes us send mail from\n * `noreply@aglyn.com` to an address the caller chose, and it composes with\n * `membership/register` — which admits arbitrary addresses because member\n * accounts are unlimited on every plan (AGL-889) — into a mail relay. The\n * bounces from that land on the sending reputation shared by every customer's\n * transactional mail.\n *\n * Four controls, in the order they run, and the ORDER is part of each:\n *\n * 1. **Attempt caps** — per recipient and per IP, durable\n * (`membership-recover-throttle.ts`). Consumed BEFORE the member lookup so\n * a member and a non-member spend the identical budget and receive the\n * identical answer; a visible 429 from here therefore leaks nothing. The\n * per-instance `Map` this replaced reset on every cold start and was kept\n * per instance, which on Vercel is close to no limit at all (AGL-794).\n * 2. **The young-member guard** — a member row created inside\n * `RECOVER_MIN_MEMBER_AGE_MS` is not worth a reset mail. Register-then-\n * recover is the whole attack and nobody forgets a password ten minutes\n * after choosing it. Silent-success exit.\n * 3. **The platform suppression list** — see the note on the call below.\n * Silent-success exit.\n * 4. **The per-site daily send ceiling** — consumed only when a message is\n * actually about to go out. Because that branch is reachable only for real\n * members, its refusal MUST be the silent-success exit rather than an\n * error, or the ceiling becomes the oracle everything else avoids.\n *\n * What remains unbounded is stated rather than papered over: a genuine botnet\n * still gets `RECOVER_ATTEMPTS_PER_IP` per source, and an attacker who can\n * create many sites gets the per-site ceiling once per site. Host creation is\n * itself rate-limited, and bounding the botnet case needs an edge WAF, not an\n * application limiter — the same conclusion `plugin-api-rate-limit.ts` reaches.\n */\nexport const membershipRecoverHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const email = String(req.body?.email ?? '')\n .trim()\n .toLowerCase()\n if (!hostId || !EMAIL_PATTERN.test(email)) {\n return res.status(400).json({ error: 'Invalid request' })\n }\n // Null when nothing readable names the caller; the throttle then skips its\n // per-source cap and the per-recipient one carries the control alone.\n const ip = readClientIp(req.headers, {\n remoteAddress: req.socket?.remoteAddress,\n })\n // Control 1. Before the lookup, so both branches spend the same budget.\n // A store failure degrades to the in-process cap rather than refusing\n // (`consumeRateLimit` fails soft on an unreachable store, closed on\n // contention) — a Firestore blip must not lock every site's members out of\n // their own password reset.\n const attempt = await consumeMembershipRecoverAttempt({ email, ip })\n if (!attempt.allowed) {\n res.setHeader('Retry-After', String(attempt.retryAfterSeconds))\n return res.status(429).json({ error: 'Too many attempts' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [hostSnapshot, membersQuery] = await Promise.all([\n hostRef.get(),\n hostRef\n .collection('siteMembers')\n .where('email', '==', email)\n .limit(1)\n .get(),\n ])\n const memberDoc = membersQuery.docs[0]\n // Unknown site, unknown email, suspended account (AGL-546): all take\n // the same silent-success exit — the response never distinguishes.\n if (\n !hostSnapshot.exists ||\n !memberDoc ||\n memberDoc.get('suspended') === true\n ) {\n return res.status(200).json({ ok: true })\n }\n // Control 2 — the register-then-recover composition (AGL-1966).\n //\n // `createdAt` is a server timestamp written by `membership-register.ts`.\n // A row that has none is a legacy member, not a fresh one: rows predating\n // the field must NOT be refused, so an unreadable or absent value reads as\n // \"old enough\". This guard exists to refuse a member created seconds ago,\n // which is a case where the field is always present by construction.\n const createdAtMs = (() => {\n const raw = memberDoc.get('createdAt') as\n | { toMillis?: () => number }\n | undefined\n try {\n return typeof raw?.toMillis === 'function' ? raw.toMillis() : null\n } catch {\n return null\n }\n })()\n if (\n createdAtMs !== null &&\n Date.now() - createdAtMs < RECOVER_MIN_MEMBER_AGE_MS\n ) {\n return res.status(200).json({ ok: true })\n }\n // Control 3 — the platform suppression list (AGL-1918 / AGL-2407).\n //\n // `email-suppression.ts` argues that TRANSACTIONAL mail deliberately does\n // not consult this list, because refusing a password reset over an\n // unrelated old bounce locks a real customer out of their own account.\n // That argument is about mail a signed-in human just asked us for. It does\n // not reach here, and this is the exception it does not cover:\n //\n // - The address is chosen by an ANONYMOUS caller, not by the account\n // holder. \"The human just did something\" is exactly the premise that is\n // missing on an unauthenticated endpoint.\n // - The list holds PERMANENT bounces and spam complaints only — transient\n // bounces are excluded at the webhook. A permanent bounce means the\n // mailbox does not exist, so the send cannot reach anyone; all it can do\n // is tell a provider that `aglyn.com` re-mails dead addresses. There is\n // no locked-out customer on the other side of it to protect.\n // - The reputational cost is shared by every customer's transactional\n // mail, which is precisely what AGL-1966 is about.\n //\n // The HOST list (`hosts/{hostId}/suppressions`) is deliberately NOT\n // consulted: it also holds marketing unsubscribes, and unsubscribing from\n // a store's newsletter must never stop that store's password resets.\n //\n // `isEmailSuppressed` fails CLOSED — a read that throws answers \"treat as\n // suppressed\". That adds no new outage mode here: the member lookup above\n // is a Firestore read on the same database, so a Firestore outage has\n // already taken this handler to its silent-success catch.\n if (await isEmailSuppressed(email)) {\n return res.status(200).json({ ok: true })\n }\n if (!isEmailConfigured()) {\n // Config gaps must not become an existence oracle either; log for\n // the operator and keep the visitor-facing contract.\n console.error('membership/recover: email is not configured')\n return res.status(200).json({ ok: true })\n }\n // Bound to the hash sign-in checks, the credential document's (AGL-3308).\n const token = mintPasswordResetToken(\n hostId,\n memberDoc.id,\n await readMemberPasswordHash(hostRef, memberDoc),\n )\n // `hostPublicOrigin`, not a hand-rolled apex (AGL-2195). This URL is\n // minted server-side and mailed out, so a wrong apex is not a display\n // bug — it is a live link on somebody else's domain.\n const siteBase =\n hostPublicOrigin({\n cname: hostSnapshot.get('cname'),\n subdomain: hostSnapshot.get('subdomain'),\n }) ?? ''\n const resetUrl = `${siteBase}/recover?token=${encodeURIComponent(token)}`\n const siteName = String(\n hostSnapshot.get('displayName') ?? hostSnapshot.get('subdomain') ?? 'your site',\n )\n // White-label sender identity (White-Label Phase 3): the store's brand via\n // the one shared resolver (the copy already uses the site name).\n const branding = resolveBrandingProfile(\n (await getOrgForHost(hostId).catch(() => null))?.org as never,\n )\n // Control 4 — the per-site daily ceiling on recovery mail (AGL-1966).\n //\n // Consumed here, as late as possible, because it counts MESSAGES and not\n // requests: everything above this line can refuse without having decided\n // to send, and a counter that ticked for those would exhaust a site's\n // budget on traffic that never cost a message.\n //\n // The refusal is the silent-success exit, NOT a 429. This branch is\n // reachable only for an address that really is a member, so a visible\n // error here would be the existence oracle the whole handler is built to\n // avoid — the one place where the cheap answer is the wrong one.\n //\n // The accepted cost: during an attack on a site, a genuine member can get\n // no mail and no error. The ceiling is sized more than an order of\n // magnitude above any real site's daily resets so that reaching it is\n // evidence of the attack rather than of a busy Tuesday.\n const sendBudget = await consumeMembershipRecoverSend({ hostId })\n if (!sendBudget.allowed) {\n console.error('membership/recover: daily send ceiling reached', {\n hostId,\n retryAfterSeconds: sendBudget.retryAfterSeconds,\n })\n return res.status(200).json({ ok: true })\n }\n const intro = `Someone asked to reset the password for your ${siteName} account.`\n const note =\n 'The link works once and expires in 1 hour. If you did not ' +\n 'ask for this, you can safely ignore this email — your ' +\n 'password is unchanged.'\n // The `member-password-reset` site email (AGL-3370): the site's design,\n // or the built-in copy in its header and footer.\n const designed = await renderHostEmailWithTokens(\n firestore,\n hostId,\n 'member-password-reset',\n { 'site.name': siteName, 'reset.intro': intro, resetUrl, 'reset.note': note },\n siteBase ? { origin: siteBase } : {},\n ).catch(() => null)\n const emailOutcome = await sendEmail({\n to: email,\n subject: designed?.subject || `Reset your ${siteName} password`,\n text:\n designed?.text ||\n `${intro.replace(/\\.$/, '')}. If that was you, set a new password here:\\n\\n` +\n `${resetUrl}\\n\\n${note}`,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'membership recovery',\n // Owed to the recipient by their own account: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'account',\n })\n // Cost meter (AGL-1438). Transactional, and the clearest case for why a\n // quota may not refuse one: this email is how the member gets back into\n // their account.\n // Only a sent email is metered (AGL-4227).\n if (emailOutcome?.sent) await meterHostEmail(hostId)\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n // Even a backend failure stays silent-success: the enumeration\n // contract beats the visitor's error visibility here, and the send is\n // best-effort by design.\n return res.status(200).json({ ok: true })\n }\n}\n"],"names":["resolveBrandingProfile","hostPublicOrigin","consumeMembershipRecoverAttempt","consumeMembershipRecoverSend","firebaseAdmin","getOrgForHost","hostSendingIdentity","isEmailSuppressed","meterHostEmail","RECOVER_MIN_MEMBER_AGE_MS","isEmailConfigured","sendEmail","renderHostEmailWithTokens","mintPasswordResetToken","readMemberPasswordHash","readClientIp","EMAIL_PATTERN","membershipRecoverHandler","req","res","method","status","json","error","hostId","String","body","email","trim","toLowerCase","test","ip","headers","remoteAddress","socket","attempt","allowed","setHeader","retryAfterSeconds","hostSnapshot","firestore","app","hostRef","collection","doc","membersQuery","Promise","all","get","where","limit","memberDoc","docs","exists","ok","createdAtMs","raw","toMillis","Date","now","console","token","id","siteBase","cname","subdomain","resetUrl","encodeURIComponent","siteName","branding","catch","org","sendBudget","intro","note","designed","origin","emailOutcome","to","subject","text","replace","html","fromName","sendingIdentity","audience","context","owedFor","sent"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,sBAAsB,QAAQ,sBAAqB;AAC5D,SAASC,gBAAgB,QAAQ,sBAAqB;AACtD,SACEC,+BAA+B,EAC/BC,4BAA4B,EAC5BC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,iBAAiB,EACjBC,cAAc,EACdC,yBAAyB,QACpB,2BAA0B;AACjC,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,yBAAyB,QAAQ,oDAAmD;AAC7F,SAASC,sBAAsB,QAAQ,kBAAc;AACrD,SAASC,sBAAsB,QAAQ,0BAAsB;AAC7D,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AAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEgC,IAAI;QAAK;IACzC;AACF,EAAC"}
@@ -14,6 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ import { createHash, createHmac, randomBytes, scryptSync, timingSafeEqual } from "crypto";
17
+ import { signedInHintCookieName } from "@aglyn/aglyn/app-utils/sign-in-visibility";
17
18
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
18
19
  /**
19
20
  * Site membership primitives (AGL-109): visitor accounts per host with
@@ -136,7 +137,17 @@ export function setMemberCookie(res, hostId, token) {
136
137
  // console __session cookie.
137
138
  const secure = process.env.NODE_ENV === 'production' ? '; Secure' : '';
138
139
  const base = `${name}=${token != null ? token : ''}; Path=/; HttpOnly; SameSite=Lax${secure}`;
139
- res.setHeader('Set-Cookie', token ? `${base}; Max-Age=${30 * 24 * 60 * 60}` : `${base}; Max-Age=0`);
140
+ const maxAge = token ? `; Max-Age=${30 * 24 * 60 * 60}` : '; Max-Age=0';
141
+ // The readable sign-in HINT beside it (AGL-4231): a `1` the page reads
142
+ // before its first paint to show "Account" rather than "Sign in". It
143
+ // carries nothing and grants nothing — the session above stays HttpOnly
144
+ // and is what every endpoint checks — so it may be readable, and it lives
145
+ // and dies with the session.
146
+ const hint = `${signedInHintCookieName(hostId)}=${token ? '1' : ''}; Path=/; SameSite=Lax${secure}`;
147
+ res.setHeader('Set-Cookie', [
148
+ `${base}${maxAge}`,
149
+ `${hint}${maxAge}`
150
+ ]);
140
151
  }
141
152
  export function readMemberSession(req, hostId) {
142
153
  var _req_cookies;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createHash,\n createHmac,\n randomBytes,\n scryptSync,\n timingSafeEqual,\n} from 'crypto'\nimport type { PluginApiRequest, PluginApiResponse } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\n\n/**\n * Site membership primitives (AGL-109): visitor accounts per host with\n * scrypt-hashed passwords and an HMAC-signed httpOnly session cookie.\n * Per-site Firebase Auth is a future infra decision (AGL-45 class); this\n * keeps member content out of static HTML the same way AGL-87 does.\n */\n\nconst SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000\n\n// A per-boot fallback keeps dev working; production must set the env so\n// sessions survive deploys and instances agree.\n//\n// `||`, NOT `??`, and on a self-host install that is the whole difference\n// (AGL-2014). `.env.selfhost.example` ships `MEMBER_SESSION_SECRET=` blank and\n// compose `env_file` sets a blank line as the EMPTY STRING rather than leaving\n// it unset — so `??` did not fire, `SESSION_SECRET` was `''`, and `createHmac`\n// signs happily with an empty key. Every storefront member session cookie on a\n// template-following deployment was therefore signed with a key any reader of\n// this repository already has, i.e. forgeable. `||` restores the per-boot\n// random the comment above describes and the env template already promises\n// (\"without it, sessions don't survive a restart and disagree across\n// instances\") — unforgeable, and visibly degraded rather than silently open.\n//\n// Nothing caught it because `tools/scripts/selfhost-ci-env.mjs` FILLS this\n// variable before the image build, so the one job that builds these images\n// tests a configuration no operator following the template has.\nconst SESSION_SECRET =\n process.env.MEMBER_SESSION_SECRET || randomBytes(32).toString('hex')\n\nexport function hashMemberPassword(password: string): string {\n const salt = randomBytes(16).toString('hex')\n const hash = scryptSync(password, salt, 64).toString('hex')\n return `${salt}:${hash}`\n}\n\nexport function verifyMemberPassword(\n password: string,\n stored: string | undefined,\n): boolean {\n const [salt, hash] = String(stored ?? '').split(':')\n if (!salt || !hash) return false\n const candidate = scryptSync(password, salt, 64)\n const expected = Buffer.from(hash, 'hex')\n return (\n candidate.length === expected.length &&\n timingSafeEqual(new Uint8Array(candidate), new Uint8Array(expected))\n )\n}\n\nfunction sign(payload: string): string {\n return createHmac('sha256', SESSION_SECRET).update(payload).digest('hex')\n}\n\nexport function mintMemberSession(hostId: string, memberId: string): string {\n const payload = `${hostId}.${memberId}.${Date.now() + SESSION_TTL_MS}`\n return `${payload}.${sign(payload)}`\n}\n\n/**\n * Verified session contents. `issuedAtMs` is derived, not stored: the\n * payload carries `now + TTL`, so subtracting the TTL recovers the mint\n * time. That is what lets sessions be revoked in bulk (AGL-914) without\n * changing the token format or invalidating cookies already in the wild.\n */\nexport interface MemberSessionToken {\n memberId: string\n issuedAtMs: number\n}\n\n/** Returns the session contents when the cookie verifies for this host. */\nexport function parseMemberSession(\n hostId: string,\n token: string | undefined,\n): MemberSessionToken | null {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return null\n const [tokenHost, memberId, expires, signature] = parts\n if (tokenHost !== hostId) return null\n if (Number(expires) < Date.now()) return null\n const payload = `${tokenHost}.${memberId}.${expires}`\n const expected = sign(payload)\n const a = Buffer.from(signature)\n const b = Buffer.from(expected)\n if (a.length !== b.length) return null\n if (!timingSafeEqual(new Uint8Array(a), new Uint8Array(b))) return null\n return { memberId, issuedAtMs: Number(expires) - SESSION_TTL_MS }\n}\n\n/** Returns the memberId when the cookie verifies for this host. */\nexport function verifyMemberSession(\n hostId: string,\n token: string | undefined,\n): string | null {\n return parseMemberSession(hostId, token)?.memberId ?? null\n}\n\n/** Password-reset links live for one hour (AGL-552). */\nconst RESET_TOKEN_TTL_MS = 60 * 60 * 1000\n\n/**\n * Fingerprint of the member's CURRENT scrypt hash, folded into the reset\n * token signature (AGL-552): completing a reset rewrites `passwordScrypt`,\n * so every token minted before it stops verifying — single-use without any\n * server-side token storage.\n */\nfunction passwordFingerprint(passwordScrypt: string | undefined): string {\n return createHash('sha256')\n .update(String(passwordScrypt ?? ''))\n .digest('hex')\n}\n\n/**\n * Single-use, time-boxed password-reset token (AGL-552):\n * `hostId.memberId.expiry.HMAC(payload + password-fingerprint)`. Same\n * secret as sessions; the fingerprint binding is what makes it one-shot.\n */\nexport function mintPasswordResetToken(\n hostId: string,\n memberId: string,\n passwordScrypt: string | undefined,\n): string {\n const payload = `${hostId}.${memberId}.${Date.now() + RESET_TOKEN_TTL_MS}`\n return `${payload}.${sign(\n `${payload}.${passwordFingerprint(passwordScrypt)}`,\n )}`\n}\n\n/**\n * First step of reset verification: extract the memberId from a\n * well-formed, unexpired token for THIS host. The signature is NOT checked\n * here (it binds to the member's current password hash, which the caller\n * has to load first) — never trust the result without a follow-up\n * {@link verifyPasswordResetToken}.\n */\nexport function passwordResetTokenMemberId(\n hostId: string,\n token: string | undefined,\n): string | null {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return null\n const [tokenHost, memberId, expires] = parts\n if (tokenHost !== hostId) return null\n if (!memberId) return null\n if (Number(expires) < Date.now()) return null\n return memberId\n}\n\n/** Full reset-token check: host, expiry, and password-hash binding. */\nexport function verifyPasswordResetToken(\n hostId: string,\n token: string | undefined,\n currentPasswordScrypt: string | undefined,\n): boolean {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return false\n const [tokenHost, memberId, expires, signature] = parts\n if (tokenHost !== hostId || !memberId) return false\n if (Number(expires) < Date.now()) return false\n const payload = `${tokenHost}.${memberId}.${expires}`\n const expected = sign(\n `${payload}.${passwordFingerprint(currentPasswordScrypt)}`,\n )\n const a = Buffer.from(signature)\n const b = Buffer.from(expected)\n if (a.length !== b.length) return false\n return timingSafeEqual(new Uint8Array(a), new Uint8Array(b))\n}\n\nexport function memberCookieName(hostId: string): string {\n return `aglyn_member_${hostId.replace(/[^A-Za-z0-9_-]/g, '')}`\n}\n\nexport function setMemberCookie(\n res: PluginApiResponse,\n hostId: string,\n token: string | null,\n): void {\n const name = memberCookieName(hostId)\n // Secure in production (AGL-500): the member session is an HMAC-signed\n // credential, so it must never travel over plaintext HTTP on a tenant\n // custom domain. Omit only in local dev (http://localhost), matching the\n // console __session cookie.\n const secure = process.env.NODE_ENV === 'production' ? '; Secure' : ''\n const base = `${name}=${token ?? ''}; Path=/; HttpOnly; SameSite=Lax${secure}`\n res.setHeader(\n 'Set-Cookie',\n token ? `${base}; Max-Age=${30 * 24 * 60 * 60}` : `${base}; Max-Age=0`,\n )\n}\n\nexport function readMemberSession(\n req: PluginApiRequest,\n hostId: string,\n): string | null {\n const raw = req.cookies?.[memberCookieName(hostId)]\n return verifyMemberSession(hostId, raw)\n}\n\n/**\n * Field name for the bulk session cut-off (AGL-914). Set to `Date.now()`\n * whenever every existing session for a member must stop working — today\n * only when an admin sets their password from the console, since a rewritten\n * `passwordScrypt` does NOT invalidate sessions on its own (unlike a reset\n * TOKEN, which binds to the hash by design).\n */\nexport const MEMBER_SESSIONS_VALID_FROM_FIELD = 'sessionsValidFromMs'\n\n/** Suspension rejection body — matches the login flow's AGL-546 message. */\nexport const MEMBER_SUSPENDED_ERROR =\n 'This account has been suspended. Contact the site owner.'\n\n/** Resolved member-session state, see {@link readActiveMemberSession}. */\nexport type MemberSessionCheck =\n | { status: 'anonymous' }\n | { status: 'suspended'; memberId: string }\n | {\n status: 'active'\n memberId: string\n member: FirebaseFirestore.DocumentSnapshot\n }\n\n/**\n * Session + member-doc resolution for cookie-authenticated endpoints\n * (AGL-550). A verified cookie alone stopped being enough once console\n * suspension (AGL-546) landed: the HMAC session outlives the member's\n * standing, so every endpoint must also load the doc and check\n * `suspended`. That is one doc read per request — acceptable, and most\n * endpoints needed the member doc anyway. A deleted member doc reads as\n * `anonymous` (same as no cookie).\n */\nexport async function readActiveMemberSession(\n req: PluginApiRequest,\n hostId: string,\n): Promise<MemberSessionCheck> {\n const session = parseMemberSession(\n hostId,\n req.cookies?.[memberCookieName(hostId)],\n )\n if (!session) return { status: 'anonymous' }\n const { memberId, issuedAtMs } = session\n const member = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('siteMembers')\n .doc(memberId)\n .get()\n if (!member.exists) return { status: 'anonymous' }\n // Revoked in bulk (AGL-914): a session minted before the cut-off is dead\n // even though its signature is still good. Reads as `anonymous` rather\n // than `suspended` — the account is fine, this browser just holds a stale\n // cookie, and signing in again is the correct next step.\n const validFrom = Number(member.get(MEMBER_SESSIONS_VALID_FROM_FIELD) ?? 0)\n if (validFrom && issuedAtMs < validFrom) return { status: 'anonymous' }\n if (member.get('suspended') === true) {\n return { status: 'suspended', memberId }\n }\n return { status: 'active', memberId, member }\n}\n\n/**\n * Guard for cookie-authenticated member endpoints (AGL-550): resolves\n * the session AND the member doc, writing the rejection itself — 401\n * (`signInError`) when there is no usable session, 403 with the session\n * cookie cleared (mirroring membership-account's AGL-546 handling, so\n * the site stops presenting a signed-in shell) when the member is\n * suspended. Returns null after responding; handlers `if (!auth) return`.\n */\nexport async function requireActiveMember(\n req: PluginApiRequest,\n res: PluginApiResponse,\n hostId: string,\n signInError = 'Not signed in',\n): Promise<{\n memberId: string\n member: FirebaseFirestore.DocumentSnapshot\n} | null> {\n const session = await readActiveMemberSession(req, hostId)\n if (session.status === 'suspended') {\n setMemberCookie(res, hostId, null)\n res.status(403).json({ error: MEMBER_SUSPENDED_ERROR })\n return null\n }\n if (session.status !== 'active') {\n res.status(401).json({ error: signInError })\n return null\n }\n return { memberId: session.memberId, member: session.member }\n}\n"],"names":["createHash","createHmac","randomBytes","scryptSync","timingSafeEqual","firebaseAdmin","SESSION_TTL_MS","SESSION_SECRET","process","env","MEMBER_SESSION_SECRET","toString","hashMemberPassword","password","salt","hash","verifyMemberPassword","stored","String","split","candidate","expected","Buffer","from","length","Uint8Array","sign","payload","update","digest","mintMemberSession","hostId","memberId","Date","now","parseMemberSession","token","parts","tokenHost","expires","signature","Number","a","b","issuedAtMs","verifyMemberSession","RESET_TOKEN_TTL_MS","passwordFingerprint","passwordScrypt","mintPasswordResetToken","passwordResetTokenMemberId","verifyPasswordResetToken","currentPasswordScrypt","memberCookieName","replace","setMemberCookie","res","name","secure","NODE_ENV","base","setHeader","readMemberSession","req","raw","cookies","MEMBER_SESSIONS_VALID_FROM_FIELD","MEMBER_SUSPENDED_ERROR","readActiveMemberSession","member","session","status","app","firestore","collection","doc","get","exists","validFrom","requireActiveMember","signInError","json","error"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,UAAU,EACVC,WAAW,EACXC,UAAU,EACVC,eAAe,QACV,SAAQ;AAEf,SAASC,aAAa,QAAQ,2BAA0B;AAExD;;;;;CAKC,GAED,MAAMC,iBAAiB,KAAK,KAAK,KAAK,KAAK;AAE3C,wEAAwE;AACxE,gDAAgD;AAChD,EAAE;AACF,0EAA0E;AAC1E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,qEAAqE;AACrE,6EAA6E;AAC7E,EAAE;AACF,2EAA2E;AAC3E,2EAA2E;AAC3E,gEAAgE;AAChE,MAAMC,iBACJC,QAAQC,GAAG,CAACC,qBAAqB,IAAIR,YAAY,IAAIS,QAAQ,CAAC;AAEhE,OAAO,SAASC,mBAAmBC,QAAgB;IACjD,MAAMC,OAAOZ,YAAY,IAAIS,QAAQ,CAAC;IACtC,MAAMI,OAAOZ,WAAWU,UAAUC,MAAM,IAAIH,QAAQ,CAAC;IACrD,OAAO,GAAGG,KAAK,CAAC,EAAEC,MAAM;AAC1B;AAEA,OAAO,SAASC,qBACdH,QAAgB,EAChBI,MAA0B;IAE1B,MAAM,CAACH,MAAMC,KAAK,GAAGG,OAAOD,iBAAAA,SAAU,IAAIE,KAAK,CAAC;IAChD,IAAI,CAACL,QAAQ,CAACC,MAAM,OAAO;IAC3B,MAAMK,YAAYjB,WAAWU,UAAUC,MAAM;IAC7C,MAAMO,WAAWC,OAAOC,IAAI,CAACR,MAAM;IACnC,OACEK,UAAUI,MA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AM;IAAC;AAC9D"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createHash,\n createHmac,\n randomBytes,\n scryptSync,\n timingSafeEqual,\n} from 'crypto'\nimport type { PluginApiRequest, PluginApiResponse } from '@aglyn/aglyn/server'\nimport { signedInHintCookieName } from '@aglyn/aglyn/app-utils/sign-in-visibility'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\n\n/**\n * Site membership primitives (AGL-109): visitor accounts per host with\n * scrypt-hashed passwords and an HMAC-signed httpOnly session cookie.\n * Per-site Firebase Auth is a future infra decision (AGL-45 class); this\n * keeps member content out of static HTML the same way AGL-87 does.\n */\n\nconst SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000\n\n// A per-boot fallback keeps dev working; production must set the env so\n// sessions survive deploys and instances agree.\n//\n// `||`, NOT `??`, and on a self-host install that is the whole difference\n// (AGL-2014). `.env.selfhost.example` ships `MEMBER_SESSION_SECRET=` blank and\n// compose `env_file` sets a blank line as the EMPTY STRING rather than leaving\n// it unset — so `??` did not fire, `SESSION_SECRET` was `''`, and `createHmac`\n// signs happily with an empty key. Every storefront member session cookie on a\n// template-following deployment was therefore signed with a key any reader of\n// this repository already has, i.e. forgeable. `||` restores the per-boot\n// random the comment above describes and the env template already promises\n// (\"without it, sessions don't survive a restart and disagree across\n// instances\") — unforgeable, and visibly degraded rather than silently open.\n//\n// Nothing caught it because `tools/scripts/selfhost-ci-env.mjs` FILLS this\n// variable before the image build, so the one job that builds these images\n// tests a configuration no operator following the template has.\nconst SESSION_SECRET =\n process.env.MEMBER_SESSION_SECRET || randomBytes(32).toString('hex')\n\nexport function hashMemberPassword(password: string): string {\n const salt = randomBytes(16).toString('hex')\n const hash = scryptSync(password, salt, 64).toString('hex')\n return `${salt}:${hash}`\n}\n\nexport function verifyMemberPassword(\n password: string,\n stored: string | undefined,\n): boolean {\n const [salt, hash] = String(stored ?? '').split(':')\n if (!salt || !hash) return false\n const candidate = scryptSync(password, salt, 64)\n const expected = Buffer.from(hash, 'hex')\n return (\n candidate.length === expected.length &&\n timingSafeEqual(new Uint8Array(candidate), new Uint8Array(expected))\n )\n}\n\nfunction sign(payload: string): string {\n return createHmac('sha256', SESSION_SECRET).update(payload).digest('hex')\n}\n\nexport function mintMemberSession(hostId: string, memberId: string): string {\n const payload = `${hostId}.${memberId}.${Date.now() + SESSION_TTL_MS}`\n return `${payload}.${sign(payload)}`\n}\n\n/**\n * Verified session contents. `issuedAtMs` is derived, not stored: the\n * payload carries `now + TTL`, so subtracting the TTL recovers the mint\n * time. That is what lets sessions be revoked in bulk (AGL-914) without\n * changing the token format or invalidating cookies already in the wild.\n */\nexport interface MemberSessionToken {\n memberId: string\n issuedAtMs: number\n}\n\n/** Returns the session contents when the cookie verifies for this host. */\nexport function parseMemberSession(\n hostId: string,\n token: string | undefined,\n): MemberSessionToken | null {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return null\n const [tokenHost, memberId, expires, signature] = parts\n if (tokenHost !== hostId) return null\n if (Number(expires) < Date.now()) return null\n const payload = `${tokenHost}.${memberId}.${expires}`\n const expected = sign(payload)\n const a = Buffer.from(signature)\n const b = Buffer.from(expected)\n if (a.length !== b.length) return null\n if (!timingSafeEqual(new Uint8Array(a), new Uint8Array(b))) return null\n return { memberId, issuedAtMs: Number(expires) - SESSION_TTL_MS }\n}\n\n/** Returns the memberId when the cookie verifies for this host. */\nexport function verifyMemberSession(\n hostId: string,\n token: string | undefined,\n): string | null {\n return parseMemberSession(hostId, token)?.memberId ?? null\n}\n\n/** Password-reset links live for one hour (AGL-552). */\nconst RESET_TOKEN_TTL_MS = 60 * 60 * 1000\n\n/**\n * Fingerprint of the member's CURRENT scrypt hash, folded into the reset\n * token signature (AGL-552): completing a reset rewrites `passwordScrypt`,\n * so every token minted before it stops verifying — single-use without any\n * server-side token storage.\n */\nfunction passwordFingerprint(passwordScrypt: string | undefined): string {\n return createHash('sha256')\n .update(String(passwordScrypt ?? ''))\n .digest('hex')\n}\n\n/**\n * Single-use, time-boxed password-reset token (AGL-552):\n * `hostId.memberId.expiry.HMAC(payload + password-fingerprint)`. Same\n * secret as sessions; the fingerprint binding is what makes it one-shot.\n */\nexport function mintPasswordResetToken(\n hostId: string,\n memberId: string,\n passwordScrypt: string | undefined,\n): string {\n const payload = `${hostId}.${memberId}.${Date.now() + RESET_TOKEN_TTL_MS}`\n return `${payload}.${sign(\n `${payload}.${passwordFingerprint(passwordScrypt)}`,\n )}`\n}\n\n/**\n * First step of reset verification: extract the memberId from a\n * well-formed, unexpired token for THIS host. The signature is NOT checked\n * here (it binds to the member's current password hash, which the caller\n * has to load first) — never trust the result without a follow-up\n * {@link verifyPasswordResetToken}.\n */\nexport function passwordResetTokenMemberId(\n hostId: string,\n token: string | undefined,\n): string | null {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return null\n const [tokenHost, memberId, expires] = parts\n if (tokenHost !== hostId) return null\n if (!memberId) return null\n if (Number(expires) < Date.now()) return null\n return memberId\n}\n\n/** Full reset-token check: host, expiry, and password-hash binding. */\nexport function verifyPasswordResetToken(\n hostId: string,\n token: string | undefined,\n currentPasswordScrypt: string | undefined,\n): boolean {\n const parts = String(token ?? '').split('.')\n if (parts.length !== 4) return false\n const [tokenHost, memberId, expires, signature] = parts\n if (tokenHost !== hostId || !memberId) return false\n if (Number(expires) < Date.now()) return false\n const payload = `${tokenHost}.${memberId}.${expires}`\n const expected = sign(\n `${payload}.${passwordFingerprint(currentPasswordScrypt)}`,\n )\n const a = Buffer.from(signature)\n const b = Buffer.from(expected)\n if (a.length !== b.length) return false\n return timingSafeEqual(new Uint8Array(a), new Uint8Array(b))\n}\n\nexport function memberCookieName(hostId: string): string {\n return `aglyn_member_${hostId.replace(/[^A-Za-z0-9_-]/g, '')}`\n}\n\nexport function setMemberCookie(\n res: PluginApiResponse,\n hostId: string,\n token: string | null,\n): void {\n const name = memberCookieName(hostId)\n // Secure in production (AGL-500): the member session is an HMAC-signed\n // credential, so it must never travel over plaintext HTTP on a tenant\n // custom domain. Omit only in local dev (http://localhost), matching the\n // console __session cookie.\n const secure = process.env.NODE_ENV === 'production' ? '; Secure' : ''\n const base = `${name}=${token ?? ''}; Path=/; HttpOnly; SameSite=Lax${secure}`\n const maxAge = token ? `; Max-Age=${30 * 24 * 60 * 60}` : '; Max-Age=0'\n // The readable sign-in HINT beside it (AGL-4231): a `1` the page reads\n // before its first paint to show \"Account\" rather than \"Sign in\". It\n // carries nothing and grants nothing — the session above stays HttpOnly\n // and is what every endpoint checks — so it may be readable, and it lives\n // and dies with the session.\n const hint = `${signedInHintCookieName(hostId)}=${token ? '1' : ''}; Path=/; SameSite=Lax${secure}`\n res.setHeader('Set-Cookie', [`${base}${maxAge}`, `${hint}${maxAge}`])\n}\n\nexport function readMemberSession(\n req: PluginApiRequest,\n hostId: string,\n): string | null {\n const raw = req.cookies?.[memberCookieName(hostId)]\n return verifyMemberSession(hostId, raw)\n}\n\n/**\n * Field name for the bulk session cut-off (AGL-914). Set to `Date.now()`\n * whenever every existing session for a member must stop working — today\n * only when an admin sets their password from the console, since a rewritten\n * `passwordScrypt` does NOT invalidate sessions on its own (unlike a reset\n * TOKEN, which binds to the hash by design).\n */\nexport const MEMBER_SESSIONS_VALID_FROM_FIELD = 'sessionsValidFromMs'\n\n/** Suspension rejection body — matches the login flow's AGL-546 message. */\nexport const MEMBER_SUSPENDED_ERROR =\n 'This account has been suspended. Contact the site owner.'\n\n/** Resolved member-session state, see {@link readActiveMemberSession}. */\nexport type MemberSessionCheck =\n | { status: 'anonymous' }\n | { status: 'suspended'; memberId: string }\n | {\n status: 'active'\n memberId: string\n member: FirebaseFirestore.DocumentSnapshot\n }\n\n/**\n * Session + member-doc resolution for cookie-authenticated endpoints\n * (AGL-550). A verified cookie alone stopped being enough once console\n * suspension (AGL-546) landed: the HMAC session outlives the member's\n * standing, so every endpoint must also load the doc and check\n * `suspended`. That is one doc read per request — acceptable, and most\n * endpoints needed the member doc anyway. A deleted member doc reads as\n * `anonymous` (same as no cookie).\n */\nexport async function readActiveMemberSession(\n req: PluginApiRequest,\n hostId: string,\n): Promise<MemberSessionCheck> {\n const session = parseMemberSession(\n hostId,\n req.cookies?.[memberCookieName(hostId)],\n )\n if (!session) return { status: 'anonymous' }\n const { memberId, issuedAtMs } = session\n const member = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('siteMembers')\n .doc(memberId)\n .get()\n if (!member.exists) return { status: 'anonymous' }\n // Revoked in bulk (AGL-914): a session minted before the cut-off is dead\n // even though its signature is still good. Reads as `anonymous` rather\n // than `suspended` — the account is fine, this browser just holds a stale\n // cookie, and signing in again is the correct next step.\n const validFrom = Number(member.get(MEMBER_SESSIONS_VALID_FROM_FIELD) ?? 0)\n if (validFrom && issuedAtMs < validFrom) return { status: 'anonymous' }\n if (member.get('suspended') === true) {\n return { status: 'suspended', memberId }\n }\n return { status: 'active', memberId, member }\n}\n\n/**\n * Guard for cookie-authenticated member endpoints (AGL-550): resolves\n * the session AND the member doc, writing the rejection itself — 401\n * (`signInError`) when there is no usable session, 403 with the session\n * cookie cleared (mirroring membership-account's AGL-546 handling, so\n * the site stops presenting a signed-in shell) when the member is\n * suspended. Returns null after responding; handlers `if (!auth) return`.\n */\nexport async function requireActiveMember(\n req: PluginApiRequest,\n res: PluginApiResponse,\n hostId: string,\n signInError = 'Not signed in',\n): Promise<{\n memberId: string\n member: FirebaseFirestore.DocumentSnapshot\n} | null> {\n const session = await readActiveMemberSession(req, hostId)\n if (session.status === 'suspended') {\n setMemberCookie(res, hostId, null)\n res.status(403).json({ error: MEMBER_SUSPENDED_ERROR })\n return null\n }\n if (session.status !== 'active') {\n res.status(401).json({ error: signInError })\n return null\n }\n return { memberId: session.memberId, member: session.member }\n}\n"],"names":["createHash","createHmac","randomBytes","scryptSync","timingSafeEqual","signedInHintCookieName","firebaseAdmin","SESSION_TTL_MS","SESSION_SECRET","process","env","MEMBER_SESSION_SECRET","toString","hashMemberPassword","password","salt","hash","verifyMemberPassword","stored","String","split","candidate","expected","Buffer","from","length","Uint8Array","sign","payload","update","digest","mintMemberSession","hostId","memberId","Date","now","parseMemberSession","token","parts","tokenHost","expires","signature","Number","a","b","issuedAtMs","verifyMemberSession","RESET_TOKEN_TTL_MS","passwordFingerprint","passwordScrypt","mintPasswordResetToken","passwordResetTokenMemberId","verifyPasswordResetToken","currentPasswordScrypt","memberCookieName","replace","setMemberCookie","res","name","secure","NODE_ENV","base","maxAge","hint","setHeader","readMemberSession","req","raw","cookies","MEMBER_SESSIONS_VALID_FROM_FIELD","MEMBER_SUSPENDED_ERROR","readActiveMemberSession","member","session","status","app","firestore","collection","doc","get","exists","validFrom","requireActiveMember","signInError","json","error"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,UAAU,EACVC,WAAW,EACXC,UAAU,EACVC,eAAe,QACV,SAAQ;AAEf,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,aAAa,QAAQ,2BAA0B;AAExD;;;;;CAKC,GAED,MAAMC,iBAAiB,KAAK,KAAK,KAAK,KAAK;AAE3C,wEAAwE;AACxE,gDAAgD;AAChD,EAAE;AACF,0EAA0E;AAC1E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,qEAAqE;AACrE,6EAA6E;AAC7E,EAAE;AACF,2EAA2E;AAC3E,2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;IACvE,0EAA0E;IAC1E,yDAAyD;IACzD,MAAMO,YAAYvC,QAAO8B,cAAAA,OAAOO,GAAG,CAACV,6CAAXG,cAAgD;IACzE,IAAIS,aAAapC,aAAaoC,WAAW,OAAO;QAAEP,QAAQ;IAAY;IACtE,IAAIF,OAAOO,GAAG,CAAC,iBAAiB,MAAM;QACpC,OAAO;YAAEL,QAAQ;YAAazC;QAAS;IACzC;IACA,OAAO;QAAEyC,QAAQ;QAAUzC;QAAUuC;IAAO;AAC9C;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeU,oBACpBhB,GAAqB,EACrBT,GAAsB,EACtBzB,MAAc,EACdmD,cAAc,eAAe;IAK7B,MAAMV,UAAU,MAAMF,wBAAwBL,KAAKlC;IACnD,IAAIyC,QAAQC,MAAM,KAAK,aAAa;QAClClB,gBAAgBC,KAAKzB,QAAQ;QAC7ByB,IAAIiB,MAAM,CAAC,KAAKU,IAAI,CAAC;YAAEC,OAAOf;QAAuB;QACrD,OAAO;IACT;IACA,IAAIG,QAAQC,MAAM,KAAK,UAAU;QAC/BjB,IAAIiB,MAAM,CAAC,KAAKU,IAAI,CAAC;YAAEC,OAAOF;QAAY;QAC1C,OAAO;IACT;IACA,OAAO;QAAElD,UAAUwC,QAAQxC,QAAQ;QAAEuC,QAAQC,QAAQD,MAAM;IAAC;AAC9D"}
@@ -358,9 +358,24 @@ async function deliverEmail(store, ref, to, message, context, /** The moment and
358
358
  owedFor: 'order'
359
359
  }));
360
360
  await copies.settle(Boolean(result == null ? void 0 : result.sent));
361
+ // A message that did not leave is NOT sent (AGL-4227): thrown, so the
362
+ // caller releases the order's marker and reports this channel failed rather
363
+ // than writing "sent" on the order's timeline — the workspace's email limit,
364
+ // a suppression or a provider refusal all end here. Nothing is metered for
365
+ // it either: an email that never left is not a cost.
366
+ if (!(result == null ? void 0 : result.sent)) {
367
+ throw new Error(`Email not sent: ${describeUnsentEmail(result)}`);
368
+ }
361
369
  // Cost meter (AGL-1438), as every transactional store email.
362
370
  await meterHostEmail(ref.hostId);
363
371
  }
372
+ /** Why a store email did not leave, in the words the order's failure records. */ function describeUnsentEmail(result) {
373
+ const failure = result;
374
+ if ((failure == null ? void 0 : failure.reason) === 'rate-limited') {
375
+ return failure.detail || 'the workspace reached its email limit';
376
+ }
377
+ return (failure == null ? void 0 : failure.detail) || (failure == null ? void 0 : failure.reason) || 'delivery failed';
378
+ }
364
379
  /**
365
380
  * Sends one order text. A receipt goes at once — the buyer is at the counter
366
381
  * or the checkout waiting for it. Every later moment (shipped, delivered,