@revenexx/cover 0.10.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/app/api/account.ts +4 -0
  2. package/app/assets/css/cover.css +9 -0
  3. package/app/components/RevenexxForm.vue +4 -0
  4. package/app/components/account/AccountSidebar.vue +2 -5
  5. package/app/components/account/carts/AccountCartsTable.vue +4 -2
  6. package/app/components/account/dashboard/AccountDashboardKpis.vue +74 -34
  7. package/app/components/account/dashboard/AccountDashboardQuickActions.vue +24 -6
  8. package/app/components/account/organization/AccountOrganization.vue +3 -1
  9. package/app/components/account/team/AccountTeam.vue +32 -7
  10. package/app/components/auth/AuthForgotPasswordPanel.vue +9 -4
  11. package/app/components/auth/AuthLoginPanel.vue +75 -18
  12. package/app/components/auth/AuthRegisterPanel.vue +1 -1
  13. package/app/components/cart/actions/CartSaveToListModal.vue +5 -0
  14. package/app/components/cart/item/CartItem.vue +17 -75
  15. package/app/components/cart/position/CartPosition.vue +17 -30
  16. package/app/components/cart/quote/CartQuoteRequestModal.vue +9 -1
  17. package/app/components/cart/switcher/CartSwitcher.vue +5 -2
  18. package/app/components/category/view/GridView.vue +10 -1
  19. package/app/components/category/view/ListView.vue +10 -1
  20. package/app/components/checkout/confirmation/CheckoutConfirmationActions.vue +2 -0
  21. package/app/components/checkout/onepage/CheckoutAddressSection.vue +4 -4
  22. package/app/components/checkout/onepage/CheckoutDeliverySection.vue +18 -2
  23. package/app/components/checkout/onepage/CheckoutGate.vue +2 -0
  24. package/app/components/checkout/onepage/CheckoutOnePageView.vue +1 -1
  25. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +10 -0
  26. package/app/components/checkout/onepage/CheckoutSummarySection.vue +7 -1
  27. package/app/components/layout/Region.vue +13 -0
  28. package/app/components/layout/footer/Footer.vue +8 -0
  29. package/app/components/layout/header/AppBar.vue +4 -3
  30. package/app/components/layout/header/MainNav.vue +3 -3
  31. package/app/components/listing/ListingResults.vue +3 -1
  32. package/app/components/product/card/Compact.vue +10 -1
  33. package/app/components/product/detail/ProductDetailAddToCart.vue +51 -18
  34. package/app/components/product/detail/ProductDetailIdentity.vue +1 -1
  35. package/app/components/product/detail/ProductDetailPriceRequest.vue +1 -1
  36. package/app/components/product/detail/ProductDetailSaveToList.vue +10 -0
  37. package/app/composables/useAccountDashboard.ts +0 -10
  38. package/app/composables/useAccountNavigation.ts +35 -0
  39. package/app/composables/useAuthStore.ts +6 -2
  40. package/app/composables/useCategoryListing.ts +6 -0
  41. package/app/composables/useCheckoutOnePage.ts +21 -2
  42. package/app/composables/useMasterDataEditable.ts +23 -0
  43. package/app/composables/useProductCard.ts +29 -2
  44. package/app/composables/useProductListing.ts +79 -0
  45. package/app/composables/useQuantityStepper.ts +90 -0
  46. package/app/composables/useQuickActions.ts +35 -0
  47. package/app/composables/useRoleGrants.ts +32 -0
  48. package/app/composables/useSearchListing.ts +4 -0
  49. package/app/composables/useThemeEvents.ts +144 -0
  50. package/app/config/accountDashboard.ts +26 -0
  51. package/app/config/quickActions.ts +40 -5
  52. package/app/interfaces/account/dashboard.ts +2 -0
  53. package/app/interfaces/auth.ts +25 -4
  54. package/app/interfaces/quantity-stepper.ts +17 -0
  55. package/app/interfaces/shopSettings.ts +84 -0
  56. package/app/layouts/default.vue +19 -10
  57. package/app/layouts/focus.vue +28 -7
  58. package/app/middleware/checkout-guard.ts +7 -1
  59. package/app/pages/punchout/transfer.vue +22 -0
  60. package/app/plugins/theme-events.client.ts +132 -0
  61. package/app/shared/themeEvents.ts +445 -0
  62. package/i18n/locales/de/account.json +7 -0
  63. package/i18n/locales/de/auth.json +42 -2
  64. package/i18n/locales/de/cart.json +4 -2
  65. package/i18n/locales/de/checkout.json +2 -1
  66. package/i18n/locales/de/common.json +2 -0
  67. package/i18n/locales/de/cover.json +44 -0
  68. package/i18n/locales/de/editor.json +47 -1
  69. package/i18n/locales/en/account.json +7 -0
  70. package/i18n/locales/en/auth.json +42 -2
  71. package/i18n/locales/en/cart.json +4 -2
  72. package/i18n/locales/en/checkout.json +2 -1
  73. package/i18n/locales/en/common.json +2 -0
  74. package/i18n/locales/en/cover.json +44 -0
  75. package/i18n/locales/en/editor.json +47 -1
  76. package/nuxt.config.ts +15 -1
  77. package/package.json +5 -2
  78. package/server/api/account/orders/[id]/cancel.post.ts +1 -1
  79. package/server/api/account/orders/[id]/messages.get.ts +1 -1
  80. package/server/api/account/orders/[id]/messages.post.ts +1 -1
  81. package/server/api/account/orders/[id]/return.post.ts +1 -0
  82. package/server/api/account/orders/[id].get.ts +1 -1
  83. package/server/api/account/pending-approvals/index.get.ts +1 -0
  84. package/server/api/account/profile.get.ts +3 -1
  85. package/server/api/auth/login.post.ts +22 -3
  86. package/server/api/auth/magic-link.put.ts +6 -1
  87. package/server/api/auth/otp.put.ts +6 -1
  88. package/server/api/carts/[id]/activate.post.ts +8 -0
  89. package/server/api/carts/[id]/index.delete.ts +3 -0
  90. package/server/api/carts/[id]/index.put.ts +1 -0
  91. package/server/api/carts/[id]/items.post.ts +1 -0
  92. package/server/api/carts/index.post.ts +4 -0
  93. package/server/api/orders/index.post.ts +33 -0
  94. package/server/api/quick-actions.get.ts +6 -38
  95. package/server/interfaces/auth.ts +10 -1
  96. package/server/middleware/buyer-principal.ts +18 -0
  97. package/server/routes/punchout/start.get.ts +6 -15
  98. package/server/services/ApiAddressBookService.ts +43 -1
  99. package/server/services/ApiAuthService.ts +119 -22
  100. package/server/services/ApiCartService.ts +67 -32
  101. package/server/services/ApiOrganizationService.ts +7 -2
  102. package/server/services/ApiTeamService.ts +93 -21
  103. package/server/services/MockAuthService.ts +21 -2
  104. package/server/utils/buyerIdentity.ts +168 -0
  105. package/server/utils/cartOwnership.ts +67 -0
  106. package/server/utils/liveOrderLists.ts +50 -23
  107. package/server/utils/liveOrders.ts +39 -24
  108. package/server/utils/livePrices.ts +7 -15
  109. package/server/utils/masterData.ts +29 -0
  110. package/server/utils/passwordlessSignIn.ts +13 -4
  111. package/server/utils/pendingApprovals.ts +29 -7
  112. package/server/utils/procurementCheckout.ts +2 -0
  113. package/server/utils/quickActionCatalogue.ts +53 -0
  114. package/server/utils/revenexxSdk.ts +116 -2
  115. package/server/utils/shopSettings.ts +5 -0
@@ -23,8 +23,9 @@ function toAccountOrganization(row: ApiOrgRow): AccountOrganization {
23
23
 
24
24
  /**
25
25
  * Live company data: the signed-in contact's organization in the customers
26
- * app. The organization id comes from the session cookie (auth/me link);
27
- * contacts without an organization (private buyers) have none.
26
+ * app. The organization is the one the identity service verified for this
27
+ * request (RAD-155) — never an id the browser supplied; contacts without an
28
+ * organization (private buyers) have none.
28
29
  */
29
30
  export class ApiOrganizationService implements IOrganizationService {
30
31
  async get(event: H3Event): Promise<AccountOrganization | null> {
@@ -58,6 +59,10 @@ export class ApiOrganizationService implements IOrganizationService {
58
59
  return toAccountOrganization(row);
59
60
  }
60
61
  catch (err) {
62
+ const refused = selfServiceRefusal(err);
63
+ if (refused) {
64
+ throw refused;
65
+ }
61
66
  if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
62
67
  throw createError({ statusCode: 422, message: err.message });
63
68
  }
@@ -39,10 +39,59 @@ function toAccountTeamMember(row: ApiContactRow): AccountTeamMember {
39
39
  };
40
40
  }
41
41
 
42
+ function refusal(err: unknown, what: string): never {
43
+ const refused = selfServiceRefusal(err);
44
+ if (refused) {
45
+ throw refused;
46
+ }
47
+ if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
48
+ throw createError({ statusCode: 422, message: err.message });
49
+ }
50
+ getLogService().error(`API request failed: team/${what}`, apiErrorContext(err));
51
+ throw createError({ statusCode: 502, statusMessage: "Team service unavailable" });
52
+ }
53
+
54
+ /**
55
+ * The verified buyer who may run their organization's people: signed in, in an
56
+ * organization, and holding `contacts.manage`. Fails closed — a live session
57
+ * always states its permissions, so "not stated" is not a grant here.
58
+ */
59
+ function requireTeamManager(event: H3Event): { contactId: string; organizationId: string; role: string | undefined } {
60
+ const buyer = verifiedBuyer(event);
61
+ if (!buyer?.contactId) {
62
+ throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
63
+ }
64
+ if (!buyer.organizationId) {
65
+ throw createError({ statusCode: 403, message: "Only a company account has people to manage.", data: { type: "no_organization" } });
66
+ }
67
+ if (!buyerHolds(buyer, "contacts.manage", false)) {
68
+ throw createError({
69
+ statusCode: 403,
70
+ message: "Your role does not allow managing your company's people.",
71
+ data: { type: "permission_missing", permission: "contacts.manage" },
72
+ });
73
+ }
74
+ return { contactId: buyer.contactId, organizationId: buyer.organizationId, role: buyer.role };
75
+ }
76
+
77
+ function refuseRoleAbove(): never {
78
+ throw createError({
79
+ statusCode: 403,
80
+ message: "You cannot give anybody a role above your own.",
81
+ data: { type: "role_above_own" },
82
+ });
83
+ }
84
+
42
85
  /**
43
86
  * Live team data: the contacts of the signed-in contact's organization in the
44
- * customers app. The organization id comes from the session cookie (auth/me
45
- * link); contacts without an organization (private buyers) get an empty list.
87
+ * customers app. The organization is the one the identity service verified for
88
+ * this request (RAD-155), never one the browser named; contacts without an
89
+ * organization (private buyers) get an empty list.
90
+ *
91
+ * Writes are held to three rules here, ahead of the customers app's own:
92
+ * the caller holds `contacts.manage`, the person changed is in the caller's
93
+ * organization (anybody else is not found), and nobody is given — or taken
94
+ * from — a role above the caller's own.
46
95
  */
47
96
  export class ApiTeamService implements ITeamService {
48
97
  async list(event: H3Event): Promise<AccountTeamMember[]> {
@@ -66,43 +115,66 @@ export class ApiTeamService implements ITeamService {
66
115
  }
67
116
 
68
117
  async invite(event: H3Event, input: AccountTeamMemberFormState): Promise<AccountTeamMember> {
69
- const { organization_id } = sessionOrderRefs(event);
70
- if (!organization_id) {
71
- throw createError({ statusCode: 401, statusMessage: "No organization in session" });
118
+ const caller = requireTeamManager(event);
119
+ if (!mayGrantRole(caller.role, input.role)) {
120
+ refuseRoleAbove();
72
121
  }
122
+ let row: ApiContactRow;
73
123
  try {
74
- const row = await useRevenexxSdk().customersContacts.customersContactsCreate({
124
+ row = await useRevenexxSdk().customersContacts.customersContactsCreate({
75
125
  email: input.email,
76
126
  firstName: input.firstName || undefined,
77
127
  lastName: input.lastName || undefined,
78
128
  role: input.role,
79
- organizationId: organization_id,
129
+ organizationId: caller.organizationId,
80
130
  }) as unknown as ApiContactRow;
81
- return toAccountTeamMember(row);
82
131
  }
83
132
  catch (err) {
84
- if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
85
- throw createError({ statusCode: 422, message: err.message });
86
- }
87
- getLogService().error("API request failed: team/invite", apiErrorContext(err));
88
- throw createError({ statusCode: 502, statusMessage: "Team service unavailable" });
133
+ refusal(err, "invite");
89
134
  }
135
+ return toAccountTeamMember(row);
90
136
  }
91
137
 
92
- async update(_event: H3Event, id: string, patch: { role: AccountTeamRole }): Promise<AccountTeamMember> {
138
+ async update(event: H3Event, id: string, patch: { role: AccountTeamRole }): Promise<AccountTeamMember> {
139
+ const caller = requireTeamManager(event);
140
+ if (id === caller.contactId) {
141
+ throw createError({
142
+ statusCode: 403,
143
+ message: "Your own role is set by the merchant.",
144
+ data: { type: "own_role" },
145
+ });
146
+ }
147
+
148
+ // Whose contact is this? Anybody outside the caller's organization is
149
+ // answered exactly like an id that does not exist.
150
+ let target: ApiContactRow | null = null;
93
151
  try {
94
- const row = await useRevenexxSdk().customersContacts.customersContactsUpdate({
152
+ target = await useRevenexxSdk().customersContacts.customersContactsGet({ id }) as unknown as ApiContactRow;
153
+ }
154
+ catch (err) {
155
+ if (!(err instanceof RevenexxException && err.code === 404)) {
156
+ refusal(err, "get");
157
+ }
158
+ }
159
+ if (!target || target.organization_id !== caller.organizationId) {
160
+ throw createError({ statusCode: 404, statusMessage: "Team member not found" });
161
+ }
162
+ // Neither hand out a role above one's own, nor take one away from
163
+ // somebody who holds it.
164
+ if (!mayGrantRole(caller.role, patch.role) || roleRank(target.role) > roleRank(caller.role)) {
165
+ refuseRoleAbove();
166
+ }
167
+
168
+ let row: ApiContactRow;
169
+ try {
170
+ row = await useRevenexxSdk().customersContacts.customersContactsUpdate({
95
171
  id,
96
172
  role: patch.role,
97
173
  }) as unknown as ApiContactRow;
98
- return toAccountTeamMember(row);
99
174
  }
100
175
  catch (err) {
101
- if (err instanceof RevenexxException && (err.code === 400 || err.code === 422)) {
102
- throw createError({ statusCode: 422, message: err.message });
103
- }
104
- getLogService().error("API request failed: team/update", apiErrorContext(err));
105
- throw createError({ statusCode: 502, statusMessage: "Team service unavailable" });
176
+ refusal(err, "update");
106
177
  }
178
+ return toAccountTeamMember(row);
107
179
  }
108
180
  }
@@ -1,6 +1,7 @@
1
1
  import type { H3Event } from "h3";
2
2
 
3
3
  import type { AuthUser, StoredSession } from "../../app/interfaces/auth";
4
+ import { loginIdentifierKind, offeredLoginIdentifiers } from "../../app/interfaces/shopSettings";
4
5
  import type { AuthLoginResult, AuthPersona, IAuthService } from "../interfaces/auth";
5
6
 
6
7
  const SESSION_TTL_MS = 1000 * 60 * 60 * 12; // 12h demo session
@@ -51,8 +52,26 @@ export class MockAuthService implements IAuthService {
51
52
  return { $id: persona.id, name: persona.name, email: persona.email, role: persona.role };
52
53
  }
53
54
 
54
- async login(event: H3Event, email: string): Promise<AuthLoginResult> {
55
- const persona = await this.findPersona(p => p.email.toLowerCase() === email.toLowerCase());
55
+ /**
56
+ * Signs a persona in by whatever the shop accepts, refusing a kind it does
57
+ * not the way the customers app does — so the demo shows the same answer a
58
+ * live shop gives rather than one only the demo can.
59
+ */
60
+ async login(event: H3Event, identifier: string): Promise<AuthLoginResult> {
61
+ const kind = loginIdentifierKind(identifier);
62
+ const identifiers = await getShopSettings(event).then(s => s.signIn.identifiers, () => null);
63
+ if (!offeredLoginIdentifiers(identifiers).includes(kind)) {
64
+ throw createError({ statusCode: 403, data: { type: "identifier_not_offered" } });
65
+ }
66
+
67
+ const wanted = identifier.trim().toLowerCase();
68
+ const persona = await this.findPersona((p) => {
69
+ switch (kind) {
70
+ case "email": return p.email.toLowerCase() === wanted;
71
+ case "username": return p.username?.toLowerCase() === wanted;
72
+ case "customerNumber": return p.customerNumber === wanted;
73
+ }
74
+ });
56
75
  if (!persona) {
57
76
  throw createError({ statusCode: 401, data: { type: "user_invalid_credentials" } });
58
77
  }
@@ -0,0 +1,168 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { AuthRole, AuthUser } from "../../app/interfaces/auth";
4
+
5
+ /**
6
+ * Who the signed-in buyer of this request IS — as the customers app answered
7
+ * it, never as the browser claims it (RAD-155).
8
+ *
9
+ * The session cookie is plain JSON the browser can rewrite. It used to carry the
10
+ * contact and organization ids, and every live service read them straight back:
11
+ * a buyer who edited the cookie listed, invited into and ordered for any
12
+ * organization they could name. The cookie now only points at a platform session
13
+ * (user id + session id), and the identity behind it is resolved per request
14
+ * through `/customers/auth/me`, which refuses a session that is not that user's
15
+ * live one. What it answers is remembered on the event, here, and everything
16
+ * that needs a contact or an organization reads it from here.
17
+ *
18
+ * Why not a sealed cookie: a deployed Site is a brokered build serving any
19
+ * tenant with no per-site secret configured (the checkout token falls back to a
20
+ * constant there for exactly that reason), so a sealing key would either be a
21
+ * shared constant — forgeable — or fail closed and sign every buyer out. And
22
+ * auth/me is already on the request path of most account routes; resolving it
23
+ * once per request and reusing it costs little and also notices a block or a
24
+ * revoked session immediately, which a sealed cookie would not.
25
+ *
26
+ * The same answer is what the SDK client attributes the request to: the
27
+ * contact id lands in `X-Revenexx-Principal` (see useRevenexxSdk), and the
28
+ * customers app then holds the buyer to its self-service allowlist.
29
+ */
30
+
31
+ const BUYER_KEY = "coverVerifiedBuyer";
32
+ const PRINCIPAL_KEY = "revenexxPrincipal";
33
+
34
+ type BuyerContext = Record<string, unknown>;
35
+
36
+ function contextOf(event: H3Event | undefined): BuyerContext | null {
37
+ const context = (event as { context?: BuyerContext } | undefined)?.context;
38
+ return context && typeof context === "object" ? context : null;
39
+ }
40
+
41
+ /**
42
+ * Record what the identity service answered for this request. Only a verified
43
+ * answer comes through here; null records "signed out" so a second read in the
44
+ * same request does not ask again.
45
+ */
46
+ export function rememberVerifiedBuyer(event: H3Event, user: AuthUser | null): void {
47
+ const context = contextOf(event);
48
+ if (!context) {
49
+ return;
50
+ }
51
+ context[BUYER_KEY] = user;
52
+ if (user?.contactId) {
53
+ context[PRINCIPAL_KEY] = `contact:${user.contactId}`;
54
+ }
55
+ else {
56
+ delete context[PRINCIPAL_KEY];
57
+ }
58
+ }
59
+
60
+ /** Forget it again — after a sign-out within the same request. */
61
+ export function forgetVerifiedBuyer(event: H3Event): void {
62
+ const context = contextOf(event);
63
+ if (context) {
64
+ delete context[BUYER_KEY];
65
+ delete context[PRINCIPAL_KEY];
66
+ }
67
+ }
68
+
69
+ /**
70
+ * The verified buyer of this request: the user, null when signed out, or
71
+ * undefined when nothing resolved it yet. Synchronous on purpose — the
72
+ * buyer-principal middleware resolves it before any /api handler runs.
73
+ */
74
+ export function verifiedBuyer(event: H3Event | undefined): AuthUser | null | undefined {
75
+ const context = contextOf(event);
76
+ if (!context || !(BUYER_KEY in context)) {
77
+ return undefined;
78
+ }
79
+ return context[BUYER_KEY] as AuthUser | null;
80
+ }
81
+
82
+ /**
83
+ * The value for `X-Revenexx-Principal`, or "" when the request acts for no
84
+ * verified buyer. Never derived from anything the browser sent.
85
+ */
86
+ export function buyerPrincipal(event: H3Event | undefined): string {
87
+ const value = contextOf(event)?.[PRINCIPAL_KEY];
88
+ return typeof value === "string" ? value : "";
89
+ }
90
+
91
+ /**
92
+ * Least → most privileged, as the customers app orders its built-ins. A role
93
+ * the shop does not know ranks below all of them, so it can grant nothing.
94
+ */
95
+ const ROLE_RANK: Record<AuthRole, number> = {
96
+ requester: 0,
97
+ buyer: 1,
98
+ approver: 2,
99
+ admin: 3,
100
+ };
101
+
102
+ export function roleRank(role: string | undefined | null): number {
103
+ return role && role in ROLE_RANK ? ROLE_RANK[role as AuthRole] : -1;
104
+ }
105
+
106
+ /** May somebody holding `own` hand `target` to another person? */
107
+ export function mayGrantRole(own: string | undefined | null, target: string | undefined | null): boolean {
108
+ const ownRank = roleRank(own);
109
+ const targetRank = roleRank(target);
110
+ return ownRank >= 0 && targetRank >= 0 && targetRank <= ownRank;
111
+ }
112
+
113
+ /**
114
+ * Does the verified buyer hold this permission? `undefined` permissions mean
115
+ * the source never said (the demo personas): `whenUnstated` decides.
116
+ */
117
+ export function buyerHolds(user: AuthUser | null | undefined, permission: string, whenUnstated: boolean): boolean {
118
+ if (!user) {
119
+ return false;
120
+ }
121
+ if (!Array.isArray(user.permissions)) {
122
+ return whenUnstated;
123
+ }
124
+ return user.permissions.includes(permission);
125
+ }
126
+
127
+ /** The permission answer the customers app puts beside a contact on login, redeem and auth/me. */
128
+ export interface CustomersPermissionAnswer {
129
+ readonly role?: string | null;
130
+ readonly permissions?: readonly string[] | null;
131
+ readonly active?: boolean | null;
132
+ }
133
+
134
+ /**
135
+ * The grants and the may-act flag from a customers sign-in or auth/me answer.
136
+ *
137
+ * `active` lives on the permission answer: a contact row has no such column
138
+ * (it has `status`), so the shop used to read a field that was never there and
139
+ * every blocked buyer looked active. The contact's own `active` is still read
140
+ * as a fallback, in case an answer carries it.
141
+ *
142
+ * Permissions are always STATED for a live session — an empty list when the
143
+ * app answered none (no contact, or a role that grants nothing) — so a check
144
+ * against them can fail closed.
145
+ */
146
+ export function grantsFrom(
147
+ answer: CustomersPermissionAnswer | null | undefined,
148
+ contact?: { active?: boolean | null } | null,
149
+ ): { permissions: string[]; active?: boolean } {
150
+ const active = typeof answer?.active === "boolean"
151
+ ? answer.active
152
+ : typeof contact?.active === "boolean" ? contact.active : undefined;
153
+ return {
154
+ permissions: Array.isArray(answer?.permissions) ? answer.permissions.filter(p => typeof p === "string") : [],
155
+ ...(active === undefined ? {} : { active }),
156
+ };
157
+ }
158
+
159
+ /**
160
+ * Which requests resolve the buyer up front (server/middleware). Every BFF
161
+ * route does, except the sign-in routes: logging in, registering and asking for
162
+ * a mailed link act for nobody yet and must send no principal, and
163
+ * `/api/auth/me` resolves the buyer on its own.
164
+ */
165
+ export function needsVerifiedBuyer(path: string): boolean {
166
+ // `/api/_…` is module plumbing (icons and the like), not a buyer's request.
167
+ return path.startsWith("/api/") && !path.startsWith("/api/auth/") && !path.startsWith("/api/_");
168
+ }
@@ -0,0 +1,67 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { ICartManager } from "../interfaces/cart";
4
+
5
+ /**
6
+ * The cart an open punchout visit works in, or null outside one.
7
+ *
8
+ * The visit cookie is HTTP-only and written by the shop itself from the
9
+ * punchout app's claim, so the cart it names is the request's own for as long
10
+ * as the visit is open. A handed-back visit is over (RAD-109).
11
+ */
12
+ function openVisitCartId(event: H3Event): string | null {
13
+ const visit = readPunchoutVisit(event);
14
+ return visit && !visit.handedBack ? visit.cartId : null;
15
+ }
16
+
17
+ /**
18
+ * Refuse a cart the request does not own.
19
+ *
20
+ * The cart id of the multi-cart routes comes from the URL, and the carts app
21
+ * does not narrow a write to the acting buyer — so without this, anybody who
22
+ * learned a cart id could rename, empty into, activate or delete somebody else's
23
+ * cart (RAD-155). A cart is the request's own when it is among the carts listed
24
+ * for the verified contact, or for the guest session. Anybody else's answers
25
+ * exactly like one that does not exist.
26
+ *
27
+ * On an open punchout visit the visit's cart is owned by the visit's handle
28
+ * (pSid), not by the contact — so it is the request's own by the visit, without
29
+ * asking the contact's list, which would not contain it (RAD-109).
30
+ */
31
+ export async function assertOwnCart(event: H3Event, manager: ICartManager, id: string): Promise<void> {
32
+ const visitCart = openVisitCartId(event);
33
+ if (visitCart && id === visitCart) {
34
+ return;
35
+ }
36
+ let ids: string[];
37
+ try {
38
+ ids = (await manager.listCarts(event)).carts.map(cart => cart.id);
39
+ }
40
+ catch (err) {
41
+ getLogService().error("Service error: carts/ownership", toErrorContext(err));
42
+ throw createError({ statusCode: 502, message: "Cart service unavailable" });
43
+ }
44
+ if (!ids.includes(id)) {
45
+ throw createError({ statusCode: 404, message: "Cart not found" });
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Refuse to leave a punchout visit's cart (RAD-109).
51
+ *
52
+ * The hand-back sends the visit's cart and no other, so a visit that switched
53
+ * to another cart would fill one its procurement system never receives, and a
54
+ * visit that deleted its own would have nothing left to hand back. Both answer
55
+ * 409 `punchout_cart_fixed` — a refusal the shop can name, not a "not found"
56
+ * that would read as a broken cart. Outside a visit this does nothing.
57
+ */
58
+ export function assertPunchoutCartKept(event: H3Event, id: string, action: "activate" | "delete"): void {
59
+ const visitCart = openVisitCartId(event);
60
+ if (!visitCart) {
61
+ return;
62
+ }
63
+ const leaves = action === "activate" ? id !== visitCart : id === visitCart;
64
+ if (leaves) {
65
+ throw createError({ statusCode: 409, data: { type: "punchout_cart_fixed" } });
66
+ }
67
+ }
@@ -1,7 +1,9 @@
1
1
  import type { H3Event } from "h3";
2
+ import { RevenexxException } from "@revenexx/sdk";
2
3
  import type { Models } from "@revenexx/sdk";
3
4
 
4
5
  import type { OrderList, OrderListPosition } from "../../app/interfaces/account/order-lists";
6
+ import type { RevenexxSdk } from "./revenexxSdk";
5
7
 
6
8
  /**
7
9
  * Live order lists through the `orderlists` gateway app
@@ -16,6 +18,11 @@ import type { OrderList, OrderListPosition } from "../../app/interfaces/account/
16
18
  * returns the owner's own lists ∪ the organization's shared lists. We supply
17
19
  * both from the authenticated contact (auth/me). The cover OrderList keeps
18
20
  * `public` UI-side; it maps to the app's `shared`.
21
+ *
22
+ * Access: every call carries the contact as `X-Revenexx-Principal`
23
+ * (RAD-168). With it, orderlists (>= 1.0, RAD-134) answers 404 for another
24
+ * customer's private list — items included; without it the tenant key reads
25
+ * every list of the tenant. That 404 is passed on as cover's own.
19
26
  */
20
27
 
21
28
  interface AppItem {
@@ -56,6 +63,24 @@ async function actor(event: H3Event): Promise<{ contactId: string; name: string;
56
63
  return { contactId: user.contactId, name: user.name, organizationId: user.organizationId };
57
64
  }
58
65
 
66
+ /** The SDK acting as the signed-in contact. */
67
+ function sdkAs(me: { contactId: string }): RevenexxSdk {
68
+ return useRevenexxSdk({ principal: `contact:${me.contactId}` });
69
+ }
70
+
71
+ /** A list the principal may not see is one that does not exist. */
72
+ async function orNotFound<T>(run: () => Promise<T>): Promise<T> {
73
+ try {
74
+ return await run();
75
+ }
76
+ catch (err) {
77
+ if (err instanceof RevenexxException && err.code === 404) {
78
+ throw createError({ statusCode: 404, message: "List not found" });
79
+ }
80
+ throw err;
81
+ }
82
+ }
83
+
59
84
  function toCoverPosition(item: AppItem): OrderListPosition {
60
85
  return {
61
86
  // cover treats position.id as the PRODUCT id (membership flag on the
@@ -175,7 +200,7 @@ function toCoverList(row: AppList): OrderList {
175
200
  /** Own lists ∪ org-shared, each with its positions (bounded fan-out). */
176
201
  export async function listOrderLists(event: H3Event): Promise<OrderList[]> {
177
202
  const me = await actor(event);
178
- const sdk = useRevenexxSdk();
203
+ const sdk = sdkAs(me);
179
204
  // Typed list filter (orderlists.list declares owner_id/organization_id —
180
205
  // @revenexx/sdk >= 0.0.11). The fan-out to full lists is typed too.
181
206
  const { items } = await sdk.orderlists.orderlistsList({
@@ -187,8 +212,8 @@ export async function listOrderLists(event: H3Event): Promise<OrderList[]> {
187
212
  }
188
213
 
189
214
  export async function getOrderList(event: H3Event, id: string): Promise<OrderList> {
190
- await actor(event);
191
- const row = await useRevenexxSdk().orderlists.orderlistsGet({ id });
215
+ const me = await actor(event);
216
+ const row = await orNotFound(() => sdkAs(me).orderlists.orderlistsGet({ id }));
192
217
  return toCoverList(row as unknown as AppList);
193
218
  }
194
219
 
@@ -197,7 +222,7 @@ export async function createOrderList(
197
222
  body: { name: string; kind?: string; public?: boolean; positions?: OrderListPosition[] },
198
223
  ): Promise<OrderList> {
199
224
  const me = await actor(event);
200
- const row = await useRevenexxSdk().orderlists.orderlistsCreate({
225
+ const row = await sdkAs(me).orderlists.orderlistsCreate({
201
226
  name: body.name,
202
227
  ownerId: me.contactId,
203
228
  ownerName: me.name,
@@ -214,28 +239,30 @@ export async function updateOrderList(
214
239
  id: string,
215
240
  body: { name?: string; public?: boolean; positions?: OrderListPosition[]; appendPositions?: OrderListPosition[] },
216
241
  ): Promise<OrderList> {
217
- await actor(event);
218
- const sdk = useRevenexxSdk();
219
-
220
- if (typeof body.name === "string" && body.name.trim() || typeof body.public === "boolean") {
221
- await sdk.orderlists.orderlistsUpdate({
222
- id,
223
- ...(typeof body.name === "string" && body.name.trim() ? { name: body.name.trim() } : {}),
224
- ...(typeof body.public === "boolean" ? { shared: body.public } : {}),
225
- });
226
- }
242
+ const me = await actor(event);
243
+ const sdk = sdkAs(me);
227
244
 
228
- if (Array.isArray(body.positions)) {
229
- await sdk.orderlists.orderlistsItemsReplace({ listId: id, items: body.positions.map(toItemInput) });
230
- }
231
- for (const position of body.appendPositions ?? []) {
232
- await sdk.orderlists.orderlistsItemsCreate({ listId: id, ...toItemCreateParams(position) });
233
- }
245
+ return await orNotFound(async () => {
246
+ if (typeof body.name === "string" && body.name.trim() || typeof body.public === "boolean") {
247
+ await sdk.orderlists.orderlistsUpdate({
248
+ id,
249
+ ...(typeof body.name === "string" && body.name.trim() ? { name: body.name.trim() } : {}),
250
+ ...(typeof body.public === "boolean" ? { shared: body.public } : {}),
251
+ });
252
+ }
234
253
 
235
- return toCoverList(await sdk.orderlists.orderlistsGet({ id }) as unknown as AppList);
254
+ if (Array.isArray(body.positions)) {
255
+ await sdk.orderlists.orderlistsItemsReplace({ listId: id, items: body.positions.map(toItemInput) });
256
+ }
257
+ for (const position of body.appendPositions ?? []) {
258
+ await sdk.orderlists.orderlistsItemsCreate({ listId: id, ...toItemCreateParams(position) });
259
+ }
260
+
261
+ return toCoverList(await sdk.orderlists.orderlistsGet({ id }) as unknown as AppList);
262
+ });
236
263
  }
237
264
 
238
265
  export async function deleteOrderList(event: H3Event, id: string): Promise<void> {
239
- await actor(event);
240
- await useRevenexxSdk().orderlists.orderlistsDelete({ id });
266
+ const me = await actor(event);
267
+ await orNotFound(() => sdkAs(me).orderlists.orderlistsDelete({ id }));
241
268
  }