@aglyn/plugins-commerce 1.0.0-beta.183 → 1.0.0-beta.185
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 +1 -1
- package/package.json +13 -13
- package/src/lib/server/member-credentials.d.ts +73 -0
- package/src/lib/server/member-credentials.js +92 -0
- package/src/lib/server/member-credentials.js.map +1 -0
- package/src/lib/server/member-post.js +9 -5
- package/src/lib/server/member-post.js.map +1 -1
- package/src/lib/server/membership-admin-password.d.ts +6 -1
- package/src/lib/server/membership-admin-password.js +29 -7
- package/src/lib/server/membership-admin-password.js.map +1 -1
- package/src/lib/server/membership-admin-remove.d.ts +38 -0
- package/src/lib/server/membership-admin-remove.js +99 -0
- package/src/lib/server/membership-admin-remove.js.map +1 -0
- package/src/lib/server/membership-login.js +7 -2
- package/src/lib/server/membership-login.js.map +1 -1
- package/src/lib/server/membership-recover.js +4 -1
- package/src/lib/server/membership-recover.js.map +1 -1
- package/src/lib/server/membership-register.d.ts +3 -2
- package/src/lib/server/membership-register.js +11 -5
- package/src/lib/server/membership-register.js.map +1 -1
- package/src/lib/server/membership-reset.d.ts +9 -3
- package/src/lib/server/membership-reset.js +41 -22
- package/src/lib/server/membership-reset.js.map +1 -1
- package/src/lib/server/process-abandoned.js +12 -3
- package/src/lib/server/process-abandoned.js.map +1 -1
- package/src/lib/server/process-restock.js +14 -5
- package/src/lib/server/process-restock.js.map +1 -1
- package/src/lib/server.js +7 -3
- package/src/lib/server.js.map +1 -1
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { hostRoleCanWrite } from "@aglyn/aglyn/server";
|
|
17
|
+
import { firebaseAdmin, isImpersonationSession } from "@aglyn/tenant-data-admin";
|
|
18
|
+
import { isMemberDocumentId, memberCredentialRef } from "./member-credentials.js";
|
|
19
|
+
/**
|
|
20
|
+
* Remove a SITE MEMBER from the console (AGL-3308): the profile and its
|
|
21
|
+
* credential document, in one batch.
|
|
22
|
+
*
|
|
23
|
+
* The password hash lives in a collection no client can reach, so a client
|
|
24
|
+
* delete of the profile would leave it behind — a credential for an account
|
|
25
|
+
* the site owner removed. The rules therefore refuse a client delete of any
|
|
26
|
+
* member that has a credential document, and this route is the removal.
|
|
27
|
+
*
|
|
28
|
+
* Who may call it is who the rules let delete a profile before it: a site
|
|
29
|
+
* role that writes content (`admin`, `editor` or `author` in the host's
|
|
30
|
+
* `memberRoles`). A frozen site is refused by the dispatcher's lockdown gate
|
|
31
|
+
* before this runs, the half the rules spelled `hostWritesFrozen`.
|
|
32
|
+
*
|
|
33
|
+
* Removing the profile also ends every session the member holds:
|
|
34
|
+
* `readActiveMemberSession` reads a missing profile as signed out.
|
|
35
|
+
*
|
|
36
|
+
* Idempotent. A member already gone answers 200, and a credential document
|
|
37
|
+
* left without its profile is cleared on the way.
|
|
38
|
+
*/ export const membershipAdminRemoveHandler = async (req, res)=>{
|
|
39
|
+
var _req_headers_authorization, _ref, _ref1;
|
|
40
|
+
var _req_body, _req_body1;
|
|
41
|
+
if (req.method !== 'POST') {
|
|
42
|
+
return res.status(405).json({
|
|
43
|
+
error: 'Method not allowed'
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
const authorization = String((_req_headers_authorization = req.headers['authorization']) != null ? _req_headers_authorization : '');
|
|
47
|
+
const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : '';
|
|
48
|
+
if (!idToken) return res.status(401).json({
|
|
49
|
+
error: 'Unauthenticated'
|
|
50
|
+
});
|
|
51
|
+
const hostId = String((_ref = (_req_body = req.body) == null ? void 0 : _req_body.hostId) != null ? _ref : '');
|
|
52
|
+
const memberId = String((_ref1 = (_req_body1 = req.body) == null ? void 0 : _req_body1.memberId) != null ? _ref1 : '');
|
|
53
|
+
if (!hostId || !memberId) {
|
|
54
|
+
return res.status(400).json({
|
|
55
|
+
error: 'Missing hostId or memberId'
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (!isMemberDocumentId(memberId)) {
|
|
59
|
+
return res.status(400).json({
|
|
60
|
+
error: 'Unknown member'
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
var _hostSnapshot_get;
|
|
65
|
+
const app = firebaseAdmin.app();
|
|
66
|
+
const decoded = await app.auth().verifyIdToken(idToken);
|
|
67
|
+
if (!decoded.email_verified && !isImpersonationSession(decoded)) {
|
|
68
|
+
// The shape of emailUnverifiedResponse (AGL-479), by hand for the same
|
|
69
|
+
// reason as membership-admin-password: this is a (req, res) handler.
|
|
70
|
+
return res.status(403).json({
|
|
71
|
+
error: 'Verify your email to continue',
|
|
72
|
+
reason: 'email-unverified'
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const firestore = app.firestore();
|
|
76
|
+
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
77
|
+
const hostSnapshot = await hostRef.get();
|
|
78
|
+
const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
|
|
79
|
+
if (!hostSnapshot.exists || !hostRoleCanWrite(memberRole)) {
|
|
80
|
+
return res.status(403).json({
|
|
81
|
+
error: 'Not permitted'
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const batch = firestore.batch();
|
|
85
|
+
batch.delete(hostRef.collection('siteMembers').doc(memberId));
|
|
86
|
+
batch.delete(memberCredentialRef(hostRef, memberId));
|
|
87
|
+
await batch.commit();
|
|
88
|
+
return res.status(200).json({
|
|
89
|
+
ok: true
|
|
90
|
+
});
|
|
91
|
+
} catch (error) {
|
|
92
|
+
console.error(error);
|
|
93
|
+
return res.status(500).json({
|
|
94
|
+
error: 'Could not remove the member'
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
//# sourceMappingURL=membership-admin-remove.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-admin-remove.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 { hostRoleCanWrite, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { isMemberDocumentId, memberCredentialRef } from './member-credentials'\n\n/**\n * Remove a SITE MEMBER from the console (AGL-3308): the profile and its\n * credential document, in one batch.\n *\n * The password hash lives in a collection no client can reach, so a client\n * delete of the profile would leave it behind — a credential for an account\n * the site owner removed. The rules therefore refuse a client delete of any\n * member that has a credential document, and this route is the removal.\n *\n * Who may call it is who the rules let delete a profile before it: a site\n * role that writes content (`admin`, `editor` or `author` in the host's\n * `memberRoles`). A frozen site is refused by the dispatcher's lockdown gate\n * before this runs, the half the rules spelled `hostWritesFrozen`.\n *\n * Removing the profile also ends every session the member holds:\n * `readActiveMemberSession` reads a missing profile as signed out.\n *\n * Idempotent. A member already gone answers 200, and a credential document\n * left without its profile is cleared on the way.\n */\nexport const membershipAdminRemoveHandler: PluginApiHandler = async (\n req,\n res,\n) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const authorization = String(req.headers['authorization'] ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : ''\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n const hostId = String(req.body?.hostId ?? '')\n const memberId = String(req.body?.memberId ?? '')\n if (!hostId || !memberId) {\n return res.status(400).json({ error: 'Missing hostId or memberId' })\n }\n if (!isMemberDocumentId(memberId)) {\n return res.status(400).json({ error: 'Unknown member' })\n }\n\n try {\n const app = firebaseAdmin.app()\n const decoded = await app.auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n // The shape of emailUnverifiedResponse (AGL-479), by hand for the same\n // reason as membership-admin-password: this is a (req, res) handler.\n return res.status(403).json({\n error: 'Verify your email to continue',\n reason: 'email-unverified',\n })\n }\n const firestore = app.firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (!hostSnapshot.exists || !hostRoleCanWrite(memberRole)) {\n return res.status(403).json({ error: 'Not permitted' })\n }\n\n const batch = firestore.batch()\n batch.delete(hostRef.collection('siteMembers').doc(memberId))\n batch.delete(memberCredentialRef(hostRef, memberId))\n await batch.commit()\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Could not remove the member' })\n }\n}\n"],"names":["hostRoleCanWrite","firebaseAdmin","isImpersonationSession","isMemberDocumentId","memberCredentialRef","membershipAdminRemoveHandler","req","res","method","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","hostId","body","memberId","hostSnapshot","app","decoded","auth","verifyIdToken","email_verified","reason","firestore","host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AI,CAACzB,uBAAuBsB,UAAU;YAC/D,uEAAuE;YACvE,qEAAqE;YACrE,OAAOjB,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAC1BC,OAAO;gBACPiB,QAAQ;YACV;QACF;QACA,MAAMC,YAAYN,IAAIM,SAAS;QAC/B,MAAMC,UAAUD,UAAUE,UAAU,CAAC,SAASC,GAAG,CAACb;QAClD,MAAMG,eAAe,MAAMQ,QAAQG,GAAG;QACtC,MAAMC,aAAa,EAACZ,oBAAAA,aAAaW,GAAG,CAAC,0BAAjBX,oBAAmC,CAAC,EAAE,CAACE,QAAQW,GAAG,CAAC;QACvE,IAAI,CAACb,aAAac,MAAM,IAAI,CAACpC,iBAAiBkC,aAAa;YACzD,OAAO3B,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAgB;QACvD;QAEA,MAAM0B,QAAQR,UAAUQ,KAAK;QAC7BA,MAAMC,MAAM,CAACR,QAAQC,UAAU,CAAC,eAAeC,GAAG,CAACX;QACnDgB,MAAMC,MAAM,CAAClC,oBAAoB0B,SAAST;QAC1C,MAAMgB,MAAME,MAAM;QAClB,OAAOhC,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAE8B,IAAI;QAAK;IACzC,EAAE,OAAO7B,OAAO;QACd8B,QAAQ9B,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA8B;IACrE;AACF,EAAC"}
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { emitHostEvent } from "@aglyn/tenant-runtime";
|
|
18
18
|
import { readCartId } from "./cart-cookie.js";
|
|
19
19
|
import { MEMBER_SUSPENDED_ERROR, mintMemberSession, setMemberCookie, verifyMemberPassword } from "./membership.js";
|
|
20
|
+
import { readMemberPasswordHash } from "./member-credentials.js";
|
|
20
21
|
import { NO_CLIENT_ADDRESS_BUCKET, readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
|
|
21
22
|
// Best-effort per-instance brute-force damper (mirrors AGL-87 unlock).
|
|
22
23
|
const attemptsByIp = new Map();
|
|
@@ -56,9 +57,13 @@ const MAX_ATTEMPTS = 10;
|
|
|
56
57
|
}
|
|
57
58
|
try {
|
|
58
59
|
const firestore = firebaseAdmin.app().firestore();
|
|
59
|
-
const
|
|
60
|
+
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
61
|
+
const membersQuery = await hostRef.collection('siteMembers').where('email', '==', email).limit(1).get();
|
|
60
62
|
const memberDoc = membersQuery.docs[0];
|
|
61
|
-
|
|
63
|
+
// The credential document's hash, else the legacy copy on the profile
|
|
64
|
+
// (AGL-3308) — see member-credentials.ts.
|
|
65
|
+
const passwordScrypt = memberDoc ? await readMemberPasswordHash(hostRef, memberDoc) : undefined;
|
|
66
|
+
if (!memberDoc || !verifyMemberPassword(password, passwordScrypt)) {
|
|
62
67
|
return res.status(401).json({
|
|
63
68
|
error: 'Wrong email or password'
|
|
64
69
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-login.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { readCartId } from './cart-cookie'\nimport {\n MEMBER_SUSPENDED_ERROR,\n mintMemberSession,\n setMemberCookie,\n verifyMemberPassword,\n} from './membership'\nimport {\n NO_CLIENT_ADDRESS_BUCKET,\n readClientIp,\n} from '@aglyn/aglyn/app-utils/request-ip'\n\n// Best-effort per-instance brute-force damper (mirrors AGL-87 unlock).\nconst attemptsByIp = new Map<string, number[]>()\nconst WINDOW_MS = 60_000\nconst MAX_ATTEMPTS = 10\n\n/** Site member sign-in (AGL-109); sets the session cookie on success. */\nexport const membershipLoginHandler: 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 const password = String(req.body?.password ?? '')\n if (!hostId || !email || !password) {\n return res.status(400).json({ error: 'Invalid request' })\n }\n // Keeps counting under the no-address bucket rather than being skipped: this\n // damper guards a PASSWORD, and one that stops counting is a password anyone\n // can grind. On a deployment that cannot name its callers the whole site\n // shares one attempt budget, which is the direction to be wrong in here.\n const ip =\n readClientIp(req.headers, { remoteAddress: req.socket?.remoteAddress }) ??\n NO_CLIENT_ADDRESS_BUCKET\n const now = Date.now()\n const attempts = (attemptsByIp.get(ip) ?? []).filter(\n (at) => now - at < WINDOW_MS,\n )\n attempts.push(now)\n attemptsByIp.set(ip, attempts)\n if (attempts.length > MAX_ATTEMPTS) {\n return res.status(429).json({ error: 'Too many attempts' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const membersQuery = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('siteMembers')\n .where('email', '==', email)\n .limit(1)\n .get()\n const memberDoc = membersQuery.docs[0]\n if (\n !memberDoc ||\n !verifyMemberPassword(password, memberDoc.get('passwordScrypt'))\n ) {\n return res.status(401).json({ error: 'Wrong email or password' })\n }\n // Suspension gate (AGL-546): console-suspended members cannot sign in.\n // Checked after the password so the message never leaks account\n // existence to guessers who don't hold the credentials.\n if (memberDoc.get('suspended') === true) {\n return res.status(401).json({ error: MEMBER_SUSPENDED_ERROR })\n }\n // Event trigger (AGL-128/148).\n await emitHostEvent(hostId, 'memberSignIn', { email })\n // Cart linkage (AGL-294): stamp the guest cart with the member so\n // abandoned-cart and analytics can attribute it.\n //\n // AGL-1763: `update()`, never `set(..., { merge: true })`. `cartId` is the\n // `aglyn_cart_{hostId}` cookie verbatim — the one value on this request the\n // client chooses — and a merge-set against a missing path CREATES the\n // document. So a member could mint `carts/{anything}` at will, one document\n // per sign-in, each holding a `customerId` and nothing else: no `lines`, no\n // `createdAtMs`, no `updatedAtMs`. Inert to read — `cart.ts` treats a\n // missing `lines` as `[]` — but real storage on the merchant's Firestore\n // and real weight in the per-host document count, growing without bound and\n // belonging to no basket anyone ever filled.\n //\n // Nor is the cookie confined to one document. `CollectionReference.doc()`\n // appends a SLASH-SEPARATED path and refuses it only when the component\n // count comes out odd, so a cookie of `a/b/c` wrote to `carts/a/b/c` — a\n // document at a nesting of the caller's choosing.\n //\n // Refusing loses nothing, which is why this is a plain refusal rather than\n // AGL-1760's refuse-and-record: a cart that does not exist holds no lines,\n // so there is no basket to attribute and no work to strand. `cart.ts` is\n // what creates a cart — on the first POST that puts something in it, with\n // the whole document written. This only ever stamps one.\n //\n // AGL-1769 moved the cookie's name and its validity rule into\n // `cart-cookie.ts`, so a slash-bearing value never reaches `.doc()` from\n // here at all. `update()` stays: the rule bounds the value to ONE document\n // id, and whether THAT document exists is a separate question only the\n // write can answer.\n const cartId = readCartId(req.cookies, hostId)\n if (cartId) {\n try {\n await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('carts')\n .doc(cartId)\n .update({ customerId: memberDoc.id })\n } catch (error) {\n // Absent cart, malformed cookie, or a Firestore failure — none of them\n // may fail a sign-in that has already succeeded, so this stays\n // swallowed as it was. It is no longer SILENT, though: the old\n // `.catch(() => undefined)` could not tell a missing cart from an\n // outage. And the guard is a `try` rather than a `.catch()` because\n // `.doc()` throws SYNCHRONOUSLY on an odd-component path, outside the\n // promise the old handler covered — a mangled cookie used to 500 the\n // member's own sign-in.\n console.error('Cart linkage failed', hostId, error)\n }\n }\n setMemberCookie(res, hostId, mintMemberSession(hostId, memberDoc.id))\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Sign-in failed' })\n }\n}\n"],"names":["firebaseAdmin","emitHostEvent","readCartId","MEMBER_SUSPENDED_ERROR","mintMemberSession","setMemberCookie","verifyMemberPassword","NO_CLIENT_ADDRESS_BUCKET","readClientIp","attemptsByIp","Map","WINDOW_MS","MAX_ATTEMPTS","membershipLoginHandler","req","res","method","status","json","error","hostId","String","body","email","trim","toLowerCase","password","ip","headers","remoteAddress","socket","now","Date","attempts","get","filter","at","push","set","length","firestore","app","membersQuery","collection","doc","where","limit","memberDoc","docs","cartId","cookies","update","customerId","id","console","ok"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,aAAa,QAAQ,wBAAuB;AACrD,SAASC,UAAU,QAAQ,mBAAe;AAC1C,SACEC,sBAAsB,EACtBC,iBAAiB,EACjBC,eAAe,EACfC,oBAAoB,QACf,kBAAc;AACrB,SACEC,wBAAwB,EACxBC,YAAY,QACP,oCAAmC;AAE1C,uEAAuE;AACvE,MAAMC,eAAe,IAAIC;AACzB,MAAMC,YAAY;AAClB,MAAMC,eAAe;AAErB,uEAAuE,GACvE,OAAO,MAAMC,yBAA2C,OAAOC,KAAKC;4BAiBhEP,eAGgBC;QAhBIK,WACDA,YAGGA,YASqBA;IAhB7C,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,QAAQF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,KAAK,oBAAI,IACrCC,IAAI,GACJC,WAAW;IACd,MAAMC,WAAWL,iBAAOP,aAAAA,IAAIQ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,OAAO;QAAiB;IACxD;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-login.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport { readCartId } from './cart-cookie'\nimport {\n MEMBER_SUSPENDED_ERROR,\n mintMemberSession,\n setMemberCookie,\n verifyMemberPassword,\n} from './membership'\nimport { readMemberPasswordHash } from './member-credentials'\nimport {\n NO_CLIENT_ADDRESS_BUCKET,\n readClientIp,\n} from '@aglyn/aglyn/app-utils/request-ip'\n\n// Best-effort per-instance brute-force damper (mirrors AGL-87 unlock).\nconst attemptsByIp = new Map<string, number[]>()\nconst WINDOW_MS = 60_000\nconst MAX_ATTEMPTS = 10\n\n/** Site member sign-in (AGL-109); sets the session cookie on success. */\nexport const membershipLoginHandler: 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 const password = String(req.body?.password ?? '')\n if (!hostId || !email || !password) {\n return res.status(400).json({ error: 'Invalid request' })\n }\n // Keeps counting under the no-address bucket rather than being skipped: this\n // damper guards a PASSWORD, and one that stops counting is a password anyone\n // can grind. On a deployment that cannot name its callers the whole site\n // shares one attempt budget, which is the direction to be wrong in here.\n const ip =\n readClientIp(req.headers, { remoteAddress: req.socket?.remoteAddress }) ??\n NO_CLIENT_ADDRESS_BUCKET\n const now = Date.now()\n const attempts = (attemptsByIp.get(ip) ?? []).filter(\n (at) => now - at < WINDOW_MS,\n )\n attempts.push(now)\n attemptsByIp.set(ip, attempts)\n if (attempts.length > MAX_ATTEMPTS) {\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 membersQuery = await hostRef\n .collection('siteMembers')\n .where('email', '==', email)\n .limit(1)\n .get()\n const memberDoc = membersQuery.docs[0]\n // The credential document's hash, else the legacy copy on the profile\n // (AGL-3308) — see member-credentials.ts.\n const passwordScrypt = memberDoc\n ? await readMemberPasswordHash(hostRef, memberDoc)\n : undefined\n if (!memberDoc || !verifyMemberPassword(password, passwordScrypt)) {\n return res.status(401).json({ error: 'Wrong email or password' })\n }\n // Suspension gate (AGL-546): console-suspended members cannot sign in.\n // Checked after the password so the message never leaks account\n // existence to guessers who don't hold the credentials.\n if (memberDoc.get('suspended') === true) {\n return res.status(401).json({ error: MEMBER_SUSPENDED_ERROR })\n }\n // Event trigger (AGL-128/148).\n await emitHostEvent(hostId, 'memberSignIn', { email })\n // Cart linkage (AGL-294): stamp the guest cart with the member so\n // abandoned-cart and analytics can attribute it.\n //\n // AGL-1763: `update()`, never `set(..., { merge: true })`. `cartId` is the\n // `aglyn_cart_{hostId}` cookie verbatim — the one value on this request the\n // client chooses — and a merge-set against a missing path CREATES the\n // document. So a member could mint `carts/{anything}` at will, one document\n // per sign-in, each holding a `customerId` and nothing else: no `lines`, no\n // `createdAtMs`, no `updatedAtMs`. Inert to read — `cart.ts` treats a\n // missing `lines` as `[]` — but real storage on the merchant's Firestore\n // and real weight in the per-host document count, growing without bound and\n // belonging to no basket anyone ever filled.\n //\n // Nor is the cookie confined to one document. `CollectionReference.doc()`\n // appends a SLASH-SEPARATED path and refuses it only when the component\n // count comes out odd, so a cookie of `a/b/c` wrote to `carts/a/b/c` — a\n // document at a nesting of the caller's choosing.\n //\n // Refusing loses nothing, which is why this is a plain refusal rather than\n // AGL-1760's refuse-and-record: a cart that does not exist holds no lines,\n // so there is no basket to attribute and no work to strand. `cart.ts` is\n // what creates a cart — on the first POST that puts something in it, with\n // the whole document written. This only ever stamps one.\n //\n // AGL-1769 moved the cookie's name and its validity rule into\n // `cart-cookie.ts`, so a slash-bearing value never reaches `.doc()` from\n // here at all. `update()` stays: the rule bounds the value to ONE document\n // id, and whether THAT document exists is a separate question only the\n // write can answer.\n const cartId = readCartId(req.cookies, hostId)\n if (cartId) {\n try {\n await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('carts')\n .doc(cartId)\n .update({ customerId: memberDoc.id })\n } catch (error) {\n // Absent cart, malformed cookie, or a Firestore failure — none of them\n // may fail a sign-in that has already succeeded, so this stays\n // swallowed as it was. It is no longer SILENT, though: the old\n // `.catch(() => undefined)` could not tell a missing cart from an\n // outage. And the guard is a `try` rather than a `.catch()` because\n // `.doc()` throws SYNCHRONOUSLY on an odd-component path, outside the\n // promise the old handler covered — a mangled cookie used to 500 the\n // member's own sign-in.\n console.error('Cart linkage failed', hostId, error)\n }\n }\n setMemberCookie(res, hostId, mintMemberSession(hostId, memberDoc.id))\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Sign-in failed' })\n }\n}\n"],"names":["firebaseAdmin","emitHostEvent","readCartId","MEMBER_SUSPENDED_ERROR","mintMemberSession","setMemberCookie","verifyMemberPassword","readMemberPasswordHash","NO_CLIENT_ADDRESS_BUCKET","readClientIp","attemptsByIp","Map","WINDOW_MS","MAX_ATTEMPTS","membershipLoginHandler","req","res","method","status","json","error","hostId","String","body","email","trim","toLowerCase","password","ip","headers","remoteAddress","socket","now","Date","attempts","get","filter","at","push","set","length","firestore","app","hostRef","collection","doc","membersQuery","where","limit","memberDoc","docs","passwordScrypt","undefined","cartId","cookies","update","customerId","id","console","ok"],"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E;QACF,0EAA0E;QAC1E,wEAAwE;QACxE,yEAAyE;QACzE,kDAAkD;QAClD,EAAE;QACF,2EAA2E;QAC3E,2EAA2E;QAC3E,yEAAyE;QACzE,0EAA0E;QAC1E,yDAAyD;QACzD,EAAE;QACF,8DAA8D;QAC9D,yEAAyE;QACzE,2EAA2E;QAC3E,uEAAuE;QACvE,oBAAoB;QACpB,MAAM6B,SAASnD,WAAWa,IAAIuC,OAAO,EAAEjC;QACvC,IAAIgC,QAAQ;YACV,IAAI;gBACF,MAAMZ,UACHG,UAAU,CAAC,SACXC,GAAG,CAACxB,QACJuB,UAAU,CAAC,SACXC,GAAG,CAACQ,QACJE,MAAM,CAAC;oBAAEC,YAAYP,UAAUQ,EAAE;gBAAC;YACvC,EAAE,OAAOrC,OAAO;gBACd,uEAAuE;gBACvE,+DAA+D;gBAC/D,+DAA+D;gBAC/D,kEAAkE;gBAClE,oEAAoE;gBACpE,sEAAsE;gBACtE,qEAAqE;gBACrE,wBAAwB;gBACxBsC,QAAQtC,KAAK,CAAC,uBAAuBC,QAAQD;YAC/C;QACF;QACAf,gBAAgBW,KAAKK,QAAQjB,kBAAkBiB,QAAQ4B,UAAUQ,EAAE;QACnE,OAAOzC,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEwC,IAAI;QAAK;IACzC,EAAE,OAAOvC,OAAO;QACdsC,QAAQtC,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC"}
|
|
@@ -18,6 +18,7 @@ import { hostPublicOrigin } from "@aglyn/aglyn/server";
|
|
|
18
18
|
import { consumeMembershipRecoverAttempt, consumeMembershipRecoverSend, firebaseAdmin, getOrgForHost, hostSendingIdentity, isEmailSuppressed, meterHostEmail, RECOVER_MIN_MEMBER_AGE_MS } from "@aglyn/tenant-data-admin";
|
|
19
19
|
import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
|
|
20
20
|
import { mintPasswordResetToken } from "./membership.js";
|
|
21
|
+
import { readMemberPasswordHash } from "./member-credentials.js";
|
|
21
22
|
import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
|
|
22
23
|
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
23
24
|
/**
|
|
@@ -173,7 +174,9 @@ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
173
174
|
ok: true
|
|
174
175
|
});
|
|
175
176
|
}
|
|
176
|
-
|
|
177
|
+
// Bound to the hash sign-in checks: the credential document's, else the
|
|
178
|
+
// legacy copy on the profile (AGL-3308).
|
|
179
|
+
const token = mintPasswordResetToken(hostId, memberDoc.id, await readMemberPasswordHash(hostRef, memberDoc));
|
|
177
180
|
// `hostPublicOrigin`, not a hand-rolled apex (AGL-2195). This URL is
|
|
178
181
|
// minted server-side and mailed out, so a wrong apex is not a display
|
|
179
182
|
// bug — it is a live link on somebody else's domain.
|
|
@@ -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 { mintPasswordResetToken } from './membership'\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 const token = mintPasswordResetToken(\n hostId,\n memberDoc.id,\n memberDoc.get('passwordScrypt'),\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 await sendEmail({\n to: email,\n subject: `Reset your ${siteName} password`,\n text:\n `Someone asked to reset the password for your ${siteName} ` +\n 'account. If that was you, set a new password here:\\n\\n' +\n `${resetUrl}\\n\\n` +\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 fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'membership recovery',\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","mintPasswordResetToken","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","to","subject","text","fromName","sendingIdentity","audience","context"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,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,sBAAsB,QAAQ,kBAAc;AACrD,SAASC,YAAY,QAAQ,oCAAmC;AAEhE,MAAMC,gBAAgB;AAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GACD,OAAO,MAAMC,2BAA6C,OAAOC,KAAKC;;QAI9CD,WACDA,YASJA;IAbjB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,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FU,UAAUP,SAASO,QAAQ;YAC3BC,iBAAiB,MAAMrE,oBAAoBgB;YAC3CsD,UAAU;YACVC,SAAS;QACX;QACA,wEAAwE;QACxE,wEAAwE;QACxE,iBAAiB;QACjB,MAAMrE,eAAec;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 { 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, else the\n // legacy copy on the profile (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 await sendEmail({\n to: email,\n subject: `Reset your ${siteName} password`,\n text:\n `Someone asked to reset the password for your ${siteName} ` +\n 'account. If that was you, set a new password here:\\n\\n' +\n `${resetUrl}\\n\\n` +\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 fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'membership recovery',\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","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","to","subject","text","fromName","sendingIdentity","audience","context"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,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,sBAAsB,QAAQ,kBAAc;AACrD,SAASC,sBAAsB,QAAQ,0BAAsB;AAC7D,SAASC,YAAY,QAAQ,oCAAmC;AAEhE,MAAMC,gBAAgB;AAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GACD,OAAO,MAAMC,2BAA6C,OAAOC,KAAKC;;QAI9CD,WACDA,YASJA;IAbjB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,QAAQ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AoBiB;YAC3CsD,UAAU;YACVC,SAAS;QACX;QACA,wEAAwE;QACxE,wEAAwE;QACxE,iBAAiB;QACjB,MAAMtE,eAAee;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"}
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import type { PluginApiHandler } from '@aglyn/aglyn/server';
|
|
18
18
|
/**
|
|
19
|
-
* Site member sign-up (AGL-109): creates the member record
|
|
20
|
-
* doubles as a lead, and signs the
|
|
19
|
+
* Site member sign-up (AGL-109): creates the member record and its credential
|
|
20
|
+
* document (the scrypt hash, AGL-3308), doubles as a lead, and signs the
|
|
21
|
+
* visitor in via the session cookie.
|
|
21
22
|
*/
|
|
22
23
|
export declare const membershipRegisterHandler: PluginApiHandler;
|
|
@@ -20,10 +20,12 @@ import { firebaseAdmin, recordVisitorRecordCeilingTrip, resolveCampaignTouch } f
|
|
|
20
20
|
import { emitHostEvent } from "@aglyn/tenant-runtime";
|
|
21
21
|
import recordCapturedContact from "@aglyn/aglyn/plugin-manager/record-captured-contact";
|
|
22
22
|
import { hashMemberPassword, mintMemberSession, setMemberCookie } from "./membership.js";
|
|
23
|
+
import { memberCredentialRef } from "./member-credentials.js";
|
|
23
24
|
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
24
25
|
/**
|
|
25
|
-
* Site member sign-up (AGL-109): creates the member record
|
|
26
|
-
* doubles as a lead, and signs the
|
|
26
|
+
* Site member sign-up (AGL-109): creates the member record and its credential
|
|
27
|
+
* document (the scrypt hash, AGL-3308), doubles as a lead, and signs the
|
|
28
|
+
* visitor in via the session cookie.
|
|
27
29
|
*/ export const membershipRegisterHandler = async (req, res)=>{
|
|
28
30
|
var _ref, _ref1, _ref2, _ref3;
|
|
29
31
|
var _req_body, _req_body1, _req_body2, _req_body3, _req_body4;
|
|
@@ -117,11 +119,15 @@ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
117
119
|
duplicate: false,
|
|
118
120
|
ceiling: verdict.ceiling
|
|
119
121
|
};
|
|
122
|
+
// The hash goes to the credential document, which no client can read
|
|
123
|
+
// (AGL-3308), and in this transaction, so a member never exists without
|
|
124
|
+
// the password they chose. The profile below is what the console lists.
|
|
125
|
+
tx.set(memberCredentialRef(hostRef, memberRef.id), {
|
|
126
|
+
passwordScrypt: hashMemberPassword(password)
|
|
127
|
+
});
|
|
120
128
|
tx.create(memberRef, _extends({
|
|
121
129
|
email
|
|
122
|
-
}, displayName ? memberNameSearchFields(displayName) : {}, {
|
|
123
|
-
passwordScrypt: hashMemberPassword(password)
|
|
124
|
-
}, marketingConsent ? marketingConsentFieldsForHost(hostId, Date.now()) : {}, {
|
|
130
|
+
}, displayName ? memberNameSearchFields(displayName) : {}, marketingConsent ? marketingConsentFieldsForHost(hostId, Date.now()) : {}, {
|
|
125
131
|
createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
|
|
126
132
|
}));
|
|
127
133
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-register.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 { memberNameSearchFields } from './member-name-search'\nimport {\n checkVisitorRecordCeiling,\n HOST_TOKENS,\n marketingConsentFieldsForHost,\n SITE_MEMBER_CEILING_CODE,\n SITE_MEMBER_UNAVAILABLE_MESSAGE,\n SITE_MEMBERS_MAX_PER_HOST,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n recordVisitorRecordCeilingTrip,\n resolveCampaignTouch,\n} from '@aglyn/tenant-data-admin'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n hashMemberPassword,\n mintMemberSession,\n setMemberCookie,\n} from './membership'\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Site member sign-up (AGL-109): creates the member record (scrypt hash),\n * doubles as a lead, and signs the visitor in via the session cookie.\n */\nexport const membershipRegisterHandler: 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 const password = String(req.body?.password ?? '')\n const displayName = String(req.body?.displayName ?? '')\n .trim()\n .slice(0, 80)\n // Explicit opt-in checkbox (AGL-2499) — never inferred from signing up.\n const marketingConsent = req.body?.marketingConsent === true\n if (!hostId) return res.status(400).json({ error: 'Missing host' })\n if (!EMAIL_PATTERN.test(email)) {\n return res.status(400).json({ error: 'Enter a valid email' })\n }\n if (password.length < 8) {\n return res\n .status(400)\n .json({ error: 'Password must be at least 8 characters' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // Member accounts are UNLIMITED on every plan (AGL-889) — no seat or\n // quota check belongs here. Audience monetization happens downstream:\n // contact bands meter the CRM projection (AGL-890) and paid\n // memberships carry the plan's digital transaction fee (AGL-892).\n //\n // `SITE_MEMBERS_MAX_PER_HOST` below is NOT that check and does not make\n // it one (AGL-1529). It is a flat PLATFORM ceiling — same number on every\n // plan, no `OrgEntitlements` key, nothing on the price list — and it\n // exists because this handler is reachable by an ANONYMOUS VISITOR, so\n // without it the collection was bounded only by a per-(host, IP) rate\n // limiter that fails soft and bounds the RATE rather than the TOTAL. An\n // abuse control is not something we sell; \"unlimited member accounts on\n // every plan\" stays literally true.\n const membersRef = hostRef.collection('siteMembers')\n const memberRef = membersRef.doc()\n /*\n * COUNT, DEDUPE AND CREATE IN ONE TRANSACTION (AGL-1529, the AGL-2231\n * treatment).\n *\n * Read-then-decide-then-`set()` is the create-time quota that laundered\n * everywhere else in this repo: N concurrent sign-ups each read the same\n * pre-count, each find room, and each land — and nothing re-counts\n * afterwards, so the extra accounts are permanent. The fix is WHEN the\n * count is evaluated, not the counting rule.\n * `Transaction.get(AggregateQuery)` serialises the count against a\n * concurrent create into this collection: the loser retries, re-reads the\n * higher count and is refused. The duplicate-email read moves inside for\n * free, which also closes the smaller race it always had — two\n * simultaneous sign-ups on one address both saw `empty` and both wrote.\n *\n * ALL READS BEFORE THE WRITE, which Firestore requires.\n *\n * The scrypt hash sits between the last read and the create ON PURPOSE.\n * It is ~100 ms of CPU and it is the most expensive thing in the request,\n * so a refused sign-up must never pay it — hashing before the transaction\n * would hand a flood a CPU amplifier on exactly the path the ceiling\n * exists to contain, and would also be a regression, since today a\n * duplicate-email refusal does not hash either. It is a pure computation,\n * not an effect, so it does not violate the \"nothing happens in a\n * transaction body\" rule the sibling routes state.\n *\n * A refusal is returned as DATA and rendered outside: a body that can run\n * several times must not be the place a response is built.\n */\n const refusal = await firestore.runTransaction(async (tx) => {\n const existing = await tx.get(membersRef.where('email', '==', email).limit(1))\n if (!existing.empty) return { duplicate: true, ceiling: 0 }\n const used = (await tx.get(membersRef.count())).data().count\n // Live documents only, so removing a member in the inbox frees the slot.\n const verdict = checkVisitorRecordCeiling(used, SITE_MEMBERS_MAX_PER_HOST)\n if (verdict.exceeded) return { duplicate: false, ceiling: verdict.ceiling }\n tx.create(memberRef, {\n email,\n ...(displayName ? memberNameSearchFields(displayName) : {}),\n passwordScrypt: hashMemberPassword(password),\n /*\n * The checkbox is PERSISTED on the member, not only forwarded.\n *\n * It reached the lead and the contact from the two lines below and\n * was dropped for this document, so `hosts/{hostId}/siteMembers` had\n * no consent field of any kind and `audience: 'members'` had nothing\n * for the send-time join to read — the audience could not be filtered\n * even in principle (`docs/specs/email-overhaul.md` §1d/§3f). The\n * other two documents are not a substitute: a member is deduped in\n * this transaction while leads append every time, and contacts are\n * ORG-scoped where a member is the site's own.\n *\n * Written only when ticked. Signing up is not opting in — that is why\n * the checkbox exists and why it defaults unchecked — so the omitted\n * case stores nothing and reads back as an unrecorded basis rather\n * than as a refusal.\n *\n * Under this site's key even though `siteMembers` already lives\n * beneath it, so that one reader answers for every silo — see\n * `addHostLead`, which makes the same write for the same reason.\n */\n ...(marketingConsent\n ? marketingConsentFieldsForHost(hostId, Date.now())\n : {}),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n return null\n })\n if (refusal?.duplicate) {\n return res.status(409).json({ error: 'That email is already a member' })\n }\n if (refusal) {\n // Visible to the HOST — the rule that a control nobody can see in\n // the console did not ship. Durable counter + one notification.\n await recordVisitorRecordCeilingTrip({\n hostRef,\n hostId,\n kind: 'siteMembers',\n ceiling: refusal.ceiling,\n })\n // Opaque to the VISITOR, who is a stranger to this site and not our\n // customer (AGL-1666's rules, restated in the message's own docblock).\n // The one genuinely useful thing to hand them is a door that still\n // opens, so the site's OWN published support address rides along when\n // it has one — read through the host-token registry, whose description\n // of this field is literally \"where visitors should write for help\".\n // Nothing else off the host document may leave the console.\n const contact = HOST_TOKENS['supportEmail']?.resolve(\n hostSnapshot.data() as any,\n )\n return res.status(429).json({\n error: SITE_MEMBER_UNAVAILABLE_MESSAGE,\n // Machine-readable, because the dispatcher's rate limiter answers 429\n // too and the status therefore discriminates nothing.\n code: SITE_MEMBER_CEILING_CODE,\n ...(contact ? { contact } : {}),\n })\n }\n // Sign-ups double as leads for the site owner (AGL-109), through the one\n // writer that enforces `LEADS_MAX_PER_HOST` (AGL-1529). A refused lead\n // never fails the sign-up: the visitor asked for an account, not for a\n // lead record, and the trip is recorded for the owner either way.\n /*\n * THE CAMPAIGN TOUCH, RESOLVED ONCE FOR THE WHOLE SIGN-UP.\n *\n * A sign-up is the identify moment for a visitor who has been anonymous\n * until now, and it writes two records that a campaign can be credited\n * with — the lead and the contact. One resolve, one keyed read, and the\n * two cannot end up naming different campaigns.\n *\n * The MEMBER record itself is not attributed. A member is an account the\n * visitor holds and the lead is the site's record of the same act, so\n * crediting both would count one sign-up twice under two names.\n */\n const signedUpAtMs = Date.now()\n const campaignTouch = await resolveCampaignTouch({\n hostId,\n wire: req.body?.campaignTouch,\n email,\n atMs: signedUpAtMs,\n })\n /*\n * Contacts ingestion (AGL-197), reported to whichever plugin keeps people\n * rather than written by this one (AGL-3080). Commerce knows it just met\n * somebody; what a person record is belongs to the plugin that models it,\n * and a workspace that keeps none is a quiet, correct answer here.\n */\n /*\n * A member account is a RELATIONSHIP (AGL-3232): the person is a\n * contact from this moment, and an open lead the site held for the\n * address is closed as converted onto that contact by the record\n * system — a sign-up files no lead of its own any more, the way a\n * portal user is a contact and not a lead in Salesforce.\n */\n void recordCapturedContact({\n /*\n * Not resolved here. The record system keys a person on the SITE they\n * were met on, so this costs the capture nothing — and resolving it\n * would put a Firestore read in front of the writer, which is the one\n * thing `recordCapturedContact` asks a door not to do.\n */\n orgId: '',\n hostId,\n identity: { email, name: displayName || undefined },\n interaction: {\n source: 'member',\n refId: memberRef.id,\n summary: 'Joined as a member',\n },\n surface: 'relationship',\n // An account is a subscription to the site, not an enquiry (AGL-2612):\n // the stage on the contact says only that the person asked to be\n // kept. A floor, so a customer who opens an account stays a customer.\n lifecycleFloor: 'subscriber',\n ...(marketingConsent ? { marketingConsent: true } : {}),\n // Where the visitor ARRIVED from — a fact about this visit and not\n // about the person, which is what `detail` carries.\n ...(campaignTouch ? { detail: { campaignTouch } } : {}),\n })\n // Event trigger (AGL-128/148). A sign-up is no longer a lead (AGL-3232),\n // so the `lead` event is the lead surfaces' to emit.\n await emitHostEvent(hostId, 'memberSignUp', { email })\n setMemberCookie(res, hostId, mintMemberSession(hostId, memberRef.id))\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Sign-up failed' })\n }\n}\n"],"names":["memberNameSearchFields","checkVisitorRecordCeiling","HOST_TOKENS","marketingConsentFieldsForHost","SITE_MEMBER_CEILING_CODE","SITE_MEMBER_UNAVAILABLE_MESSAGE","SITE_MEMBERS_MAX_PER_HOST","firebaseAdmin","recordVisitorRecordCeilingTrip","resolveCampaignTouch","emitHostEvent","recordCapturedContact","hashMemberPassword","mintMemberSession","setMemberCookie","EMAIL_PATTERN","membershipRegisterHandler","req","res","method","status","json","error","hostId","String","body","email","trim","toLowerCase","password","displayName","slice","marketingConsent","test","length","firestore","app","hostRef","collection","doc","hostSnapshot","get","exists","membersRef","memberRef","refusal","runTransaction","tx","existing","where","limit","empty","duplicate","ceiling","used","count","data","verdict","exceeded","create","passwordScrypt","Date","now","createdAt","FieldValue","serverTimestamp","kind","contact","resolve","code","signedUpAtMs","campaignTouch","wire","atMs","orgId","identity","name","undefined","interaction","source","refId","id","summary","surface","lifecycleFloor","detail","ok","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,sBAAsB,QAAQ,0BAAsB;AAC7D,SACEC,yBAAyB,EACzBC,WAAW,EACXC,6BAA6B,EAC7BC,wBAAwB,EACxBC,+BAA+B,EAC/BC,yBAAyB,QACpB,sBAAqB;AAC5B,SACEC,aAAa,EACbC,8BAA8B,EAC9BC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,aAAa,QA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AGjDuC,gBAAgB;YAAEc,QAAQ;gBAAEd;YAAc;QAAE,IAAI,CAAC;QAEvD,yEAAyE;QACzE,qDAAqD;QACrD,MAAM7D,cAAca,QAAQ,gBAAgB;YAAEG;QAAM;QACpDZ,gBAAgBI,KAAKK,QAAQV,kBAAkBU,QAAQqB,UAAUqC,EAAE;QACnE,OAAO/D,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEiE,IAAI;QAAK;IACzC,EAAE,OAAOhE,OAAO;QACdiE,QAAQjE,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-register.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 { memberNameSearchFields } from './member-name-search'\nimport {\n checkVisitorRecordCeiling,\n HOST_TOKENS,\n marketingConsentFieldsForHost,\n SITE_MEMBER_CEILING_CODE,\n SITE_MEMBER_UNAVAILABLE_MESSAGE,\n SITE_MEMBERS_MAX_PER_HOST,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n recordVisitorRecordCeilingTrip,\n resolveCampaignTouch,\n} from '@aglyn/tenant-data-admin'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n hashMemberPassword,\n mintMemberSession,\n setMemberCookie,\n} from './membership'\nimport { memberCredentialRef } from './member-credentials'\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Site member sign-up (AGL-109): creates the member record and its credential\n * document (the scrypt hash, AGL-3308), doubles as a lead, and signs the\n * visitor in via the session cookie.\n */\nexport const membershipRegisterHandler: 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 const password = String(req.body?.password ?? '')\n const displayName = String(req.body?.displayName ?? '')\n .trim()\n .slice(0, 80)\n // Explicit opt-in checkbox (AGL-2499) — never inferred from signing up.\n const marketingConsent = req.body?.marketingConsent === true\n if (!hostId) return res.status(400).json({ error: 'Missing host' })\n if (!EMAIL_PATTERN.test(email)) {\n return res.status(400).json({ error: 'Enter a valid email' })\n }\n if (password.length < 8) {\n return res\n .status(400)\n .json({ error: 'Password must be at least 8 characters' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // Member accounts are UNLIMITED on every plan (AGL-889) — no seat or\n // quota check belongs here. Audience monetization happens downstream:\n // contact bands meter the CRM projection (AGL-890) and paid\n // memberships carry the plan's digital transaction fee (AGL-892).\n //\n // `SITE_MEMBERS_MAX_PER_HOST` below is NOT that check and does not make\n // it one (AGL-1529). It is a flat PLATFORM ceiling — same number on every\n // plan, no `OrgEntitlements` key, nothing on the price list — and it\n // exists because this handler is reachable by an ANONYMOUS VISITOR, so\n // without it the collection was bounded only by a per-(host, IP) rate\n // limiter that fails soft and bounds the RATE rather than the TOTAL. An\n // abuse control is not something we sell; \"unlimited member accounts on\n // every plan\" stays literally true.\n const membersRef = hostRef.collection('siteMembers')\n const memberRef = membersRef.doc()\n /*\n * COUNT, DEDUPE AND CREATE IN ONE TRANSACTION (AGL-1529, the AGL-2231\n * treatment).\n *\n * Read-then-decide-then-`set()` is the create-time quota that laundered\n * everywhere else in this repo: N concurrent sign-ups each read the same\n * pre-count, each find room, and each land — and nothing re-counts\n * afterwards, so the extra accounts are permanent. The fix is WHEN the\n * count is evaluated, not the counting rule.\n * `Transaction.get(AggregateQuery)` serialises the count against a\n * concurrent create into this collection: the loser retries, re-reads the\n * higher count and is refused. The duplicate-email read moves inside for\n * free, which also closes the smaller race it always had — two\n * simultaneous sign-ups on one address both saw `empty` and both wrote.\n *\n * ALL READS BEFORE THE WRITE, which Firestore requires.\n *\n * The scrypt hash sits between the last read and the create ON PURPOSE.\n * It is ~100 ms of CPU and it is the most expensive thing in the request,\n * so a refused sign-up must never pay it — hashing before the transaction\n * would hand a flood a CPU amplifier on exactly the path the ceiling\n * exists to contain, and would also be a regression, since today a\n * duplicate-email refusal does not hash either. It is a pure computation,\n * not an effect, so it does not violate the \"nothing happens in a\n * transaction body\" rule the sibling routes state.\n *\n * A refusal is returned as DATA and rendered outside: a body that can run\n * several times must not be the place a response is built.\n */\n const refusal = await firestore.runTransaction(async (tx) => {\n const existing = await tx.get(membersRef.where('email', '==', email).limit(1))\n if (!existing.empty) return { duplicate: true, ceiling: 0 }\n const used = (await tx.get(membersRef.count())).data().count\n // Live documents only, so removing a member in the inbox frees the slot.\n const verdict = checkVisitorRecordCeiling(used, SITE_MEMBERS_MAX_PER_HOST)\n if (verdict.exceeded) return { duplicate: false, ceiling: verdict.ceiling }\n // The hash goes to the credential document, which no client can read\n // (AGL-3308), and in this transaction, so a member never exists without\n // the password they chose. The profile below is what the console lists.\n tx.set(memberCredentialRef(hostRef, memberRef.id), {\n passwordScrypt: hashMemberPassword(password),\n })\n tx.create(memberRef, {\n email,\n ...(displayName ? memberNameSearchFields(displayName) : {}),\n /*\n * The checkbox is PERSISTED on the member, not only forwarded.\n *\n * It reached the lead and the contact from the two lines below and\n * was dropped for this document, so `hosts/{hostId}/siteMembers` had\n * no consent field of any kind and `audience: 'members'` had nothing\n * for the send-time join to read — the audience could not be filtered\n * even in principle (`docs/specs/email-overhaul.md` §1d/§3f). The\n * other two documents are not a substitute: a member is deduped in\n * this transaction while leads append every time, and contacts are\n * ORG-scoped where a member is the site's own.\n *\n * Written only when ticked. Signing up is not opting in — that is why\n * the checkbox exists and why it defaults unchecked — so the omitted\n * case stores nothing and reads back as an unrecorded basis rather\n * than as a refusal.\n *\n * Under this site's key even though `siteMembers` already lives\n * beneath it, so that one reader answers for every silo — see\n * `addHostLead`, which makes the same write for the same reason.\n */\n ...(marketingConsent\n ? marketingConsentFieldsForHost(hostId, Date.now())\n : {}),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n return null\n })\n if (refusal?.duplicate) {\n return res.status(409).json({ error: 'That email is already a member' })\n }\n if (refusal) {\n // Visible to the HOST — the rule that a control nobody can see in\n // the console did not ship. Durable counter + one notification.\n await recordVisitorRecordCeilingTrip({\n hostRef,\n hostId,\n kind: 'siteMembers',\n ceiling: refusal.ceiling,\n })\n // Opaque to the VISITOR, who is a stranger to this site and not our\n // customer (AGL-1666's rules, restated in the message's own docblock).\n // The one genuinely useful thing to hand them is a door that still\n // opens, so the site's OWN published support address rides along when\n // it has one — read through the host-token registry, whose description\n // of this field is literally \"where visitors should write for help\".\n // Nothing else off the host document may leave the console.\n const contact = HOST_TOKENS['supportEmail']?.resolve(\n hostSnapshot.data() as any,\n )\n return res.status(429).json({\n error: SITE_MEMBER_UNAVAILABLE_MESSAGE,\n // Machine-readable, because the dispatcher's rate limiter answers 429\n // too and the status therefore discriminates nothing.\n code: SITE_MEMBER_CEILING_CODE,\n ...(contact ? { contact } : {}),\n })\n }\n // Sign-ups double as leads for the site owner (AGL-109), through the one\n // writer that enforces `LEADS_MAX_PER_HOST` (AGL-1529). A refused lead\n // never fails the sign-up: the visitor asked for an account, not for a\n // lead record, and the trip is recorded for the owner either way.\n /*\n * THE CAMPAIGN TOUCH, RESOLVED ONCE FOR THE WHOLE SIGN-UP.\n *\n * A sign-up is the identify moment for a visitor who has been anonymous\n * until now, and it writes two records that a campaign can be credited\n * with — the lead and the contact. One resolve, one keyed read, and the\n * two cannot end up naming different campaigns.\n *\n * The MEMBER record itself is not attributed. A member is an account the\n * visitor holds and the lead is the site's record of the same act, so\n * crediting both would count one sign-up twice under two names.\n */\n const signedUpAtMs = Date.now()\n const campaignTouch = await resolveCampaignTouch({\n hostId,\n wire: req.body?.campaignTouch,\n email,\n atMs: signedUpAtMs,\n })\n /*\n * Contacts ingestion (AGL-197), reported to whichever plugin keeps people\n * rather than written by this one (AGL-3080). Commerce knows it just met\n * somebody; what a person record is belongs to the plugin that models it,\n * and a workspace that keeps none is a quiet, correct answer here.\n */\n /*\n * A member account is a RELATIONSHIP (AGL-3232): the person is a\n * contact from this moment, and an open lead the site held for the\n * address is closed as converted onto that contact by the record\n * system — a sign-up files no lead of its own any more, the way a\n * portal user is a contact and not a lead in Salesforce.\n */\n void recordCapturedContact({\n /*\n * Not resolved here. The record system keys a person on the SITE they\n * were met on, so this costs the capture nothing — and resolving it\n * would put a Firestore read in front of the writer, which is the one\n * thing `recordCapturedContact` asks a door not to do.\n */\n orgId: '',\n hostId,\n identity: { email, name: displayName || undefined },\n interaction: {\n source: 'member',\n refId: memberRef.id,\n summary: 'Joined as a member',\n },\n surface: 'relationship',\n // An account is a subscription to the site, not an enquiry (AGL-2612):\n // the stage on the contact says only that the person asked to be\n // kept. A floor, so a customer who opens an account stays a customer.\n lifecycleFloor: 'subscriber',\n ...(marketingConsent ? { marketingConsent: true } : {}),\n // Where the visitor ARRIVED from — a fact about this visit and not\n // about the person, which is what `detail` carries.\n ...(campaignTouch ? { detail: { campaignTouch } } : {}),\n })\n // Event trigger (AGL-128/148). A sign-up is no longer a lead (AGL-3232),\n // so the `lead` event is the lead surfaces' to emit.\n await emitHostEvent(hostId, 'memberSignUp', { email })\n setMemberCookie(res, hostId, mintMemberSession(hostId, memberRef.id))\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Sign-up failed' })\n }\n}\n"],"names":["memberNameSearchFields","checkVisitorRecordCeiling","HOST_TOKENS","marketingConsentFieldsForHost","SITE_MEMBER_CEILING_CODE","SITE_MEMBER_UNAVAILABLE_MESSAGE","SITE_MEMBERS_MAX_PER_HOST","firebaseAdmin","recordVisitorRecordCeilingTrip","resolveCampaignTouch","emitHostEvent","recordCapturedContact","hashMemberPassword","mintMemberSession","setMemberCookie","memberCredentialRef","EMAIL_PATTERN","membershipRegisterHandler","req","res","method","status","json","error","hostId","String","body","email","trim","toLowerCase","password","displayName","slice","marketingConsent","test","length","firestore","app","hostRef","collection","doc","hostSnapshot","get","exists","membersRef","memberRef","refusal","runTransaction","tx","existing","where","limit","empty","duplicate","ceiling","used","count","data","verdict","exceeded","set","id","passwordScrypt","create","Date","now","createdAt","FieldValue","serverTimestamp","kind","contact","resolve","code","signedUpAtMs","campaignTouch","wire","atMs","orgId","identity","name","undefined","interaction","source","refId","summary","surface","lifecycleFloor","detail","ok","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,sBAAsB,QAAQ,0BAAsB;AAC7D,SACEC,yBAAyB,EACzBC,WAAW,EACXC,6BAA6B,EAC7BC,wBAAwB,EACxBC,+BAA+B,EAC/BC,yBAAyB,QACpB,sBAAqB;AAC5B,SACEC,aAAa,EACbC,8BAA8B,EAC9BC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,aAAa,QAAQ,wBAAuB;AACrD,OAAOC,2BAA2B,sDAAqD;AACvF,SACEC,kBAAkB,EAClBC,iBAAiB,EACjBC,eAAe,QACV,kBAAc;AACrB,SAASC,mBAAmB,QAAQ,0BAAsB;AAE1D,MAAMC,gBAAgB;AAEtB;;;;CAIC,GACD,OAAO,MAAMC,4BAA8C,OAAOC,KAAKC;;QAI/CD,WACDA,YAGGA,YACGA,YAIFA;IAZzB,IAAIA,I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AAQ,gBAAgB;YAAEG;QAAM;QACpDb,gBAAgBK,KAAKK,QAAQX,kBAAkBW,QAAQqB,UAAUgB,EAAE;QACnE,OAAO1C,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEkE,IAAI;QAAK;IACzC,EAAE,OAAOjE,OAAO;QACdkE,QAAQlE,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC"}
|
|
@@ -19,8 +19,14 @@ import type { PluginApiHandler } from '@aglyn/aglyn/server';
|
|
|
19
19
|
* Password reset completion (AGL-552): verifies the recover token
|
|
20
20
|
* (signature + expiry + binding to the member's CURRENT password hash —
|
|
21
21
|
* so a completed reset invalidates every outstanding token) and writes the
|
|
22
|
-
* new scrypt hash
|
|
23
|
-
* the
|
|
24
|
-
* non-issue (256-bit HMAC), so no extra
|
|
22
|
+
* new scrypt hash to the member's credential document (AGL-3308). No session
|
|
23
|
+
* is minted here; the client signs in through the normal login route with the
|
|
24
|
+
* new password. Token guessing is a non-issue (256-bit HMAC), so no extra
|
|
25
|
+
* damper beyond login's.
|
|
26
|
+
*
|
|
27
|
+
* ONE TRANSACTION, from the token check to the write. The hash the token is
|
|
28
|
+
* checked against is the hash the write replaces, so two submissions of one
|
|
29
|
+
* link cannot both land — the second re-reads the new hash and fails the
|
|
30
|
+
* binding — and a member removed mid-request is not recreated as a stub.
|
|
25
31
|
*/
|
|
26
32
|
export declare const membershipResetHandler: PluginApiHandler;
|
|
@@ -15,13 +15,20 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
17
17
|
import { MEMBER_SUSPENDED_ERROR, hashMemberPassword, passwordResetTokenMemberId, verifyPasswordResetToken } from "./membership.js";
|
|
18
|
+
import { isMemberDocumentId, memberCredentialRef, retiredCredentialFields, storedPasswordHash } from "./member-credentials.js";
|
|
18
19
|
/**
|
|
19
20
|
* Password reset completion (AGL-552): verifies the recover token
|
|
20
21
|
* (signature + expiry + binding to the member's CURRENT password hash —
|
|
21
22
|
* so a completed reset invalidates every outstanding token) and writes the
|
|
22
|
-
* new scrypt hash
|
|
23
|
-
* the
|
|
24
|
-
* non-issue (256-bit HMAC), so no extra
|
|
23
|
+
* new scrypt hash to the member's credential document (AGL-3308). No session
|
|
24
|
+
* is minted here; the client signs in through the normal login route with the
|
|
25
|
+
* new password. Token guessing is a non-issue (256-bit HMAC), so no extra
|
|
26
|
+
* damper beyond login's.
|
|
27
|
+
*
|
|
28
|
+
* ONE TRANSACTION, from the token check to the write. The hash the token is
|
|
29
|
+
* checked against is the hash the write replaces, so two submissions of one
|
|
30
|
+
* link cannot both land — the second re-reads the new hash and fails the
|
|
31
|
+
* binding — and a member removed mid-request is not recreated as a stub.
|
|
25
32
|
*/ export const membershipResetHandler = async (req, res)=>{
|
|
26
33
|
var _ref, _ref1, _ref2;
|
|
27
34
|
var _req_body, _req_body1, _req_body2;
|
|
@@ -49,31 +56,43 @@ import { MEMBER_SUSPENDED_ERROR, hashMemberPassword, passwordResetTokenMemberId,
|
|
|
49
56
|
// Structural pre-check only (host + expiry); the signature binds to the
|
|
50
57
|
// member's current hash, which we have to load first.
|
|
51
58
|
const memberId = passwordResetTokenMemberId(hostId, token);
|
|
52
|
-
if (!memberId) return invalid();
|
|
59
|
+
if (!memberId || !isMemberDocumentId(memberId)) return invalid();
|
|
53
60
|
try {
|
|
54
61
|
const firestore = firebaseAdmin.app().firestore();
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
63
|
+
const memberRef = hostRef.collection('siteMembers').doc(memberId);
|
|
64
|
+
const credentialRef = memberCredentialRef(hostRef, memberId);
|
|
65
|
+
// Hashed once, however often the body retries, and only for a link that
|
|
66
|
+
// verified: ~100 ms of CPU is not spent on a stale or forged token.
|
|
67
|
+
let newHash;
|
|
68
|
+
const outcome = await firestore.runTransaction(async (tx)=>{
|
|
69
|
+
const [memberDoc, credentialDoc] = await tx.getAll(memberRef, credentialRef);
|
|
70
|
+
if (!memberDoc.exists) return 'invalid';
|
|
71
|
+
if (!verifyPasswordResetToken(hostId, token, storedPasswordHash(credentialDoc, memberDoc))) {
|
|
72
|
+
return 'invalid';
|
|
73
|
+
}
|
|
74
|
+
// Suspension gate (AGL-546/550): a token minted before the
|
|
75
|
+
// suspension stays cryptographically valid for its hour, so reject
|
|
76
|
+
// here — recovery must not rehabilitate a suspended account. Checked
|
|
77
|
+
// AFTER the signature so only the mailed-link holder (who already
|
|
78
|
+
// knows the account exists) can observe the suspension.
|
|
79
|
+
if (memberDoc.get('suspended') === true) return 'suspended';
|
|
80
|
+
newHash != null ? newHash : newHash = hashMemberPassword(password);
|
|
81
|
+
tx.set(credentialRef, {
|
|
82
|
+
passwordScrypt: newHash,
|
|
83
|
+
passwordResetAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
|
|
84
|
+
}, {
|
|
85
|
+
merge: true
|
|
86
|
+
});
|
|
87
|
+
tx.update(memberRef, retiredCredentialFields());
|
|
88
|
+
return 'reset';
|
|
89
|
+
});
|
|
90
|
+
if (outcome === 'invalid') return invalid();
|
|
91
|
+
if (outcome === 'suspended') {
|
|
67
92
|
return res.status(403).json({
|
|
68
93
|
error: MEMBER_SUSPENDED_ERROR
|
|
69
94
|
});
|
|
70
95
|
}
|
|
71
|
-
await memberRef.set({
|
|
72
|
-
passwordScrypt: hashMemberPassword(password),
|
|
73
|
-
passwordResetAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
|
|
74
|
-
}, {
|
|
75
|
-
merge: true
|
|
76
|
-
});
|
|
77
96
|
return res.status(200).json({
|
|
78
97
|
ok: true
|
|
79
98
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-reset.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n MEMBER_SUSPENDED_ERROR,\n hashMemberPassword,\n passwordResetTokenMemberId,\n verifyPasswordResetToken,\n} from './membership'\n\n/**\n * Password reset completion (AGL-552): verifies the recover token\n * (signature + expiry + binding to the member's CURRENT password hash —\n * so a completed reset invalidates every outstanding token) and writes the\n * new scrypt hash. No session is minted here; the client signs in through
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/membership-reset.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n MEMBER_SUSPENDED_ERROR,\n hashMemberPassword,\n passwordResetTokenMemberId,\n verifyPasswordResetToken,\n} from './membership'\nimport {\n isMemberDocumentId,\n memberCredentialRef,\n retiredCredentialFields,\n storedPasswordHash,\n} from './member-credentials'\n\n/**\n * Password reset completion (AGL-552): verifies the recover token\n * (signature + expiry + binding to the member's CURRENT password hash —\n * so a completed reset invalidates every outstanding token) and writes the\n * new scrypt hash to the member's credential document (AGL-3308). No session\n * is minted here; the client signs in through the normal login route with the\n * new password. Token guessing is a non-issue (256-bit HMAC), so no extra\n * damper beyond login's.\n *\n * ONE TRANSACTION, from the token check to the write. The hash the token is\n * checked against is the hash the write replaces, so two submissions of one\n * link cannot both land — the second re-reads the new hash and fails the\n * binding — and a member removed mid-request is not recreated as a stub.\n */\nexport const membershipResetHandler: 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 token = String(req.body?.token ?? '')\n const password = String(req.body?.password ?? '')\n if (!hostId || !token) {\n return res.status(400).json({ error: 'Invalid request' })\n }\n if (password.length < 8) {\n return res\n .status(400)\n .json({ error: 'Password must be at least 8 characters' })\n }\n const invalid = () =>\n res.status(400).json({\n error: 'That reset link is invalid or has expired — request a new one.',\n })\n // Structural pre-check only (host + expiry); the signature binds to the\n // member's current hash, which we have to load first.\n const memberId = passwordResetTokenMemberId(hostId, token)\n if (!memberId || !isMemberDocumentId(memberId)) return invalid()\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const memberRef = hostRef.collection('siteMembers').doc(memberId)\n const credentialRef = memberCredentialRef(hostRef, memberId)\n // Hashed once, however often the body retries, and only for a link that\n // verified: ~100 ms of CPU is not spent on a stale or forged token.\n let newHash: string | undefined\n const outcome = await firestore.runTransaction(async (tx) => {\n const [memberDoc, credentialDoc] = await tx.getAll(memberRef, credentialRef)\n if (!memberDoc.exists) return 'invalid'\n if (\n !verifyPasswordResetToken(\n hostId,\n token,\n storedPasswordHash(credentialDoc, memberDoc),\n )\n ) {\n return 'invalid'\n }\n // Suspension gate (AGL-546/550): a token minted before the\n // suspension stays cryptographically valid for its hour, so reject\n // here — recovery must not rehabilitate a suspended account. Checked\n // AFTER the signature so only the mailed-link holder (who already\n // knows the account exists) can observe the suspension.\n if (memberDoc.get('suspended') === true) return 'suspended'\n newHash ??= hashMemberPassword(password)\n tx.set(\n credentialRef,\n {\n passwordScrypt: newHash,\n passwordResetAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n tx.update(memberRef, retiredCredentialFields())\n return 'reset'\n })\n if (outcome === 'invalid') return invalid()\n if (outcome === 'suspended') {\n return res.status(403).json({ error: MEMBER_SUSPENDED_ERROR })\n }\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Reset failed' })\n }\n}\n"],"names":["firebaseAdmin","MEMBER_SUSPENDED_ERROR","hashMemberPassword","passwordResetTokenMemberId","verifyPasswordResetToken","isMemberDocumentId","memberCredentialRef","retiredCredentialFields","storedPasswordHash","membershipResetHandler","req","res","method","status","json","error","hostId","String","body","token","password","length","invalid","memberId","firestore","app","hostRef","collection","doc","memberRef","credentialRef","newHash","outcome","runTransaction","tx","memberDoc","credentialDoc","getAll","exists","get","set","passwordScrypt","passwordResetAt","FieldValue","serverTimestamp","merge","update","ok","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,0BAA0B,EAC1BC,wBAAwB,QACnB,kBAAc;AACrB,SACEC,kBAAkB,EAClBC,mBAAmB,EACnBC,uBAAuB,EACvBC,kBAAkB,QACb,0BAAsB;AAE7B;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,yBAA2C,OAAOC,KAAKC;;QAI5CD,WACDA,YACGA;IALxB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,S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