@open-mercato/checkout 0.10.1-develop.7797.1.f0365b4031 → 0.10.1-develop.7799.1.d9cd0c8e41
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/.turbo/turbo-build.log +1 -1
- package/dist/modules/checkout/__integration__/TC-CHKT-045-preview-scope.spec.js +132 -0
- package/dist/modules/checkout/__integration__/TC-CHKT-045-preview-scope.spec.js.map +7 -0
- package/dist/modules/checkout/api/pay/[slug]/route.js +9 -4
- package/dist/modules/checkout/api/pay/[slug]/route.js.map +2 -2
- package/package.json +5 -5
- package/src/modules/checkout/__integration__/TC-CHKT-045-preview-scope.spec.ts +138 -0
- package/src/modules/checkout/api/pay/[slug]/__tests__/preview-scope.test.ts +158 -0
- package/src/modules/checkout/api/pay/[slug]/__tests__/route.test.ts +4 -1
- package/src/modules/checkout/api/pay/[slug]/route.ts +8 -3
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:checkout] found
|
|
1
|
+
[build:checkout] found 168 entry points
|
|
2
2
|
[build:checkout] built successfully
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { expect, test } from "@playwright/test";
|
|
3
|
+
import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
|
|
4
|
+
import {
|
|
5
|
+
createOrganizationFixture,
|
|
6
|
+
createRoleFixture,
|
|
7
|
+
createUserFixture,
|
|
8
|
+
deleteOrganizationIfExists,
|
|
9
|
+
deleteRoleIfExists,
|
|
10
|
+
deleteUserIfExists,
|
|
11
|
+
setRoleAclFeatures
|
|
12
|
+
} from "@open-mercato/core/helpers/integration/authFixtures";
|
|
13
|
+
import { deleteGeneralEntityIfExists, expectId, readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
|
|
14
|
+
import { createFixedTemplateInput, readPublicPayLink } from "./helpers/fixtures.js";
|
|
15
|
+
function scopeHeaders(scope) {
|
|
16
|
+
return { Cookie: `om_selected_tenant=${scope.tenantId}; om_selected_org=${scope.organizationId}` };
|
|
17
|
+
}
|
|
18
|
+
test.describe("TC-CHKT-045: Checkout preview tenant and organization isolation", () => {
|
|
19
|
+
const label = `checkout-preview-${randomUUID()}`;
|
|
20
|
+
const password = `Qa-${randomUUID()}-Aa1!`;
|
|
21
|
+
const email = `${label}@example.com`;
|
|
22
|
+
const tenantIds = [];
|
|
23
|
+
const organizationIds = [];
|
|
24
|
+
const links = [];
|
|
25
|
+
let superadminToken = null;
|
|
26
|
+
let roleId = null;
|
|
27
|
+
let userId = null;
|
|
28
|
+
let ownScope;
|
|
29
|
+
let viewerToken;
|
|
30
|
+
test.beforeAll(async ({ request }) => {
|
|
31
|
+
superadminToken = await getAuthToken(request, "superadmin");
|
|
32
|
+
for (const suffix of ["a", "b"]) {
|
|
33
|
+
const response = await apiRequest(request, "POST", "/api/directory/tenants", {
|
|
34
|
+
token: superadminToken,
|
|
35
|
+
data: { name: `${label}-${suffix}` }
|
|
36
|
+
});
|
|
37
|
+
const body = await readJsonSafe(response);
|
|
38
|
+
expect(response.status()).toBe(201);
|
|
39
|
+
tenantIds.push(expectId(body?.id, "Tenant fixture must have an id"));
|
|
40
|
+
}
|
|
41
|
+
for (const tenantId of [tenantIds[0], tenantIds[0], tenantIds[1]]) {
|
|
42
|
+
organizationIds.push(await createOrganizationFixture(request, superadminToken, {
|
|
43
|
+
name: `${label}-org-${organizationIds.length}`,
|
|
44
|
+
tenantId
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
ownScope = { tenantId: tenantIds[0], organizationId: organizationIds[0] };
|
|
48
|
+
const scopes = [
|
|
49
|
+
ownScope,
|
|
50
|
+
{ tenantId: tenantIds[0], organizationId: organizationIds[1] },
|
|
51
|
+
{ tenantId: tenantIds[1], organizationId: organizationIds[2] }
|
|
52
|
+
];
|
|
53
|
+
roleId = await createRoleFixture(request, superadminToken, { name: label, tenantId: ownScope.tenantId });
|
|
54
|
+
await setRoleAclFeatures(request, superadminToken, {
|
|
55
|
+
roleId,
|
|
56
|
+
features: ["checkout.view"],
|
|
57
|
+
organizations: [ownScope.organizationId]
|
|
58
|
+
});
|
|
59
|
+
userId = await createUserFixture(request, superadminToken, {
|
|
60
|
+
email,
|
|
61
|
+
password,
|
|
62
|
+
organizationId: ownScope.organizationId,
|
|
63
|
+
roles: [roleId]
|
|
64
|
+
});
|
|
65
|
+
viewerToken = await getAuthToken(request, email, password);
|
|
66
|
+
for (const scope of scopes) {
|
|
67
|
+
for (const status of ["draft", "inactive", "active"]) {
|
|
68
|
+
const title = `${label}-${links.length}`;
|
|
69
|
+
const response = await apiRequest(request, "POST", "/api/checkout/links", {
|
|
70
|
+
token: superadminToken,
|
|
71
|
+
headers: scopeHeaders(scope),
|
|
72
|
+
data: createFixedTemplateInput({ status, title, password, collectCustomerDetails: false })
|
|
73
|
+
});
|
|
74
|
+
const body = await readJsonSafe(response);
|
|
75
|
+
expect(response.status()).toBe(201);
|
|
76
|
+
links.push({
|
|
77
|
+
...scope,
|
|
78
|
+
id: expectId(body?.id, "Link fixture must have an id"),
|
|
79
|
+
slug: expectId(body?.slug, "Link fixture must have a slug"),
|
|
80
|
+
title,
|
|
81
|
+
status
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
test("limits a checkout.view user to same-scope previews and preserves public gates", async ({ request }) => {
|
|
87
|
+
for (const link of links) {
|
|
88
|
+
const preview = await apiRequest(request, "GET", `/api/checkout/pay/${encodeURIComponent(link.slug)}?preview=true`, {
|
|
89
|
+
token: viewerToken
|
|
90
|
+
});
|
|
91
|
+
if (link.tenantId === ownScope.tenantId && link.organizationId === ownScope.organizationId) {
|
|
92
|
+
expect(preview.status(), `Same-scope ${link.status} preview`).toBe(200);
|
|
93
|
+
expect(await readJsonSafe(preview)).toMatchObject({
|
|
94
|
+
id: link.id,
|
|
95
|
+
title: link.title,
|
|
96
|
+
preview: true,
|
|
97
|
+
available: false,
|
|
98
|
+
requiresPassword: false
|
|
99
|
+
});
|
|
100
|
+
} else {
|
|
101
|
+
expect(preview.status(), `Foreign-scope ${link.status} preview`).toBe(404);
|
|
102
|
+
expect(await readJsonSafe(preview)).toEqual({ error: "Payment link not found" });
|
|
103
|
+
}
|
|
104
|
+
const publicResponse = await readPublicPayLink(request, link.slug);
|
|
105
|
+
if (link.status === "active") {
|
|
106
|
+
expect(publicResponse.status()).toBe(200);
|
|
107
|
+
expect(await readJsonSafe(publicResponse)).toEqual({ requiresPassword: true, title: link.title });
|
|
108
|
+
} else {
|
|
109
|
+
expect(publicResponse.status()).toBe(404);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
test.afterAll(async ({ request }) => {
|
|
114
|
+
if (superadminToken) {
|
|
115
|
+
for (const link of links.reverse()) {
|
|
116
|
+
await apiRequest(request, "DELETE", `/api/checkout/links/${encodeURIComponent(link.id)}`, {
|
|
117
|
+
token: superadminToken,
|
|
118
|
+
headers: scopeHeaders(link)
|
|
119
|
+
}).catch(() => void 0);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
await deleteUserIfExists(request, superadminToken, userId);
|
|
123
|
+
await deleteRoleIfExists(request, superadminToken, roleId);
|
|
124
|
+
for (const organizationId of organizationIds.reverse()) {
|
|
125
|
+
await deleteOrganizationIfExists(request, superadminToken, organizationId);
|
|
126
|
+
}
|
|
127
|
+
for (const tenantId of tenantIds.reverse()) {
|
|
128
|
+
await deleteGeneralEntityIfExists(request, superadminToken, "/api/directory/tenants", tenantId);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
//# sourceMappingURL=TC-CHKT-045-preview-scope.spec.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/checkout/__integration__/TC-CHKT-045-preview-scope.spec.ts"],
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport {\n createOrganizationFixture,\n createRoleFixture,\n createUserFixture,\n deleteOrganizationIfExists,\n deleteRoleIfExists,\n deleteUserIfExists,\n setRoleAclFeatures,\n} from '@open-mercato/core/helpers/integration/authFixtures'\nimport { deleteGeneralEntityIfExists, expectId, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport { createFixedTemplateInput, readPublicPayLink } from './helpers/fixtures'\n\ntype Scope = { tenantId: string; organizationId: string }\ntype LinkFixture = Scope & { id: string; slug: string; title: string; status: 'draft' | 'inactive' | 'active' }\n\nfunction scopeHeaders(scope: Scope) {\n return { Cookie: `om_selected_tenant=${scope.tenantId}; om_selected_org=${scope.organizationId}` }\n}\n\ntest.describe('TC-CHKT-045: Checkout preview tenant and organization isolation', () => {\n const label = `checkout-preview-${randomUUID()}`\n const password = `Qa-${randomUUID()}-Aa1!`\n const email = `${label}@example.com`\n const tenantIds: string[] = []\n const organizationIds: string[] = []\n const links: LinkFixture[] = []\n let superadminToken: string | null = null\n let roleId: string | null = null\n let userId: string | null = null\n let ownScope: Scope\n let viewerToken: string\n\n test.beforeAll(async ({ request }) => {\n superadminToken = await getAuthToken(request, 'superadmin')\n for (const suffix of ['a', 'b']) {\n const response = await apiRequest(request, 'POST', '/api/directory/tenants', {\n token: superadminToken,\n data: { name: `${label}-${suffix}` },\n })\n const body = await readJsonSafe<{ id?: string }>(response)\n expect(response.status()).toBe(201)\n tenantIds.push(expectId(body?.id, 'Tenant fixture must have an id'))\n }\n for (const tenantId of [tenantIds[0], tenantIds[0], tenantIds[1]]) {\n organizationIds.push(await createOrganizationFixture(request, superadminToken, {\n name: `${label}-org-${organizationIds.length}`,\n tenantId,\n }))\n }\n ownScope = { tenantId: tenantIds[0], organizationId: organizationIds[0] }\n const scopes: Scope[] = [\n ownScope,\n { tenantId: tenantIds[0], organizationId: organizationIds[1] },\n { tenantId: tenantIds[1], organizationId: organizationIds[2] },\n ]\n roleId = await createRoleFixture(request, superadminToken, { name: label, tenantId: ownScope.tenantId })\n await setRoleAclFeatures(request, superadminToken, {\n roleId,\n features: ['checkout.view'],\n organizations: [ownScope.organizationId],\n })\n userId = await createUserFixture(request, superadminToken, {\n email,\n password,\n organizationId: ownScope.organizationId,\n roles: [roleId],\n })\n viewerToken = await getAuthToken(request, email, password)\n\n for (const scope of scopes) {\n for (const status of ['draft', 'inactive', 'active'] as const) {\n const title = `${label}-${links.length}`\n const response = await apiRequest(request, 'POST', '/api/checkout/links', {\n token: superadminToken,\n headers: scopeHeaders(scope),\n data: createFixedTemplateInput({ status, title, password, collectCustomerDetails: false }),\n })\n const body = await readJsonSafe<{ id?: string; slug?: string }>(response)\n expect(response.status()).toBe(201)\n links.push({\n ...scope,\n id: expectId(body?.id, 'Link fixture must have an id'),\n slug: expectId(body?.slug, 'Link fixture must have a slug'),\n title,\n status,\n })\n }\n }\n\n })\n\n test('limits a checkout.view user to same-scope previews and preserves public gates', async ({ request }) => {\n for (const link of links) {\n const preview = await apiRequest(request, 'GET', `/api/checkout/pay/${encodeURIComponent(link.slug)}?preview=true`, {\n token: viewerToken,\n })\n if (link.tenantId === ownScope.tenantId && link.organizationId === ownScope.organizationId) {\n expect(preview.status(), `Same-scope ${link.status} preview`).toBe(200)\n expect(await readJsonSafe(preview)).toMatchObject({\n id: link.id, title: link.title, preview: true, available: false, requiresPassword: false,\n })\n } else {\n expect(preview.status(), `Foreign-scope ${link.status} preview`).toBe(404)\n expect(await readJsonSafe(preview)).toEqual({ error: 'Payment link not found' })\n }\n\n const publicResponse = await readPublicPayLink(request, link.slug)\n if (link.status === 'active') {\n expect(publicResponse.status()).toBe(200)\n expect(await readJsonSafe(publicResponse)).toEqual({ requiresPassword: true, title: link.title })\n } else {\n expect(publicResponse.status()).toBe(404)\n }\n }\n })\n\n test.afterAll(async ({ request }) => {\n if (superadminToken) {\n for (const link of links.reverse()) {\n await apiRequest(request, 'DELETE', `/api/checkout/links/${encodeURIComponent(link.id)}`, {\n token: superadminToken,\n headers: scopeHeaders(link),\n }).catch(() => undefined)\n }\n }\n await deleteUserIfExists(request, superadminToken, userId)\n await deleteRoleIfExists(request, superadminToken, roleId)\n for (const organizationId of organizationIds.reverse()) {\n await deleteOrganizationIfExists(request, superadminToken, organizationId)\n }\n for (const tenantId of tenantIds.reverse()) {\n await deleteGeneralEntityIfExists(request, superadminToken, '/api/directory/tenants', tenantId)\n }\n })\n})\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B,UAAU,oBAAoB;AACpE,SAAS,0BAA0B,yBAAyB;AAK5D,SAAS,aAAa,OAAc;AAClC,SAAO,EAAE,QAAQ,sBAAsB,MAAM,QAAQ,qBAAqB,MAAM,cAAc,GAAG;AACnG;AAEA,KAAK,SAAS,mEAAmE,MAAM;AACrF,QAAM,QAAQ,oBAAoB,WAAW,CAAC;AAC9C,QAAM,WAAW,MAAM,WAAW,CAAC;AACnC,QAAM,QAAQ,GAAG,KAAK;AACtB,QAAM,YAAsB,CAAC;AAC7B,QAAM,kBAA4B,CAAC;AACnC,QAAM,QAAuB,CAAC;AAC9B,MAAI,kBAAiC;AACrC,MAAI,SAAwB;AAC5B,MAAI,SAAwB;AAC5B,MAAI;AACJ,MAAI;AAEJ,OAAK,UAAU,OAAO,EAAE,QAAQ,MAAM;AACpC,sBAAkB,MAAM,aAAa,SAAS,YAAY;AAC1D,eAAW,UAAU,CAAC,KAAK,GAAG,GAAG;AAC/B,YAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,0BAA0B;AAAA,QAC3E,OAAO;AAAA,QACP,MAAM,EAAE,MAAM,GAAG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,OAAO,CAAC,EAAE,KAAK,GAAG;AACxC,eAAO,MAAM,aAAa,cAAc,CAAC,EAAE,QAAQ,EAAE,kBAAkB,MAAM,OAAO,KAAK,MAAM,CAAC;AAAA,MAClG,OAAO;AACL,eAAO,eAAe,OAAO,CAAC,EAAE,KAAK,GAAG;AAAA,MAC1C;AAAA,IACF;AAAA,EACF,CAAC;AAED,OAAK,SAAS,OAAO,EAAE,QAAQ,MAAM;AACnC,QAAI,iBAAiB;AACnB,iBAAW,QAAQ,MAAM,QAAQ,GAAG;AAClC,cAAM,WAAW,SAAS,UAAU,uBAAuB,mBAAmB,KAAK,EAAE,CAAC,IAAI;AAAA,UACxF,OAAO;AAAA,UACP,SAAS,aAAa,IAAI;AAAA,QAC5B,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAC1B;AAAA,IACF;AACA,UAAM,mBAAmB,SAAS,iBAAiB,MAAM;AACzD,UAAM,mBAAmB,SAAS,iBAAiB,MAAM;AACzD,eAAW,kBAAkB,gBAAgB,QAAQ,GAAG;AACtD,YAAM,2BAA2B,SAAS,iBAAiB,cAAc;AAAA,IAC3E;AACA,eAAW,YAAY,UAAU,QAAQ,GAAG;AAC1C,YAAM,4BAA4B,SAAS,iBAAiB,0BAA0B,QAAQ;AAAA,IAChG;AAAA,EACF,CAAC;AACH,CAAC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -23,8 +23,8 @@ async function GET(req, { params }) {
|
|
|
23
23
|
const resolvedParams = await params;
|
|
24
24
|
const url = new URL(req.url);
|
|
25
25
|
const previewRequested = url.searchParams.get("preview") === "true";
|
|
26
|
-
const
|
|
27
|
-
|
|
26
|
+
const previewContext = previewRequested ? await requirePreviewContext(req) : null;
|
|
27
|
+
const container = previewContext?.container ?? await createRequestContainer();
|
|
28
28
|
if (!previewRequested) {
|
|
29
29
|
const rateLimitResponse = await enforceCheckoutRateLimit({
|
|
30
30
|
req,
|
|
@@ -37,10 +37,15 @@ async function GET(req, { params }) {
|
|
|
37
37
|
if (rateLimitResponse) return rateLimitResponse;
|
|
38
38
|
}
|
|
39
39
|
const em = container.resolve("em");
|
|
40
|
+
const previewScope = previewContext ? {
|
|
41
|
+
tenantId: previewContext.auth.tenantId,
|
|
42
|
+
organizationId: previewContext.auth.orgId
|
|
43
|
+
} : void 0;
|
|
40
44
|
const link = await findOneWithDecryption(em, CheckoutLink, {
|
|
41
45
|
slug: resolvedParams.slug,
|
|
42
|
-
deletedAt: null
|
|
43
|
-
|
|
46
|
+
deletedAt: null,
|
|
47
|
+
...previewScope
|
|
48
|
+
}, void 0, previewScope);
|
|
44
49
|
if (!link || !previewRequested && !isCheckoutLinkPublic(link.status)) {
|
|
45
50
|
return NextResponse.json({ error: "Payment link not found" }, { status: 404 });
|
|
46
51
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/checkout/api/pay/%5Bslug%5D/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { loadCustomFieldValues } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CheckoutLink } from '../../../data/entities'\nimport { CHECKOUT_ENTITY_IDS } from '../../../lib/constants'\nimport { resolveCheckoutPublicCustomFields } from '../../../lib/customFields'\nimport { checkoutPublicViewRateLimitConfig, enforceCheckoutRateLimit } from '../../../lib/rateLimiter'\nimport { handleCheckoutRouteError, readCheckoutAccessCookie, requirePreviewContext } from '../../helpers'\nimport {\n isCheckoutLinkPublic,\n resolveLoadedCheckoutCustomFields,\n serializePublicPayLink,\n verifyCheckoutAccessToken,\n} from '../../../lib/utils'\nimport { checkoutTag } from '../../openapi'\n\nexport const metadata = {\n path: '/checkout/pay/[slug]',\n GET: { requireAuth: false },\n}\n\nexport async function GET(req: Request, { params }: { params: Promise<{ slug: string }> | { slug: string } }) {\n try {\n const resolvedParams = await params\n const url = new URL(req.url)\n const previewRequested = url.searchParams.get('preview') === 'true'\n const
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,yCAAyC;AAClD,SAAS,mCAAmC,gCAAgC;AAC5E,SAAS,0BAA0B,0BAA0B,6BAA6B;AAC1F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAErB,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,KAAK,EAAE,aAAa,MAAM;AAC5B;AAEA,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA6D;AAC5G,MAAI;AACF,UAAM,iBAAiB,MAAM;AAC7B,UAAM,MAAM,IAAI,IAAI,IAAI,GAAG;AAC3B,UAAM,mBAAmB,IAAI,aAAa,IAAI,SAAS,MAAM;AAC7D,UAAM,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { loadCustomFieldValues } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CheckoutLink } from '../../../data/entities'\nimport { CHECKOUT_ENTITY_IDS } from '../../../lib/constants'\nimport { resolveCheckoutPublicCustomFields } from '../../../lib/customFields'\nimport { checkoutPublicViewRateLimitConfig, enforceCheckoutRateLimit } from '../../../lib/rateLimiter'\nimport { handleCheckoutRouteError, readCheckoutAccessCookie, requirePreviewContext } from '../../helpers'\nimport {\n isCheckoutLinkPublic,\n resolveLoadedCheckoutCustomFields,\n serializePublicPayLink,\n verifyCheckoutAccessToken,\n} from '../../../lib/utils'\nimport { checkoutTag } from '../../openapi'\n\nexport const metadata = {\n path: '/checkout/pay/[slug]',\n GET: { requireAuth: false },\n}\n\nexport async function GET(req: Request, { params }: { params: Promise<{ slug: string }> | { slug: string } }) {\n try {\n const resolvedParams = await params\n const url = new URL(req.url)\n const previewRequested = url.searchParams.get('preview') === 'true'\n const previewContext = previewRequested ? await requirePreviewContext(req) : null\n const container = previewContext?.container ?? await createRequestContainer()\n if (!previewRequested) {\n // Fail-open: this endpoint is read-only.\n const rateLimitResponse = await enforceCheckoutRateLimit({\n req,\n container,\n config: checkoutPublicViewRateLimitConfig,\n namespace: 'checkout-public-view',\n errorMessage: 'Too many checkout page requests. Please try again later.',\n posture: 'fail-open',\n })\n if (rateLimitResponse) return rateLimitResponse\n }\n const em = container.resolve('em')\n const previewScope = previewContext ? {\n tenantId: previewContext.auth.tenantId,\n organizationId: previewContext.auth.orgId,\n } : undefined\n const link = await findOneWithDecryption(em, CheckoutLink, {\n slug: resolvedParams.slug,\n deletedAt: null,\n ...previewScope,\n }, undefined, previewScope)\n if (!link || (!previewRequested && !isCheckoutLinkPublic(link.status))) {\n return NextResponse.json({ error: 'Payment link not found' }, { status: 404 })\n }\n const available = link.maxCompletions == null\n ? true\n : (link.completionCount + link.activeReservationCount) < link.maxCompletions\n const token = readCheckoutAccessCookie(req)\n const passwordVerified = previewRequested || !link.passwordHash || verifyCheckoutAccessToken(token, link.slug, {\n linkId: link.id,\n sessionVersion: link.passwordHash,\n })\n if (!passwordVerified) {\n return NextResponse.json({\n requiresPassword: true,\n title: link.title ?? link.name,\n })\n }\n const customValues = await loadCustomFieldValues({\n em,\n entityId: CHECKOUT_ENTITY_IDS.link,\n recordIds: [link.id],\n tenantIdByRecord: { [link.id]: link.tenantId },\n organizationIdByRecord: { [link.id]: link.organizationId },\n })\n const normalizedCustomValues = resolveLoadedCheckoutCustomFields(customValues[link.id])\n const publicCustomFields = await resolveCheckoutPublicCustomFields({\n em,\n entityId: CHECKOUT_ENTITY_IDS.link,\n tenantId: link.tenantId,\n organizationId: link.organizationId,\n customFieldsetCode: link.customFieldsetCode ?? null,\n customValues: normalizedCustomValues,\n displayCustomFieldsOnPage: link.displayCustomFieldsOnPage,\n })\n return NextResponse.json({\n ...serializePublicPayLink(link),\n publicCustomFields,\n available: previewRequested ? false : available,\n remainingUses: link.maxCompletions == null\n ? null\n : Math.max(0, link.maxCompletions - link.completionCount - link.activeReservationCount),\n requiresPassword: false,\n preview: previewRequested,\n })\n } catch (error) {\n return handleCheckoutRouteError(error)\n }\n}\n\nexport const openApi = {\n tags: [checkoutTag],\n}\n\nexport default GET\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,yCAAyC;AAClD,SAAS,mCAAmC,gCAAgC;AAC5E,SAAS,0BAA0B,0BAA0B,6BAA6B;AAC1F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAErB,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,KAAK,EAAE,aAAa,MAAM;AAC5B;AAEA,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA6D;AAC5G,MAAI;AACF,UAAM,iBAAiB,MAAM;AAC7B,UAAM,MAAM,IAAI,IAAI,IAAI,GAAG;AAC3B,UAAM,mBAAmB,IAAI,aAAa,IAAI,SAAS,MAAM;AAC7D,UAAM,iBAAiB,mBAAmB,MAAM,sBAAsB,GAAG,IAAI;AAC7E,UAAM,YAAY,gBAAgB,aAAa,MAAM,uBAAuB;AAC5E,QAAI,CAAC,kBAAkB;AAErB,YAAM,oBAAoB,MAAM,yBAAyB;AAAA,QACvD;AAAA,QACA;AAAA,QACA,QAAQ;AAAA,QACR,WAAW;AAAA,QACX,cAAc;AAAA,QACd,SAAS;AAAA,MACX,CAAC;AACD,UAAI,kBAAmB,QAAO;AAAA,IAChC;AACA,UAAM,KAAK,UAAU,QAAQ,IAAI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rB,oBAAoB,KAAK,sBAAsB;AAAA,MAC/C,cAAc;AAAA,MACd,2BAA2B,KAAK;AAAA,IAClC,CAAC;AACD,WAAO,aAAa,KAAK;AAAA,MACvB,GAAG,uBAAuB,IAAI;AAAA,MAC9B;AAAA,MACA,WAAW,mBAAmB,QAAQ;AAAA,MACtC,eAAe,KAAK,kBAAkB,OAClC,OACA,KAAK,IAAI,GAAG,KAAK,iBAAiB,KAAK,kBAAkB,KAAK,sBAAsB;AAAA,MACxF,kBAAkB;AAAA,MAClB,SAAS;AAAA,IACX,CAAC;AAAA,EACH,SAAS,OAAO;AACd,WAAO,yBAAyB,KAAK;AAAA,EACvC;AACF;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,WAAW;AACpB;AAEA,IAAO,gBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/checkout",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.7799.1.d9cd0c8e41",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -62,18 +62,18 @@
|
|
|
62
62
|
}
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@open-mercato/core": "0.10.1-develop.
|
|
66
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
65
|
+
"@open-mercato/core": "0.10.1-develop.7799.1.d9cd0c8e41",
|
|
66
|
+
"@open-mercato/ui": "0.10.1-develop.7799.1.d9cd0c8e41",
|
|
67
67
|
"bcryptjs": "^3.0.3"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
70
|
"@mikro-orm/postgresql": "^7.0.14",
|
|
71
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
71
|
+
"@open-mercato/shared": "0.10.1-develop.7799.1.d9cd0c8e41",
|
|
72
72
|
"react": "^19.0.0",
|
|
73
73
|
"react-dom": "^19.0.0"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
76
|
+
"@open-mercato/shared": "0.10.1-develop.7799.1.d9cd0c8e41",
|
|
77
77
|
"@types/jest": "^30.0.0",
|
|
78
78
|
"@types/react": "^19.2.18",
|
|
79
79
|
"@types/react-dom": "^19.2.5",
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { expect, test } from '@playwright/test'
|
|
3
|
+
import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
|
|
4
|
+
import {
|
|
5
|
+
createOrganizationFixture,
|
|
6
|
+
createRoleFixture,
|
|
7
|
+
createUserFixture,
|
|
8
|
+
deleteOrganizationIfExists,
|
|
9
|
+
deleteRoleIfExists,
|
|
10
|
+
deleteUserIfExists,
|
|
11
|
+
setRoleAclFeatures,
|
|
12
|
+
} from '@open-mercato/core/helpers/integration/authFixtures'
|
|
13
|
+
import { deleteGeneralEntityIfExists, expectId, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
|
|
14
|
+
import { createFixedTemplateInput, readPublicPayLink } from './helpers/fixtures'
|
|
15
|
+
|
|
16
|
+
type Scope = { tenantId: string; organizationId: string }
|
|
17
|
+
type LinkFixture = Scope & { id: string; slug: string; title: string; status: 'draft' | 'inactive' | 'active' }
|
|
18
|
+
|
|
19
|
+
function scopeHeaders(scope: Scope) {
|
|
20
|
+
return { Cookie: `om_selected_tenant=${scope.tenantId}; om_selected_org=${scope.organizationId}` }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
test.describe('TC-CHKT-045: Checkout preview tenant and organization isolation', () => {
|
|
24
|
+
const label = `checkout-preview-${randomUUID()}`
|
|
25
|
+
const password = `Qa-${randomUUID()}-Aa1!`
|
|
26
|
+
const email = `${label}@example.com`
|
|
27
|
+
const tenantIds: string[] = []
|
|
28
|
+
const organizationIds: string[] = []
|
|
29
|
+
const links: LinkFixture[] = []
|
|
30
|
+
let superadminToken: string | null = null
|
|
31
|
+
let roleId: string | null = null
|
|
32
|
+
let userId: string | null = null
|
|
33
|
+
let ownScope: Scope
|
|
34
|
+
let viewerToken: string
|
|
35
|
+
|
|
36
|
+
test.beforeAll(async ({ request }) => {
|
|
37
|
+
superadminToken = await getAuthToken(request, 'superadmin')
|
|
38
|
+
for (const suffix of ['a', 'b']) {
|
|
39
|
+
const response = await apiRequest(request, 'POST', '/api/directory/tenants', {
|
|
40
|
+
token: superadminToken,
|
|
41
|
+
data: { name: `${label}-${suffix}` },
|
|
42
|
+
})
|
|
43
|
+
const body = await readJsonSafe<{ id?: string }>(response)
|
|
44
|
+
expect(response.status()).toBe(201)
|
|
45
|
+
tenantIds.push(expectId(body?.id, 'Tenant fixture must have an id'))
|
|
46
|
+
}
|
|
47
|
+
for (const tenantId of [tenantIds[0], tenantIds[0], tenantIds[1]]) {
|
|
48
|
+
organizationIds.push(await createOrganizationFixture(request, superadminToken, {
|
|
49
|
+
name: `${label}-org-${organizationIds.length}`,
|
|
50
|
+
tenantId,
|
|
51
|
+
}))
|
|
52
|
+
}
|
|
53
|
+
ownScope = { tenantId: tenantIds[0], organizationId: organizationIds[0] }
|
|
54
|
+
const scopes: Scope[] = [
|
|
55
|
+
ownScope,
|
|
56
|
+
{ tenantId: tenantIds[0], organizationId: organizationIds[1] },
|
|
57
|
+
{ tenantId: tenantIds[1], organizationId: organizationIds[2] },
|
|
58
|
+
]
|
|
59
|
+
roleId = await createRoleFixture(request, superadminToken, { name: label, tenantId: ownScope.tenantId })
|
|
60
|
+
await setRoleAclFeatures(request, superadminToken, {
|
|
61
|
+
roleId,
|
|
62
|
+
features: ['checkout.view'],
|
|
63
|
+
organizations: [ownScope.organizationId],
|
|
64
|
+
})
|
|
65
|
+
userId = await createUserFixture(request, superadminToken, {
|
|
66
|
+
email,
|
|
67
|
+
password,
|
|
68
|
+
organizationId: ownScope.organizationId,
|
|
69
|
+
roles: [roleId],
|
|
70
|
+
})
|
|
71
|
+
viewerToken = await getAuthToken(request, email, password)
|
|
72
|
+
|
|
73
|
+
for (const scope of scopes) {
|
|
74
|
+
for (const status of ['draft', 'inactive', 'active'] as const) {
|
|
75
|
+
const title = `${label}-${links.length}`
|
|
76
|
+
const response = await apiRequest(request, 'POST', '/api/checkout/links', {
|
|
77
|
+
token: superadminToken,
|
|
78
|
+
headers: scopeHeaders(scope),
|
|
79
|
+
data: createFixedTemplateInput({ status, title, password, collectCustomerDetails: false }),
|
|
80
|
+
})
|
|
81
|
+
const body = await readJsonSafe<{ id?: string; slug?: string }>(response)
|
|
82
|
+
expect(response.status()).toBe(201)
|
|
83
|
+
links.push({
|
|
84
|
+
...scope,
|
|
85
|
+
id: expectId(body?.id, 'Link fixture must have an id'),
|
|
86
|
+
slug: expectId(body?.slug, 'Link fixture must have a slug'),
|
|
87
|
+
title,
|
|
88
|
+
status,
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test('limits a checkout.view user to same-scope previews and preserves public gates', async ({ request }) => {
|
|
96
|
+
for (const link of links) {
|
|
97
|
+
const preview = await apiRequest(request, 'GET', `/api/checkout/pay/${encodeURIComponent(link.slug)}?preview=true`, {
|
|
98
|
+
token: viewerToken,
|
|
99
|
+
})
|
|
100
|
+
if (link.tenantId === ownScope.tenantId && link.organizationId === ownScope.organizationId) {
|
|
101
|
+
expect(preview.status(), `Same-scope ${link.status} preview`).toBe(200)
|
|
102
|
+
expect(await readJsonSafe(preview)).toMatchObject({
|
|
103
|
+
id: link.id, title: link.title, preview: true, available: false, requiresPassword: false,
|
|
104
|
+
})
|
|
105
|
+
} else {
|
|
106
|
+
expect(preview.status(), `Foreign-scope ${link.status} preview`).toBe(404)
|
|
107
|
+
expect(await readJsonSafe(preview)).toEqual({ error: 'Payment link not found' })
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const publicResponse = await readPublicPayLink(request, link.slug)
|
|
111
|
+
if (link.status === 'active') {
|
|
112
|
+
expect(publicResponse.status()).toBe(200)
|
|
113
|
+
expect(await readJsonSafe(publicResponse)).toEqual({ requiresPassword: true, title: link.title })
|
|
114
|
+
} else {
|
|
115
|
+
expect(publicResponse.status()).toBe(404)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
test.afterAll(async ({ request }) => {
|
|
121
|
+
if (superadminToken) {
|
|
122
|
+
for (const link of links.reverse()) {
|
|
123
|
+
await apiRequest(request, 'DELETE', `/api/checkout/links/${encodeURIComponent(link.id)}`, {
|
|
124
|
+
token: superadminToken,
|
|
125
|
+
headers: scopeHeaders(link),
|
|
126
|
+
}).catch(() => undefined)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
await deleteUserIfExists(request, superadminToken, userId)
|
|
130
|
+
await deleteRoleIfExists(request, superadminToken, roleId)
|
|
131
|
+
for (const organizationId of organizationIds.reverse()) {
|
|
132
|
+
await deleteOrganizationIfExists(request, superadminToken, organizationId)
|
|
133
|
+
}
|
|
134
|
+
for (const tenantId of tenantIds.reverse()) {
|
|
135
|
+
await deleteGeneralEntityIfExists(request, superadminToken, '/api/directory/tenants', tenantId)
|
|
136
|
+
}
|
|
137
|
+
})
|
|
138
|
+
})
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
|
|
2
|
+
import { loadCustomFieldValues } from '@open-mercato/shared/lib/crud/custom-fields'
|
|
3
|
+
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
4
|
+
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
5
|
+
import { CheckoutLink } from '../../../../data/entities'
|
|
6
|
+
import { enforceCheckoutRateLimit } from '../../../../lib/rateLimiter'
|
|
7
|
+
import { GET } from '../route'
|
|
8
|
+
|
|
9
|
+
jest.mock('@open-mercato/shared/lib/auth/server', () => ({ getAuthFromRequest: jest.fn() }))
|
|
10
|
+
jest.mock('@open-mercato/shared/lib/crud/custom-fields', () => ({ loadCustomFieldValues: jest.fn() }))
|
|
11
|
+
jest.mock('@open-mercato/shared/lib/di/container', () => ({ createRequestContainer: jest.fn() }))
|
|
12
|
+
jest.mock('@open-mercato/shared/lib/encryption/find', () => ({ findOneWithDecryption: jest.fn() }))
|
|
13
|
+
jest.mock('../../../../lib/customFields', () => ({
|
|
14
|
+
resolveCheckoutPublicCustomFields: jest.fn().mockResolvedValue([]),
|
|
15
|
+
}))
|
|
16
|
+
jest.mock('../../../../lib/rateLimiter', () => ({
|
|
17
|
+
checkoutPublicViewRateLimitConfig: {},
|
|
18
|
+
enforceCheckoutRateLimit: jest.fn(),
|
|
19
|
+
}))
|
|
20
|
+
|
|
21
|
+
const tenantId = '11111111-1111-4111-8111-111111111111'
|
|
22
|
+
const organizationId = '22222222-2222-4222-8222-222222222222'
|
|
23
|
+
const foreignTenantId = '33333333-3333-4333-8333-333333333333'
|
|
24
|
+
const foreignOrganizationId = '44444444-4444-4444-8444-444444444444'
|
|
25
|
+
const userHasAllFeatures = jest.fn()
|
|
26
|
+
const em = {}
|
|
27
|
+
let link: CheckoutLink
|
|
28
|
+
|
|
29
|
+
function readLink(preview = true) {
|
|
30
|
+
return GET(
|
|
31
|
+
new Request(`https://merchant.example/api/checkout/pay/donate${preview ? '?preview=true' : ''}`),
|
|
32
|
+
{ params: { slug: 'donate' } },
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
describe('GET /api/checkout/pay/[slug] preview scope', () => {
|
|
37
|
+
beforeEach(() => {
|
|
38
|
+
jest.clearAllMocks()
|
|
39
|
+
link = Object.assign(new CheckoutLink(), {
|
|
40
|
+
id: '55555555-5555-4555-8555-555555555555',
|
|
41
|
+
slug: 'donate',
|
|
42
|
+
name: 'Donate',
|
|
43
|
+
title: 'Donate',
|
|
44
|
+
tenantId,
|
|
45
|
+
organizationId,
|
|
46
|
+
pricingMode: 'fixed',
|
|
47
|
+
fixedPriceAmount: '25.00',
|
|
48
|
+
fixedPriceCurrencyCode: 'USD',
|
|
49
|
+
status: 'draft',
|
|
50
|
+
deletedAt: null,
|
|
51
|
+
})
|
|
52
|
+
jest.mocked(getAuthFromRequest).mockResolvedValue({ sub: 'viewer', tenantId, orgId: organizationId })
|
|
53
|
+
userHasAllFeatures.mockResolvedValue(true)
|
|
54
|
+
jest.mocked(createRequestContainer).mockResolvedValue({
|
|
55
|
+
resolve: (name: string) => {
|
|
56
|
+
const dependencies: Record<string, unknown> = { em, commandBus: {}, rbacService: { userHasAllFeatures } }
|
|
57
|
+
return dependencies[name]
|
|
58
|
+
},
|
|
59
|
+
} as unknown as Awaited<ReturnType<typeof createRequestContainer>>)
|
|
60
|
+
jest.mocked(findOneWithDecryption).mockImplementation(async (_em, _entity, where) => {
|
|
61
|
+
const filters = where as Record<string, unknown>
|
|
62
|
+
return Object.entries(filters).every(([key, value]) => link[key as keyof CheckoutLink] === value)
|
|
63
|
+
? link
|
|
64
|
+
: null
|
|
65
|
+
})
|
|
66
|
+
jest.mocked(loadCustomFieldValues).mockResolvedValue({})
|
|
67
|
+
jest.mocked(enforceCheckoutRateLimit).mockResolvedValue(null)
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it.each(['draft', 'inactive', 'active'] as const)('previews a same-scope %s link without its password', async (status) => {
|
|
71
|
+
link.status = status
|
|
72
|
+
link.passwordHash = 'protected-link-hash'
|
|
73
|
+
|
|
74
|
+
const response = await readLink()
|
|
75
|
+
|
|
76
|
+
expect(response.status).toBe(200)
|
|
77
|
+
expect(await response.json()).toMatchObject({ id: link.id, preview: true, available: false, requiresPassword: false })
|
|
78
|
+
expect(userHasAllFeatures).toHaveBeenCalledWith('viewer', ['checkout.view'], { tenantId, organizationId })
|
|
79
|
+
expect(findOneWithDecryption).toHaveBeenCalledWith(
|
|
80
|
+
em,
|
|
81
|
+
CheckoutLink,
|
|
82
|
+
{ slug: 'donate', deletedAt: null, tenantId, organizationId },
|
|
83
|
+
undefined,
|
|
84
|
+
{ tenantId, organizationId },
|
|
85
|
+
)
|
|
86
|
+
expect(enforceCheckoutRateLimit).not.toHaveBeenCalled()
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
describe.each([
|
|
90
|
+
['another tenant', { tenantId: foreignTenantId }],
|
|
91
|
+
['another organization', { organizationId: foreignOrganizationId }],
|
|
92
|
+
] as const)('%s', (_description, foreignScope) => {
|
|
93
|
+
it.each(['draft', 'inactive', 'active'] as const)('returns 404 for a protected %s preview', async (status) => {
|
|
94
|
+
Object.assign(link, foreignScope, { status, passwordHash: 'protected-link-hash' })
|
|
95
|
+
|
|
96
|
+
const response = await readLink()
|
|
97
|
+
|
|
98
|
+
expect(response.status).toBe(404)
|
|
99
|
+
expect(await response.json()).toEqual({ error: 'Payment link not found' })
|
|
100
|
+
expect(loadCustomFieldValues).not.toHaveBeenCalled()
|
|
101
|
+
})
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
it.each([
|
|
105
|
+
null,
|
|
106
|
+
{ sub: 'viewer', tenantId: null, orgId: organizationId },
|
|
107
|
+
{ sub: 'viewer', tenantId, orgId: null },
|
|
108
|
+
])('rejects a preview without a complete authenticated scope: %j', async (auth) => {
|
|
109
|
+
jest.mocked(getAuthFromRequest).mockResolvedValue(auth)
|
|
110
|
+
|
|
111
|
+
const response = await readLink()
|
|
112
|
+
|
|
113
|
+
expect(response.status).toBe(401)
|
|
114
|
+
expect(findOneWithDecryption).not.toHaveBeenCalled()
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
it('rejects a preview without checkout.view', async () => {
|
|
118
|
+
userHasAllFeatures.mockResolvedValue(false)
|
|
119
|
+
|
|
120
|
+
const response = await readLink()
|
|
121
|
+
|
|
122
|
+
expect(response.status).toBe(403)
|
|
123
|
+
expect(findOneWithDecryption).not.toHaveBeenCalled()
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
it('returns the same 404 for deleted and unknown links', async () => {
|
|
127
|
+
link.deletedAt = new Date()
|
|
128
|
+
expect((await readLink()).status).toBe(404)
|
|
129
|
+
jest.mocked(findOneWithDecryption).mockResolvedValue(null)
|
|
130
|
+
expect((await readLink()).status).toBe(404)
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it('serves an active public link outside the caller scope without authenticating', async () => {
|
|
134
|
+
Object.assign(link, { tenantId: foreignTenantId, organizationId: foreignOrganizationId, status: 'active' })
|
|
135
|
+
|
|
136
|
+
const response = await readLink(false)
|
|
137
|
+
|
|
138
|
+
expect(response.status).toBe(200)
|
|
139
|
+
expect(await response.json()).toMatchObject({ id: link.id, preview: false, requiresPassword: false })
|
|
140
|
+
expect(getAuthFromRequest).not.toHaveBeenCalled()
|
|
141
|
+
expect(enforceCheckoutRateLimit).toHaveBeenCalled()
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
it.each(['draft', 'inactive'] as const)('keeps a %s link unavailable to the public', async (status) => {
|
|
145
|
+
link.status = status
|
|
146
|
+
expect((await readLink(false)).status).toBe(404)
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
it('keeps the public password gate for an active protected link', async () => {
|
|
150
|
+
Object.assign(link, { tenantId: foreignTenantId, status: 'active', passwordHash: 'protected-link-hash' })
|
|
151
|
+
|
|
152
|
+
const response = await readLink(false)
|
|
153
|
+
|
|
154
|
+
expect(response.status).toBe(200)
|
|
155
|
+
expect(await response.json()).toEqual({ requiresPassword: true, title: 'Donate' })
|
|
156
|
+
expect(loadCustomFieldValues).not.toHaveBeenCalled()
|
|
157
|
+
})
|
|
158
|
+
})
|
|
@@ -148,7 +148,10 @@ describe('GET /api/checkout/pay/[slug] public response', () => {
|
|
|
148
148
|
{ key: 'campaign', label: 'Campaign', value: 'Community', kind: 'text', multi: false },
|
|
149
149
|
])
|
|
150
150
|
jest.mocked(readCheckoutAccessCookie).mockReturnValue(null)
|
|
151
|
-
jest.mocked(requirePreviewContext).mockResolvedValue({
|
|
151
|
+
jest.mocked(requirePreviewContext).mockResolvedValue({
|
|
152
|
+
auth: { sub: 'viewer', tenantId: link.tenantId, orgId: link.organizationId },
|
|
153
|
+
container: { resolve: () => ({}) },
|
|
154
|
+
} as Awaited<ReturnType<typeof requirePreviewContext>>)
|
|
152
155
|
})
|
|
153
156
|
|
|
154
157
|
afterAll(() => {
|
|
@@ -25,8 +25,8 @@ export async function GET(req: Request, { params }: { params: Promise<{ slug: st
|
|
|
25
25
|
const resolvedParams = await params
|
|
26
26
|
const url = new URL(req.url)
|
|
27
27
|
const previewRequested = url.searchParams.get('preview') === 'true'
|
|
28
|
-
const
|
|
29
|
-
|
|
28
|
+
const previewContext = previewRequested ? await requirePreviewContext(req) : null
|
|
29
|
+
const container = previewContext?.container ?? await createRequestContainer()
|
|
30
30
|
if (!previewRequested) {
|
|
31
31
|
// Fail-open: this endpoint is read-only.
|
|
32
32
|
const rateLimitResponse = await enforceCheckoutRateLimit({
|
|
@@ -40,10 +40,15 @@ export async function GET(req: Request, { params }: { params: Promise<{ slug: st
|
|
|
40
40
|
if (rateLimitResponse) return rateLimitResponse
|
|
41
41
|
}
|
|
42
42
|
const em = container.resolve('em')
|
|
43
|
+
const previewScope = previewContext ? {
|
|
44
|
+
tenantId: previewContext.auth.tenantId,
|
|
45
|
+
organizationId: previewContext.auth.orgId,
|
|
46
|
+
} : undefined
|
|
43
47
|
const link = await findOneWithDecryption(em, CheckoutLink, {
|
|
44
48
|
slug: resolvedParams.slug,
|
|
45
49
|
deletedAt: null,
|
|
46
|
-
|
|
50
|
+
...previewScope,
|
|
51
|
+
}, undefined, previewScope)
|
|
47
52
|
if (!link || (!previewRequested && !isCheckoutLinkPublic(link.status))) {
|
|
48
53
|
return NextResponse.json({ error: 'Payment link not found' }, { status: 404 })
|
|
49
54
|
}
|