@revenexx/cover 0.10.1 → 0.11.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 (107) 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/dashboard/AccountDashboardKpis.vue +74 -34
  6. package/app/components/account/dashboard/AccountDashboardQuickActions.vue +24 -6
  7. package/app/components/account/organization/AccountOrganization.vue +3 -1
  8. package/app/components/account/team/AccountTeam.vue +32 -7
  9. package/app/components/auth/AuthForgotPasswordPanel.vue +9 -4
  10. package/app/components/auth/AuthLoginPanel.vue +5 -3
  11. package/app/components/cart/actions/CartSaveToListModal.vue +5 -0
  12. package/app/components/cart/item/CartItem.vue +17 -75
  13. package/app/components/cart/position/CartPosition.vue +17 -30
  14. package/app/components/cart/quote/CartQuoteRequestModal.vue +9 -1
  15. package/app/components/category/view/GridView.vue +10 -1
  16. package/app/components/category/view/ListView.vue +10 -1
  17. package/app/components/checkout/confirmation/CheckoutConfirmationActions.vue +2 -0
  18. package/app/components/checkout/onepage/CheckoutAddressSection.vue +4 -4
  19. package/app/components/checkout/onepage/CheckoutDeliverySection.vue +18 -2
  20. package/app/components/checkout/onepage/CheckoutGate.vue +2 -0
  21. package/app/components/checkout/onepage/CheckoutOnePageView.vue +1 -1
  22. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +10 -0
  23. package/app/components/checkout/onepage/CheckoutSummarySection.vue +7 -1
  24. package/app/components/layout/Region.vue +13 -0
  25. package/app/components/layout/footer/Footer.vue +8 -0
  26. package/app/components/layout/header/AppBar.vue +4 -3
  27. package/app/components/layout/header/MainNav.vue +3 -3
  28. package/app/components/listing/ListingResults.vue +3 -1
  29. package/app/components/product/card/Compact.vue +10 -1
  30. package/app/components/product/detail/ProductDetailAddToCart.vue +51 -18
  31. package/app/components/product/detail/ProductDetailIdentity.vue +1 -1
  32. package/app/components/product/detail/ProductDetailPriceRequest.vue +1 -1
  33. package/app/components/product/detail/ProductDetailSaveToList.vue +10 -0
  34. package/app/composables/useAccountDashboard.ts +0 -10
  35. package/app/composables/useAccountNavigation.ts +35 -0
  36. package/app/composables/useAuthStore.ts +2 -0
  37. package/app/composables/useCategoryListing.ts +6 -0
  38. package/app/composables/useCheckoutOnePage.ts +21 -2
  39. package/app/composables/useMasterDataEditable.ts +23 -0
  40. package/app/composables/useProductCard.ts +29 -2
  41. package/app/composables/useProductListing.ts +79 -0
  42. package/app/composables/useQuantityStepper.ts +90 -0
  43. package/app/composables/useQuickActions.ts +35 -0
  44. package/app/composables/useRoleGrants.ts +32 -0
  45. package/app/composables/useSearchListing.ts +4 -0
  46. package/app/composables/useThemeEvents.ts +144 -0
  47. package/app/config/accountDashboard.ts +26 -0
  48. package/app/config/quickActions.ts +40 -5
  49. package/app/interfaces/account/dashboard.ts +2 -0
  50. package/app/interfaces/auth.ts +13 -2
  51. package/app/interfaces/quantity-stepper.ts +17 -0
  52. package/app/layouts/default.vue +19 -10
  53. package/app/layouts/focus.vue +28 -7
  54. package/app/middleware/checkout-guard.ts +7 -1
  55. package/app/pages/punchout/transfer.vue +22 -0
  56. package/app/plugins/theme-events.client.ts +132 -0
  57. package/app/shared/themeEvents.ts +445 -0
  58. package/i18n/locales/de/account.json +7 -0
  59. package/i18n/locales/de/auth.json +1 -0
  60. package/i18n/locales/de/cart.json +2 -1
  61. package/i18n/locales/de/checkout.json +2 -1
  62. package/i18n/locales/de/common.json +2 -0
  63. package/i18n/locales/de/cover.json +44 -0
  64. package/i18n/locales/de/editor.json +47 -1
  65. package/i18n/locales/en/account.json +7 -0
  66. package/i18n/locales/en/auth.json +1 -0
  67. package/i18n/locales/en/cart.json +2 -1
  68. package/i18n/locales/en/checkout.json +2 -1
  69. package/i18n/locales/en/common.json +2 -0
  70. package/i18n/locales/en/cover.json +44 -0
  71. package/i18n/locales/en/editor.json +47 -1
  72. package/nuxt.config.ts +15 -1
  73. package/package.json +5 -2
  74. package/server/api/account/orders/[id]/cancel.post.ts +1 -1
  75. package/server/api/account/orders/[id]/messages.get.ts +1 -1
  76. package/server/api/account/orders/[id]/messages.post.ts +1 -1
  77. package/server/api/account/orders/[id]/return.post.ts +1 -0
  78. package/server/api/account/orders/[id].get.ts +1 -1
  79. package/server/api/account/pending-approvals/index.get.ts +1 -0
  80. package/server/api/account/profile.get.ts +3 -1
  81. package/server/api/auth/login.post.ts +6 -0
  82. package/server/api/auth/magic-link.put.ts +6 -1
  83. package/server/api/auth/otp.put.ts +6 -1
  84. package/server/api/carts/[id]/activate.post.ts +1 -0
  85. package/server/api/carts/[id]/index.delete.ts +1 -0
  86. package/server/api/carts/[id]/index.put.ts +1 -0
  87. package/server/api/carts/[id]/items.post.ts +1 -0
  88. package/server/api/orders/index.post.ts +33 -0
  89. package/server/api/quick-actions.get.ts +6 -38
  90. package/server/middleware/buyer-principal.ts +18 -0
  91. package/server/routes/punchout/start.get.ts +2 -2
  92. package/server/services/ApiAddressBookService.ts +43 -1
  93. package/server/services/ApiAuthService.ts +98 -17
  94. package/server/services/ApiCartService.ts +3 -10
  95. package/server/services/ApiOrganizationService.ts +7 -2
  96. package/server/services/ApiTeamService.ts +93 -21
  97. package/server/utils/buyerIdentity.ts +168 -0
  98. package/server/utils/cartOwnership.ts +27 -0
  99. package/server/utils/liveOrderLists.ts +50 -23
  100. package/server/utils/liveOrders.ts +39 -24
  101. package/server/utils/livePrices.ts +7 -15
  102. package/server/utils/masterData.ts +29 -0
  103. package/server/utils/passwordlessSignIn.ts +13 -4
  104. package/server/utils/pendingApprovals.ts +29 -7
  105. package/server/utils/procurementCheckout.ts +2 -0
  106. package/server/utils/quickActionCatalogue.ts +53 -0
  107. package/server/utils/revenexxSdk.ts +116 -2
@@ -2,6 +2,8 @@ import type { H3Event } from "h3";
2
2
 
3
3
  import type { AuthRole, AuthUser, StoredSession } from "../../app/interfaces/auth";
4
4
  import type { AuthLoginResult, IAuthService } from "../interfaces/auth";
5
+ import type { CustomersPermissionAnswer } from "../utils/buyerIdentity";
6
+ import { forgetVerifiedBuyer, grantsFrom, rememberVerifiedBuyer } from "../utils/buyerIdentity";
5
7
 
6
8
  /** Session payload of the customers app's auth passthrough. */
7
9
  interface ApiSession {
@@ -20,13 +22,49 @@ interface ApiContact {
20
22
  role?: string | null;
21
23
  organization_id?: string | null;
22
24
  /**
23
- * False for a contact that is blocked, pending or rejected. The customers app
24
- * answers it on every read and shapes the permission set to match; the shop
25
- * carries it through so a surface can say why rather than showing a wall.
25
+ * Legacy: a contact row carries `status`, not `active` — the may-act flag is
26
+ * on the permission answer beside it (see grantsFrom). Read as a fallback.
26
27
  */
27
28
  active?: boolean | null;
28
29
  }
29
30
 
31
+ /** What auth/me answers. */
32
+ interface ApiMeAnswer {
33
+ user: { $id: string; name?: string; email: string };
34
+ contact: ApiContact | null;
35
+ permissions?: CustomersPermissionAnswer | null;
36
+ }
37
+
38
+ /** The verified identity of one request, resolved at most once per request. */
39
+ const ME_KEY = "coverApiAuthMe";
40
+
41
+ /**
42
+ * A short cross-request memory of verified answers, keyed by tenant + user +
43
+ * session. A signed-in page fans out into a handful of BFF calls, and each of
44
+ * them now needs the verified buyer; without this every one of them would
45
+ * ask auth/me again within the same second. Only answers the identity service
46
+ * GAVE are kept, so a key a browser forges finds nothing it did not already
47
+ * prove — and a block or a revoked session is seen within the TTL.
48
+ */
49
+ const VERIFIED_TTL_MS = 10_000;
50
+ const VERIFIED_MAX = 1000;
51
+ const verified = new Map<string, { user: AuthUser; until: number }>();
52
+
53
+ function rememberAcrossRequests(key: string, user: AuthUser): void {
54
+ if (verified.size >= VERIFIED_MAX) {
55
+ const oldest = verified.keys().next().value;
56
+ if (oldest !== undefined) {
57
+ verified.delete(oldest);
58
+ }
59
+ }
60
+ verified.set(key, { user, until: Date.now() + VERIFIED_TTL_MS });
61
+ }
62
+
63
+ /** Test seam: forget every remembered answer. */
64
+ export function clearVerifiedSessions(): void {
65
+ verified.clear();
66
+ }
67
+
30
68
  const KNOWN_ROLES = new Set<AuthRole>(["buyer", "approver", "admin", "requester"]);
31
69
 
32
70
  function toAuthRole(role?: string | null): AuthRole | undefined {
@@ -50,17 +88,18 @@ function contactName(contact: ApiContact | null, fallback: string): string {
50
88
  */
51
89
  export class ApiAuthService implements IAuthService {
52
90
  async login(event: H3Event, email: string, password: string): Promise<AuthLoginResult> {
53
- const { session, contact } = await useRevenexxSdk().customers.customersAuthLogin({ email, password }) as unknown as {
91
+ const { session, contact, permissions } = await useRevenexxSdk().customers.customersAuthLogin({ email, password }) as unknown as {
54
92
  session: ApiSession;
55
93
  contact: ApiContact | null;
94
+ permissions?: CustomersPermissionAnswer | null;
56
95
  };
57
96
 
97
+ // The cookie points at the platform session and nothing else: the
98
+ // contact and organization are re-resolved per request (RAD-155).
58
99
  const storedSession: StoredSession = {
59
100
  id: session.$id,
60
101
  expire: session.expire,
61
102
  userId: session.userId,
62
- ...(contact?.id ? { contactId: contact.id } : {}),
63
- ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
64
103
  };
65
104
  setCookie(event, SESSION_COOKIE_NAME, JSON.stringify(storedSession), sessionCookieOptions(session.expire));
66
105
 
@@ -70,13 +109,35 @@ export class ApiAuthService implements IAuthService {
70
109
  name: contactName(contact, email),
71
110
  email: contact?.email ?? email,
72
111
  role: toAuthRole(contact?.role),
112
+ ...(contact?.id ? { contactId: contact.id } : {}),
113
+ ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
114
+ ...grantsFrom(permissions, contact),
73
115
  },
74
116
  session: { id: session.$id, expire: session.expire },
75
117
  ...(contact?.id ? { contactId: contact.id } : {}),
76
118
  };
77
119
  }
78
120
 
121
+ /**
122
+ * The verified buyer of this request. Resolved at most once per request and
123
+ * remembered on the event (rememberVerifiedBuyer), which is also what puts
124
+ * the contact on every later SDK call as its principal.
125
+ */
79
126
  async me(event: H3Event): Promise<AuthUser | null> {
127
+ const context = event.context as Record<string, unknown>;
128
+ const pending = context[ME_KEY] as Promise<AuthUser | null> | undefined;
129
+ if (pending) {
130
+ return pending;
131
+ }
132
+ const resolving = this.resolve(event).then((user) => {
133
+ rememberVerifiedBuyer(event, user);
134
+ return user;
135
+ });
136
+ context[ME_KEY] = resolving;
137
+ return resolving;
138
+ }
139
+
140
+ private async resolve(event: H3Event): Promise<AuthUser | null> {
80
141
  const raw = getCookie(event, SESSION_COOKIE_NAME);
81
142
  if (!raw) {
82
143
  return null;
@@ -92,11 +153,21 @@ export class ApiAuthService implements IAuthService {
92
153
  return null;
93
154
  }
94
155
 
95
- if (!parsed.userId) {
156
+ // Both halves are required: auth/me is asked whether THIS session is
157
+ // that user's live one, which is what makes the answer proof rather
158
+ // than an echo of whatever user id the browser wrote.
159
+ if (!parsed || typeof parsed.userId !== "string" || !parsed.userId || typeof parsed.id !== "string" || !parsed.id) {
96
160
  deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
97
161
  return null;
98
162
  }
99
163
 
164
+ const cacheKey = `${revenexxTenantKey()}\u0000${parsed.userId}\u0000${parsed.id}`;
165
+ const remembered = verified.get(cacheKey);
166
+ if (remembered && remembered.until > Date.now()) {
167
+ return remembered.user;
168
+ }
169
+ verified.delete(cacheKey);
170
+
100
171
  // Validate the session against the customers app, retrying transient
101
172
  // failures. A 401 is the only proof the session is gone (revoked/expired)
102
173
  // → clear the cookie + log out. Anything else (5xx "capability dispatch
@@ -113,27 +184,34 @@ export class ApiAuthService implements IAuthService {
113
184
  // alive — a logged-out/revoked session answers 401 here. Raw call:
114
185
  // the AuthMeRequest contract does not declare session_id yet, so
115
186
  // the generated customersAuthMe() would drop the session check.
116
- const { user, contact } = await useRevenexxSdk().call<{
117
- user: { $id: string; name?: string; email: string };
118
- contact: ApiContact | null;
119
- }>("POST", "/v1/customers/auth/me", { body: { user_id: parsed.userId, session_id: parsed.id } });
187
+ const { user, contact, permissions } = await useRevenexxSdk().call<ApiMeAnswer>(
188
+ "POST",
189
+ "/v1/customers/auth/me",
190
+ { body: { user_id: parsed.userId, session_id: parsed.id } },
191
+ );
120
192
 
121
- return {
193
+ const resolved: AuthUser = {
122
194
  $id: user.$id,
123
195
  name: contactName(contact, user.name ?? user.email),
124
196
  email: user.email,
125
197
  role: toAuthRole(contact?.role),
126
198
  ...(contact?.id ? { contactId: contact.id } : {}),
127
199
  ...(contact?.organization_id ? { organizationId: contact.organization_id } : {}),
128
- // Only when the app actually said: undefined means nobody asked,
129
- // and reading that as blocked would lock out every session whose
130
- // cookie predates this.
131
- ...(typeof contact?.active === "boolean" ? { active: contact.active } : {}),
200
+ // `active` only when the app actually said: undefined means
201
+ // nobody asked, and reading that as blocked would lock out
202
+ // every session whose cookie predates this.
203
+ ...grantsFrom(permissions, contact),
132
204
  };
205
+ rememberAcrossRequests(cacheKey, resolved);
206
+ return resolved;
133
207
  }
134
208
  catch (err) {
135
209
  lastErr = err;
136
- if (isApiUserError(err) && err.code === 401) {
210
+ // 401: the session is gone. A blocked contact or organization
211
+ // refused outright (customers >= 1.1.0) is signed out as well.
212
+ // Any other 403 is this shop's credentials, not the buyer's
213
+ // session, and must not sign everybody out.
214
+ if (err instanceof RevenexxException && (err.code === 401 || signInRefusalType(err) !== null)) {
137
215
  deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
138
216
  return null;
139
217
  }
@@ -152,6 +230,7 @@ export class ApiAuthService implements IAuthService {
152
230
  try {
153
231
  const parsed = JSON.parse(raw) as StoredSession;
154
232
  if (parsed.userId && parsed.id) {
233
+ verified.delete(`${revenexxTenantKey()}\u0000${parsed.userId}\u0000${parsed.id}`);
155
234
  await useRevenexxSdk().customers.customersAuthLogout({
156
235
  userId: parsed.userId,
157
236
  sessionId: parsed.id,
@@ -164,5 +243,7 @@ export class ApiAuthService implements IAuthService {
164
243
  }
165
244
  }
166
245
  deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
246
+ forgetVerifiedBuyer(event);
247
+ delete (event.context as Record<string, unknown>)[ME_KEY];
167
248
  }
168
249
  }
@@ -3,7 +3,6 @@ import type { Models } from "@revenexx/sdk";
3
3
  import type { H3Event } from "h3";
4
4
 
5
5
  import type { CartItem } from "../../app/interfaces/cart-item";
6
- import type { StoredSession } from "../../app/interfaces/auth";
7
6
  import type { CartSummaryRow, ICartManager, ICartService } from "../interfaces/cart";
8
7
 
9
8
  /** Cart row of the carts app. */
@@ -47,15 +46,9 @@ const DEFAULT_CART_NAME = "Mein Warenkorb";
47
46
 
48
47
  /** The request's cart owner: the logged-in contact, else the guest session. */
49
48
  function resolveOwner(event: H3Event): CartOwner {
50
- let contactId: string | null = null;
51
- const raw = getCookie(event, SESSION_COOKIE_NAME);
52
- if (raw) {
53
- try {
54
- const parsed = JSON.parse(raw) as StoredSession;
55
- contactId = parsed.contactId ?? null;
56
- }
57
- catch { /* guest */ }
58
- }
49
+ // The VERIFIED contact (RAD-155) — a contact id read from the cookie would
50
+ // open any buyer's cart to whoever wrote it there.
51
+ const contactId = sessionOrderRefs(event).contact_id ?? null;
59
52
  return { contactId, sessionKey: getOrCreateCartSessionId(event) };
60
53
  }
61
54
 
@@ -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
  }
@@ -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,27 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { ICartManager } from "../interfaces/cart";
4
+
5
+ /**
6
+ * Refuse a cart the request does not own.
7
+ *
8
+ * The cart id of the multi-cart routes comes from the URL, and the carts app
9
+ * does not narrow a write to the acting buyer — so without this, anybody who
10
+ * learned a cart id could rename, empty into, activate or delete somebody else's
11
+ * cart (RAD-155). A cart is the request's own when it is among the carts listed
12
+ * for the verified contact, or for the guest session. Anybody else's answers
13
+ * exactly like one that does not exist.
14
+ */
15
+ export async function assertOwnCart(event: H3Event, manager: ICartManager, id: string): Promise<void> {
16
+ let ids: string[];
17
+ try {
18
+ ids = (await manager.listCarts(event)).carts.map(cart => cart.id);
19
+ }
20
+ catch (err) {
21
+ getLogService().error("Service error: carts/ownership", toErrorContext(err));
22
+ throw createError({ statusCode: 502, message: "Cart service unavailable" });
23
+ }
24
+ if (!ids.includes(id)) {
25
+ throw createError({ statusCode: 404, message: "Cart not found" });
26
+ }
27
+ }