Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix: served invitation acceptance links only to callers who could send the invitation

Damian Legawiece601826eb3cc
diff --git a/.changeset/invitation-acceptance-link-endpoint.md b/.changeset/invitation-acceptance-link-endpoint.md
new file mode 100644
index 0000000000..c77b5f1939
--- /dev/null
+++ b/.changeset/invitation-acceptance-link-endpoint.md
@@ -0,0 +1,8 @@
+---
+"@spree/admin-sdk": minor
+"@spree/seller-sdk": minor
+"@spree/dashboard": patch
+"@spree/seller-dashboard": patch
+---
+
+Invitation listings no longer include `acceptance_url`, because the link carries the token that accepts the invitation. Fetch it on demand with `invitations.acceptanceLink(id)` (and `sellers.invitations.acceptanceLink(sellerId, id)` in the Admin SDK), which needs write access. The "Copy invitation link" actions in the dashboard and the seller panel now use it.
diff --git a/packages/admin-sdk/examples/invitations/acceptance-link.ts b/packages/admin-sdk/examples/invitations/acceptance-link.ts
new file mode 100644
index 0000000000..013f75df3c
--- /dev/null
+++ b/packages/admin-sdk/examples/invitations/acceptance-link.ts
@@ -0,0 +1,13 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { acceptance_url } = await client.invitations.acceptanceLink('inv_xxx')
+
+// endregion:example
+
+export { acceptance_url }
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 1b0f05827a..cb48531f0b 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -439,6 +439,7 @@ import type {
ImportRow,
Integration,
Invitation,
+ InvitationAcceptanceLink,
LineItem,
Locale,
Market,
@@ -3146,6 +3147,18 @@ export class AdminClient {
/** Sends the email again; refused once the offer has lapsed. */
resend: (sellerId: string, id: string, options?: RequestOptions): Promise<Invitation> =>
this.request<Invitation>('PATCH', `/sellers/${sellerId}/invitations/${id}/resend`, options),
+
+ /** The link that joins the seller's team; needs write access to sellers. */
+ acceptanceLink: (
+ sellerId: string,
+ id: string,
+ options?: RequestOptions,
+ ): Promise<InvitationAcceptanceLink> =>
+ this.request<InvitationAcceptanceLink>(
+ 'GET',
+ `/sellers/${sellerId}/invitations/${id}/acceptance_link`,
+ options,
+ ),
},
/** What this seller submitted about the requirements, and its decisions. */
@@ -5628,6 +5641,13 @@ export class AdminClient {
/** Issues a fresh token + email for a pending invitation. */
resend: (id: string, options?: RequestOptions): Promise<Invitation> =>
this.request<Invitation>('PATCH', `/invitations/${id}/resend`, options),
+
+ /**
+ * The acceptance link of a pending invitation. It carries the token, so it
+ * needs write access to staff and the right to grant the invitation's role.
+ */
+ acceptanceLink: (id: string, options?: RequestOptions): Promise<InvitationAcceptanceLink> =>
+ this.request<InvitationAcceptanceLink>('GET', `/invitations/${id}/acceptance_link`, options),
}
// ============================================
diff --git a/packages/admin-sdk/src/types/generated/Invitation.ts b/packages/admin-sdk/src/types/generated/Invitation.ts
index 799b5d571d..f7aeca6979 100644
--- a/packages/admin-sdk/src/types/generated/Invitation.ts
+++ b/packages/admin-sdk/src/types/generated/Invitation.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 28c09e1f380a6a5124b501f5e9dc059b
+// Typelizer digest 73489f6cdb59f0e72c3ec0ad9df13200
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {InvitationStatus} from '@/types'
@@ -13,7 +13,6 @@ interface Invitation {
role_id: string;
role_name: string;
inviter_email: string;
- acceptance_url: string;
invitee_exists: boolean;
store: { id: string; name: string };
}
diff --git a/packages/admin-sdk/src/types/generated/InvitationAcceptanceLink.ts b/packages/admin-sdk/src/types/generated/InvitationAcceptanceLink.ts
new file mode 100644
index 0000000000..766b61c281
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/InvitationAcceptanceLink.ts
@@ -0,0 +1,10 @@
+// Typelizer digest f5f197c5c870caa68e76d88979afefab
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface InvitationAcceptanceLink {
+ id: string;
+ acceptance_url: string;
+}
+
+export default InvitationAcceptanceLink;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index 396659ec98..d64df8b238 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest b0e3f0651bf80f111023efb0419d8ff5
+// Typelizer digest dbf8184dcaf961005dfb4c99d6e609aa
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { ActorKind, ClaimStatus, DataRequestStatus, ExchangeStatus, FeeKind, FulfillmentItemStatus, FulfillmentStatus, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, PaymentStatus, PriceListStatus, ProductStatus, ProductSubmissionStatus, ReturnStatus, SellerPayoutStatus, SellerRequirementSubmissionStatus, SellerStatus, SellerTransferStatus, ShippingLabelStatus, StockLocationKind, TaxExemptionCertificateStatus } from './Enums'
@@ -66,6 +66,7 @@ export type { default as ImportMapping } from './ImportMapping'
export type { default as ImportRow } from './ImportRow'
export type { default as Import } from './Import'
export type { default as Integration } from './Integration'
+export type { default as InvitationAcceptanceLink } from './InvitationAcceptanceLink'
export type { default as Invitation } from './Invitation'
export type { default as LineItem } from './LineItem'
export type { default as Market } from './Market'
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index bb8f38d1d7..01fd70c4cf 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -77,6 +77,7 @@ export type { default as ImportMapping } from './generated/ImportMapping'
export type { default as ImportRow } from './generated/ImportRow'
export type { default as Integration } from './generated/Integration'
export type { default as Invitation } from './generated/Invitation'
+export type { default as InvitationAcceptanceLink } from './generated/InvitationAcceptanceLink'
export type { default as LineItem } from './generated/LineItem'
export type { default as Market } from './generated/Market'
export type { default as Media } from './generated/Media'
diff --git a/packages/dashboard/e2e/helpers.ts b/packages/dashboard/e2e/helpers.ts
index aa2903e7b2..5cf450b30f 100644
--- a/packages/dashboard/e2e/helpers.ts
+++ b/packages/dashboard/e2e/helpers.ts
@@ -407,3 +407,28 @@ export async function createInTransitTransfer(
return transfer
}
+
+/**
+ * The path an invitee opens to accept an invitation. The link carries the
+ * invitation's token, so the listing never includes it; this fetches it the way
+ * the "copy link" action does. `invitationPath` is the invitation's API path,
+ * e.g. `/api/v3/admin/invitations/inv_x` or `/api/v3/admin/sellers/seller_x/invitations/inv_x`.
+ */
+export async function invitationAcceptancePath(
+ page: Page,
+ session: E2ELoginSession,
+ invitationPath: string,
+): Promise<string> {
+ const res = await page.request.get(`${invitationPath}/acceptance_link`, {
+ headers: {
+ 'X-Spree-Store-Id': session.store_id,
+ Authorization: `Bearer ${session.accessToken}`,
+ },
+ })
+ if (!res.ok()) {
+ throw new Error(`Acceptance link request failed with ${res.status()}: ${await res.text()}`)
+ }
+ const { acceptance_url } = (await res.json()) as { acceptance_url: string }
+ // Tolerate either path-only (no app origin configured) or an absolute URL.
+ return acceptance_url.replace(/^https?:\/\/[^/]+/, '')
+}
diff --git a/packages/dashboard/e2e/invitation-acceptance.spec.ts b/packages/dashboard/e2e/invitation-acceptance.spec.ts
index b9802eb382..c4b9b72b8a 100644
--- a/packages/dashboard/e2e/invitation-acceptance.spec.ts
+++ b/packages/dashboard/e2e/invitation-acceptance.spec.ts
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test'
-import { login } from './helpers'
+import { invitationAcceptancePath, login } from './helpers'
test.describe('invitation lifecycle', () => {
test('admin invites a teammate and the invitee signs up via the link', async ({
@@ -19,9 +19,9 @@ test.describe('invitation lifecycle', () => {
await page.getByLabel(/role/i).click()
await page.getByRole('option').first().click()
- // API wait justified per CLAUDE.md: `acceptance_url` is normally
- // emailed, not surfaced in the admin UI, so there's no DOM signal to
- // pull the link from.
+ // API wait justified per CLAUDE.md: the acceptance link is normally
+ // emailed, and the copy action puts it on the clipboard, so there's no DOM
+ // signal to pull it from.
const [createResponse] = await Promise.all([
page.waitForResponse(
(res) =>
@@ -32,10 +32,13 @@ test.describe('invitation lifecycle', () => {
),
page.getByRole('button', { name: /send invitation/i }).click(),
])
- const invitation = (await createResponse.json()) as { acceptance_url: string }
- expect(invitation.acceptance_url).toMatch(/\/accept-invitation\//)
- // Tolerate either path-only (test env, admin_url unset) or absolute URL.
- const acceptancePath = invitation.acceptance_url.replace(/^https?:\/\/[^/]+/, '')
+ const invitation = (await createResponse.json()) as { id: string }
+ const acceptancePath = await invitationAcceptancePath(
+ page,
+ creds,
+ `/api/v3/admin/invitations/${invitation.id}`,
+ )
+ expect(acceptancePath).toMatch(/\/accept-invitation\//)
await page.getByRole('button', { name: /user menu/i }).click()
await page.getByRole('menuitem', { name: /log out/i }).click()
diff --git a/packages/dashboard/e2e/seller-catalog.spec.ts b/packages/dashboard/e2e/seller-catalog.spec.ts
index 0c2908dde7..702d3abd38 100644
--- a/packages/dashboard/e2e/seller-catalog.spec.ts
+++ b/packages/dashboard/e2e/seller-catalog.spec.ts
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test'
-import { login } from './helpers'
+import { invitationAcceptancePath, login } from './helpers'
// The seller panel is its own app on its own origin (see playwright.config.ts).
const SELLER_PANEL = `http://localhost:${process.env.E2E_SELLER_VITE_PORT || '5175'}`
@@ -39,8 +39,12 @@ async function signInAsNewSeller(
),
page.getByRole('button', { name: /send invitation/i }).click(),
])
- const { data } = (await listResponse.json()) as { data: Array<{ acceptance_url: string }> }
- const acceptancePath = data[0].acceptance_url.replace(/^https?:\/\/[^/]+/, '')
+ const { data } = (await listResponse.json()) as { data: Array<{ id: string }> }
+ const acceptancePath = await invitationAcceptancePath(
+ page,
+ creds,
+ `${new URL(listResponse.url()).pathname}/${data[0].id}`,
+ )
const context = await browser.newContext()
const sellerPage = await context.newPage()
diff --git a/packages/dashboard/e2e/seller-delivery-methods.spec.ts b/packages/dashboard/e2e/seller-delivery-methods.spec.ts
index 4506082ca5..ccdcbe4e25 100644
--- a/packages/dashboard/e2e/seller-delivery-methods.spec.ts
+++ b/packages/dashboard/e2e/seller-delivery-methods.spec.ts
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test'
-import { login } from './helpers'
+import { invitationAcceptancePath, login } from './helpers'
// The seller panel is its own app on its own origin (see playwright.config.ts).
const SELLER_PANEL = `http://localhost:${process.env.E2E_SELLER_VITE_PORT || '5175'}`
@@ -39,8 +39,12 @@ async function signInAsNewSeller(
),
page.getByRole('button', { name: /send invitation/i }).click(),
])
- const { data } = (await listResponse.json()) as { data: Array<{ acceptance_url: string }> }
- const acceptancePath = data[0].acceptance_url.replace(/^https?:\/\/[^/]+/, '')
+ const { data } = (await listResponse.json()) as { data: Array<{ id: string }> }
+ const acceptancePath = await invitationAcceptancePath(
+ page,
+ creds,
+ `${new URL(listResponse.url()).pathname}/${data[0].id}`,
+ )
const context = await browser.newContext()
const sellerPage = await context.newPage()
diff --git a/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts b/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts
index bf723a3f2a..233e723fa0 100644
--- a/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts
+++ b/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test'
-import { login } from './helpers'
+import { invitationAcceptancePath, login } from './helpers'
// The seller panel is its own app on its own origin (see playwright.config.ts),
// so this spec drives two: the operator's dashboard through `baseURL`, and the
@@ -26,10 +26,9 @@ test.describe('seller invitation lifecycle', () => {
await page.locator('#invite-email').fill(inviteeEmail)
// API wait justified per CLAUDE.md: the acceptance link is emailed rather
- // than shown, so no DOM signal carries it. Read off the team card's own
- // refetch, which the SPA makes with its access token — a bare
- // `page.request` call carries no session, since the token is held in
- // memory rather than in a cookie.
+ // than shown, so no DOM signal carries it. The new invitation's id comes
+ // off the team card's own refetch; its link is then fetched with the
+ // login's access token.
const [listResponse] = await Promise.all([
page.waitForResponse(
(res) =>
@@ -44,8 +43,12 @@ test.describe('seller invitation lifecycle', () => {
// The invitation appears on the seller's team card once it is sent.
await expect(page.getByText(inviteeEmail)).toBeVisible({ timeout: 15_000 })
- const { data } = (await listResponse.json()) as { data: Array<{ acceptance_url: string }> }
- const acceptancePath = data[0].acceptance_url.replace(/^https?:\/\/[^/]+/, '')
+ const { data } = (await listResponse.json()) as { data: Array<{ id: string }> }
+ const acceptancePath = await invitationAcceptancePath(
+ page,
+ creds,
+ `${new URL(listResponse.url()).pathname}/${data[0].id}`,
+ )
expect(acceptancePath).toMatch(/\/accept-invitation\//)
// A fresh context so the operator's refresh cookie never reaches the panel.
diff --git a/packages/dashboard/e2e/seller-package-types.spec.ts b/packages/dashboard/e2e/seller-package-types.spec.ts
index 472a5c9767..c16a33df7b 100644
--- a/packages/dashboard/e2e/seller-package-types.spec.ts
+++ b/packages/dashboard/e2e/seller-package-types.spec.ts
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test'
-import { login } from './helpers'
+import { invitationAcceptancePath, login } from './helpers'
// The seller panel is its own app on its own origin (see playwright.config.ts).
const SELLER_PANEL = `http://localhost:${process.env.E2E_SELLER_VITE_PORT || '5175'}`
@@ -39,8 +39,12 @@ async function signInAsNewSeller(
),
page.getByRole('button', { name: /send invitation/i }).click(),
])
- const { data } = (await listResponse.json()) as { data: Array<{ acceptance_url: string }> }
- const acceptancePath = data[0].acceptance_url.replace(/^https?:\/\/[^/]+/, '')
+ const { data } = (await listResponse.json()) as { data: Array<{ id: string }> }
+ const acceptancePath = await invitationAcceptancePath(
+ page,
+ creds,
+ `${new URL(listResponse.url()).pathname}/${data[0].id}`,
+ )
const context = await browser.newContext()
const sellerPage = await context.newPage()
diff --git a/packages/dashboard/src/hooks/use-staff.ts b/packages/dashboard/src/hooks/use-staff.ts
index 9098726501..6571ccc832 100644
--- a/packages/dashboard/src/hooks/use-staff.ts
+++ b/packages/dashboard/src/hooks/use-staff.ts
@@ -1,6 +1,6 @@
import type { AdminUserUpdateParams, InvitationCreateParams } from '@spree/admin-sdk'
import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'
-import { useQuery } from '@tanstack/react-query'
+import { useMutation, useQuery } from '@tanstack/react-query'
export function useStaff() {
return useQuery({
@@ -75,3 +75,13 @@ export function useDeleteInvitation() {
errorMessage: false,
})
}
+
+/**
+ * Fetches an invitation's acceptance link on demand. The link carries the
+ * token, so the invitation listing never includes it.
+ */
+export function useInvitationAcceptanceLink() {
+ return useMutation({
+ mutationFn: (id: string) => adminClient.invitations.acceptanceLink(id),
+ })
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 7abb612867..f561fd6198 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -5141,7 +5141,8 @@
"errors": {
"failed_to_remove": "فشل في إزالة الموظفين",
"failed_to_resend": "فشلت إعادة إرسال الدعوة",
- "failed_to_revoke": "فشل في إلغاء الدعوة"
+ "failed_to_revoke": "فشل في إلغاء الدعوة",
+ "failed_to_copy_link": "تعذّر نسخ رابط الدعوة"
},
"invite": {
"email_placeholder": "[email protected]",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 50519882e4..ad1ff80929 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -5108,7 +5108,8 @@
"errors": {
"failed_to_remove": "Mitarbeiter konnte nicht entfernt werden",
"failed_to_resend": "Einladung konnte nicht erneut gesendet werden",
- "failed_to_revoke": "Einladung konnte nicht zurückgezogen werden"
+ "failed_to_revoke": "Einladung konnte nicht zurückgezogen werden",
+ "failed_to_copy_link": "Einladungslink konnte nicht kopiert werden"
},
"invite": {
"email_placeholder": "[email protected]",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index d7e7da5414..ab07892fe3 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -5108,7 +5108,8 @@
"errors": {
"failed_to_remove": "Failed to remove staff",
"failed_to_resend": "Failed to resend invitation",
- "failed_to_revoke": "Failed to revoke invitation"
+ "failed_to_revoke": "Failed to revoke invitation",
+ "failed_to_copy_link": "Failed to copy invitation link"
},
"invite": {
"email_placeholder": "[email protected]",
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index 889041f2c2..2be20e009f 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -5535,7 +5535,8 @@
"errors": {
"failed_to_remove": "No se pudo quitar al staff",
"failed_to_resend": "No se pudo reenviar la invitación",
- "failed_to_revoke": "No se pudo revocar la invitación"
+ "failed_to_revoke": "No se pudo revocar la invitación",
+ "failed_to_copy_link": "No se pudo copiar el enlace de invitación"
},
"invite": {
"email_placeholder": "compañ[email protected]",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 36c1282959..67ee6c8c3f 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -5108,7 +5108,8 @@
"errors": {
"failed_to_remove": "Échec du retrait du membre du personnel",
"failed_to_resend": "Échec du renvoi de l'invitation",
- "failed_to_revoke": "Échec de la révocation de l'invitation"
+ "failed_to_revoke": "Échec de la révocation de l'invitation",
+ "failed_to_copy_link": "Impossible de copier le lien d'invitation"
},
"invite": {
"email_placeholder": "[email protected]",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index ec0b10a972..a0a1a6a3cb 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -5172,7 +5172,8 @@
"errors": {
"failed_to_remove": "Nie udało się usunąć personelu",
"failed_to_resend": "Nie udało się ponownie wysłać zaproszenia",
- "failed_to_revoke": "Nie udało się cofnąć zaproszenia"
+ "failed_to_revoke": "Nie udało się cofnąć zaproszenia",
+ "failed_to_copy_link": "Nie udało się skopiować linku zaproszenia"
},
"invite": {
"email_placeholder": "[email protected]",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 164cf8aa89..0dd0ced616 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -5097,7 +5097,8 @@
"errors": {
"failed_to_remove": "移除员工失败",
"failed_to_resend": "重新发送邀请失败",
- "failed_to_revoke": "撤销邀请失败"
+ "failed_to_revoke": "撤销邀请失败",
+ "failed_to_copy_link": "复制邀请链接失败"
},
"invite": {
"email_placeholder": "[email protected]",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/staff.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/staff.tsx
index 98354fbebc..878ccda4e7 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/staff.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/staff.tsx
@@ -1,6 +1,12 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { type AdminUser, type Invitation, type Role, SpreeError } from '@spree/admin-sdk'
-import { getInitials, mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'
+import {
+ getInitials,
+ mapSpreeErrorsToForm,
+ PageHeader,
+ Subject,
+ usePermissions,
+} from '@spree/dashboard-core'
import {
Avatar,
AvatarFallback,
@@ -71,6 +77,7 @@ import { z } from 'zod/v4'
import {
useCreateInvitation,
useDeleteInvitation,
+ useInvitationAcceptanceLink,
useInvitations,
useRemoveStaff,
useResendInvitation,
@@ -301,15 +308,25 @@ function InvitationRow({ invitation }: { invitation: Invitation }) {
const resendMutation = useResendInvitation()
const deleteMutation = useDeleteInvitation()
const confirm = useConfirm()
+ const acceptanceLink = useInvitationAcceptanceLink()
+ const { permissions } = usePermissions()
const { copy } = useCopyToClipboard()
async function handleCopyLink() {
- // Path-only when `Spree::Config[:admin_url]` is unset; resolve against the SPA's origin.
- const url = invitation.acceptance_url.startsWith('/')
- ? `${window.location.origin}${invitation.acceptance_url}`
- : invitation.acceptance_url
- await copy(url)
- toastManager.add({ type: 'success', title: t('admin.staff.actions.invitation_link_copied') })
+ try {
+ const { acceptance_url } = await acceptanceLink.mutateAsync(invitation.id)
+ // Path-only when no dashboard origin is configured; resolve against the SPA's origin.
+ const url = acceptance_url.startsWith('/')
+ ? `${window.location.origin}${acceptance_url}`
+ : acceptance_url
+ await copy(url)
+ toastManager.add({ type: 'success', title: t('admin.staff.actions.invitation_link_copied') })
+ } catch (err) {
+ toastManager.add({
+ type: 'error',
+ title: err instanceof Error ? err.message : t('admin.staff.errors.failed_to_copy_link'),
+ })
+ }
}
async function handleResend() {
@@ -385,6 +402,8 @@ function InvitationRow({ invitation }: { invitation: Invitation }) {
key: 'copy-link',
label: t('admin.staff.actions.copy_invitation_link'),
icon: <LinkIcon className="size-4" />,
+ visible: permissions.can('update', Subject.Invitation),
+ disabled: acceptanceLink.isPending,
onSelect: handleCopyLink,
},
{
diff --git a/packages/seller-dashboard/src/pages/team.tsx b/packages/seller-dashboard/src/pages/team.tsx
index 441c9fd1ef..4e11b85003 100644
--- a/packages/seller-dashboard/src/pages/team.tsx
+++ b/packages/seller-dashboard/src/pages/team.tsx
@@ -1,4 +1,4 @@
-import { Can, getInitials, PageHeader, Slot } from '@spree/dashboard-core'
+import { Can, getInitials, PageHeader, Slot, usePermissions } from '@spree/dashboard-core'
import {
Avatar,
AvatarFallback,
@@ -283,6 +283,7 @@ function InvitationRow({ invitation }: { invitation: Invitation }) {
const queryClient = useQueryClient()
const confirm = useConfirm()
const { copy } = useCopyToClipboard()
+ const { permissions } = usePermissions()
const invalidate = () =>
queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'invitations'] })
@@ -313,20 +314,34 @@ function InvitationRow({ invitation }: { invitation: Invitation }) {
}),
})
+ // The link carries the invitation's token, so it is fetched on demand
+ // rather than shipped with the listing.
+ const acceptanceLink = useMutation({
+ mutationFn: (id: string) => sellerClient().invitations.acceptanceLink(id),
+ })
+
async function handleCopyLink() {
- // Path-only when no panel origin is configured; resolve against wherever
- // this panel is actually mounted. `BASE_URL` matters: served at /sellers
- // (the single-node topology), origin alone would produce a link that
- // misses the mount and 404s.
- const url = invitation.acceptance_url.startsWith('/')
- ? new URL(
- `.${invitation.acceptance_url}`,
- `${window.location.origin}${import.meta.env.BASE_URL}`,
- ).toString()
- : invitation.acceptance_url
-
- await copy(url)
- toastManager.add({ type: 'success', title: t('team.messages.link_copied') })
+ try {
+ const { acceptance_url } = await acceptanceLink.mutateAsync(invitation.id)
+ // Path-only when no panel origin is configured; resolve against wherever
+ // this panel is actually mounted. `BASE_URL` matters: served at /sellers
+ // (the single-node topology), origin alone would produce a link that
+ // misses the mount and 404s.
+ const url = acceptance_url.startsWith('/')
+ ? new URL(
+ `.${acceptance_url}`,
+ `${window.location.origin}${import.meta.env.BASE_URL}`,
+ ).toString()
+ : acceptance_url
+
+ await copy(url)
+ toastManager.add({ type: 'success', title: t('team.messages.link_copied') })
+ } catch (err) {
+ toastManager.add({
+ type: 'error',
+ title: err instanceof Error ? err.message : t('common.error'),
+ })
+ }
}
async function handleRevoke() {
@@ -371,6 +386,8 @@ function InvitationRow({ invitation }: { invitation: Invitation }) {
key: 'copy',
label: t('team.actions.copy_link'),
icon: <LinkIcon className="size-4" />,
+ visible: permissions.can('update', 'seller_profile'),
+ disabled: acceptanceLink.isPending,
onSelect: handleCopyLink,
},
{
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 7b666e6a7b..3248e695c2 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -15,6 +15,7 @@ import type {
Import,
ImportRow,
Invitation,
+ InvitationAcceptanceLink,
Order,
PackageType,
Payout,
@@ -304,6 +305,10 @@ export class SellerClient {
/** Withdraws an offer that has not been accepted. */
revoke: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/invitations/${id}`, options),
+
+ /** The link a colleague opens to join; it carries the invitation's token. */
+ acceptanceLink: (id: string, options?: RequestOptions): Promise<InvitationAcceptanceLink> =>
+ this.request<InvitationAcceptanceLink>('GET', `/invitations/${id}/acceptance_link`, options),
}
/**
diff --git a/packages/seller-sdk/src/types/generated/Invitation.ts b/packages/seller-sdk/src/types/generated/Invitation.ts
index 40dd801062..bc7d82c359 100644
--- a/packages/seller-sdk/src/types/generated/Invitation.ts
+++ b/packages/seller-sdk/src/types/generated/Invitation.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 9f9288dfab6fb9b426a3712756a3407f
+// Typelizer digest 82b23b3aa65e23088346388740a94f37
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {InvitationStatus} from '@/types'
@@ -10,7 +10,6 @@ type Invitation = {
expires_at: string | null;
accepted_at: string | null;
status: InvitationStatus;
- acceptance_url: string;
}
export default Invitation;
diff --git a/packages/seller-sdk/src/types/generated/InvitationAcceptanceLink.ts b/packages/seller-sdk/src/types/generated/InvitationAcceptanceLink.ts
new file mode 100644
index 0000000000..466fb955fc
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/InvitationAcceptanceLink.ts
@@ -0,0 +1,10 @@
+// Typelizer digest f5f197c5c870caa68e76d88979afefab
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type InvitationAcceptanceLink = {
+ id: string;
+ acceptance_url: string;
+}
+
+export default InvitationAcceptanceLink;
diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.ts
index d0703f6105..7f83712809 100644
--- a/packages/seller-sdk/src/types/generated/index.ts
+++ b/packages/seller-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 6319e187657fb620d87ebc1541716387
+// Typelizer digest 569a224cd20ff6a2977dfb45119e6391
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { ClaimStatus, ExchangeStatus, FulfillmentStatus, ImportRowStatus, ImportStatus, InvitationStatus, ProductStatus, ProductSubmissionStatus, ReturnStatus, SellerRequirementSubmissionStatus, SellerStatus, ShippingLabelStatus, StockLocationKind } from './Enums'
@@ -27,6 +27,7 @@ export type { default as Fulfillment } from './Fulfillment'
export type { default as ImportMapping } from './ImportMapping'
export type { default as ImportRow } from './ImportRow'
export type { default as Import } from './Import'
+export type { default as InvitationAcceptanceLink } from './InvitationAcceptanceLink'
export type { default as Invitation } from './Invitation'
export type { default as Media } from './Media'
export type { default as OrderLineItem } from './OrderLineItem'
diff --git a/spree/api/app/controllers/spree/api/v3/admin/invitations/acceptance_links_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/invitations/acceptance_links_controller.rb
new file mode 100644
index 0000000000..47f450aef3
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/invitations/acceptance_links_controller.rb
@@ -0,0 +1,41 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Invitations
+ # The acceptance link of a pending staff invitation.
+ #
+ # The link carries the token that creates the account and grants the
+ # role, so it is authorized like sending the invitation: the caller
+ # needs write access to staff and must be allowed to grant the
+ # invitation's role. Reading staff is not enough.
+ class AcceptanceLinksController < Admin::BaseController
+ include Spree::Api::V3::Admin::RoleGrantGuard
+
+ scoped_resource :staff
+
+ # GET /api/v3/admin/invitations/:invitation_id/acceptance_link
+ def show
+ invitation = Spree::Invitation.
+ where(resource: current_store).
+ pending.
+ find_by_prefix_id!(params[:invitation_id])
+ authorize!(:update, invitation)
+ return if reject_unauthorized_role_grant!([invitation.role_id])
+
+ render json: Spree.api.admin_invitation_acceptance_link_serializer.new(
+ invitation, params: { store: current_store }
+ ).to_h
+ end
+
+ protected
+
+ def read_actions
+ []
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/sellers/invitations/acceptance_links_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/sellers/invitations/acceptance_links_controller.rb
new file mode 100644
index 0000000000..f3e9013be9
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/sellers/invitations/acceptance_links_controller.rb
@@ -0,0 +1,37 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Sellers
+ module Invitations
+ # The acceptance link of a pending invitation onto a seller's team.
+ #
+ # The link carries the token that joins the team, so reading
+ # sellers is not enough: the caller must be able to change the
+ # seller, as when sending the invitation.
+ class AcceptanceLinksController < Admin::BaseController
+ scoped_resource :sellers
+
+ # GET /api/v3/admin/sellers/:seller_id/invitations/:invitation_id/acceptance_link
+ def show
+ seller = current_store.sellers.find_by_prefix_id!(params[:seller_id])
+ authorize!(:update, seller)
+ invitation = seller.invitations.pending.find_by_prefix_id!(params[:invitation_id])
+
+ render json: Spree.api.admin_invitation_acceptance_link_serializer.new(
+ invitation, params: { store: current_store }
+ ).to_h
+ end
+
+ protected
+
+ def read_actions
+ []
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/invitations/acceptance_links_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/invitations/acceptance_links_controller.rb
new file mode 100644
index 0000000000..e9fc0d0ab7
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/invitations/acceptance_links_controller.rb
@@ -0,0 +1,34 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ module Invitations
+ # The acceptance link of a pending invitation onto this seller's team.
+ #
+ # The link carries the token that joins the team, so it is authorized
+ # like inviting someone: write access to the seller profile. Rooted at
+ # `current_seller.invitations`, so another seller's invitation reads
+ # as missing.
+ class AcceptanceLinksController < Seller::BaseController
+ scoped_resource :seller_profile
+
+ # GET /api/v3/seller/invitations/:invitation_id/acceptance_link
+ def show
+ invitation = current_seller.invitations.pending.find_by_prefix_id!(params[:invitation_id])
+
+ render json: Spree.api.seller_invitation_acceptance_link_serializer.new(
+ invitation, params: { store: current_store }
+ ).to_h
+ end
+
+ protected
+
+ def read_actions
+ []
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/invitation_acceptance_link_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/invitation_acceptance_link_serializer.rb
new file mode 100644
index 0000000000..6a941a92da
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/invitation_acceptance_link_serializer.rb
@@ -0,0 +1,15 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # The acceptance link of one staff invitation, served on its own so the
+ # token never travels with the invitation listing.
+ class InvitationAcceptanceLinkSerializer < V3::BaseSerializer
+ typelize acceptance_url: :string
+
+ attributes :acceptance_url
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb
index 29b086699d..2a3a999c0a 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb
@@ -13,7 +13,6 @@ module Spree
role_name: :string,
inviter_email: :string,
expires_at: :string,
- acceptance_url: :string,
invitee_exists: :boolean,
store: '{ id: string; name: string }'
@@ -34,16 +33,6 @@ module Spree
invitation.inviter.email
end
- # Absolute URL when a dashboard origin is configured, otherwise the
- # path so the SPA can prepend `window.location.origin`.
- attribute :acceptance_url do |invitation|
- if Spree::Config[:dashboard_url].present?
- Rails.application.routes.url_helpers.admin_invitation_acceptance_url(invitation)
- else
- "/accept-invitation/#{invitation.prefixed_id}?token=#{invitation.token}"
- end
- end
-
# Drives the SPA's sign-in vs sign-up branch on the acceptance page.
# Looked up by email so an admin who's already on another store sees
# the password prompt, not a fresh account form.
diff --git a/spree/api/app/serializers/spree/api/v3/seller/invitation_acceptance_link_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/invitation_acceptance_link_serializer.rb
new file mode 100644
index 0000000000..119229224a
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/invitation_acceptance_link_serializer.rb
@@ -0,0 +1,15 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # The acceptance link of one seller-team invitation, served on its own
+ # so the token never travels with the invitation listing.
+ class InvitationAcceptanceLinkSerializer < V3::BaseSerializer
+ typelize acceptance_url: :string
+
+ attributes :acceptance_url
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb
index 5f95a5a879..46468c4eb9 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb
@@ -5,8 +5,7 @@ module Spree
class InvitationSerializer < V3::BaseSerializer
typelize email: :string, status: [:string, enum: Spree::Invitation.statuses, enum_type_name: 'InvitationStatus'],
expires_at: [:string, nullable: true],
- accepted_at: [:string, nullable: true],
- acceptance_url: :string
+ accepted_at: [:string, nullable: true]
attributes :email,
created_at: :iso8601, expires_at: :iso8601, accepted_at: :iso8601
@@ -14,14 +13,6 @@ module Spree
attribute :status do |invitation|
invitation.status.to_s
end
-
- attribute :acceptance_url do |invitation|
- if Spree::Config[:seller_panel_url].present? || Spree::Config[:dashboard_url].present?
- Rails.application.routes.url_helpers.admin_invitation_acceptance_url(invitation)
- else
- "/accept-invitation/#{invitation.prefixed_id}?token=#{invitation.token}"
- end
- end
end
end
end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 00cbcfbd45..2f1f8b51df 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -273,6 +273,7 @@ Spree::Core::Engine.add_routes do
member do
patch :resend
end
+ resource :acceptance_link, only: [:show], controller: 'invitations/acceptance_links'
end
resources :api_keys, only: [:index, :show, :create, :update, :destroy] do
collection do
@@ -590,6 +591,7 @@ Spree::Core::Engine.add_routes do
member do
patch :resend
end
+ resource :acceptance_link, only: [:show], controller: 'sellers/invitations/acceptance_links'
end
# What this seller submitted about the requirements, and the
@@ -900,6 +902,7 @@ Spree::Core::Engine.add_routes do
member do
patch :resend
end
+ resource :acceptance_link, only: [:show], controller: 'invitations/acceptance_links'
end
resources :products, only: [:index, :show, :create, :update, :destroy] do
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index c462d547db..d0ac2c9579 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -189,6 +189,7 @@ module Spree
seller_team_member_serializer: 'Spree::Api::V3::Seller::TeamMemberSerializer',
seller_account_serializer: 'Spree::Api::V3::Seller::AccountSerializer',
seller_invitation_serializer: 'Spree::Api::V3::Seller::InvitationSerializer',
+ seller_invitation_acceptance_link_serializer: 'Spree::Api::V3::Seller::InvitationAcceptanceLinkSerializer',
seller_product_serializer: 'Spree::Api::V3::Seller::ProductSerializer',
seller_product_type_serializer: 'Spree::Api::V3::Seller::ProductTypeSerializer',
seller_delivery_profile_serializer: 'Spree::Api::V3::Seller::DeliveryProfileSerializer',
@@ -268,6 +269,7 @@ module Spree
admin_webhook_endpoint_serializer: 'Spree::Api::V3::Admin::WebhookEndpointSerializer',
admin_webhook_delivery_serializer: 'Spree::Api::V3::Admin::WebhookDeliverySerializer',
admin_invitation_serializer: 'Spree::Api::V3::Admin::InvitationSerializer',
+ admin_invitation_acceptance_link_serializer: 'Spree::Api::V3::Admin::InvitationAcceptanceLinkSerializer',
admin_role_serializer: 'Spree::Api::V3::Admin::RoleSerializer',
admin_permission_serializer: 'Spree::Api::V3::Admin::PermissionSerializer',
admin_export_serializer: 'Spree::Api::V3::Admin::ExportSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/invitations/acceptance_links_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/invitations/acceptance_links_controller_spec.rb
new file mode 100644
index 0000000000..9a6264783a
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/invitations/acceptance_links_controller_spec.rb
@@ -0,0 +1,73 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::Invitations::AcceptanceLinksController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin'
+
+ let!(:admin_role) { Spree::Role.default_admin_role }
+ let(:staff_role) { create(:role, name: 'staff', permissions: %w[read_orders], resource: store) }
+ let(:invitation) { create(:invitation, resource: store, role: staff_role) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #show' do
+ context 'as a super-admin' do
+ let(:headers) { bearer_headers }
+
+ it 'returns the link with its token' do
+ get :show, params: { invitation_id: invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['acceptance_url']).to include(invitation.token)
+ end
+
+ it 'does not find an invitation of another store' do
+ other = create(:invitation, resource: create(:store))
+
+ get :show, params: { invitation_id: other.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ # Reading staff is not enough: the token creates the account and grants
+ # the role, so it is authorized like sending the invitation.
+ context 'with a secret key that can only read staff' do
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: ['read_staff']) }
+ let(:headers) { { 'x-spree-api-key' => caller_key.plaintext_token } }
+
+ it 'is forbidden' do
+ get :show, params: { invitation_id: invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(response.body).not_to include(invitation.token)
+ end
+ end
+
+ context 'as a non-admin staff member who can write staff' do
+ let(:inviter_role) { create(:role, name: 'team_manager', permissions: %w[write_staff read_orders], resource: store) }
+ let(:staff_admin) do
+ create(:admin_user, :without_admin_role).tap { |user| create(:role_user, user: user, role: inviter_role) }
+ end
+ let(:headers) do
+ { 'Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(staff_admin, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}" }
+ end
+
+ it 'returns the link for a role it may grant' do
+ get :show, params: { invitation_id: invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'is forbidden for an invitation into the admin role' do
+ admin_invitation = create(:invitation, resource: store, role: admin_role)
+
+ get :show, params: { invitation_id: admin_invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(response.body).not_to include(admin_invitation.token)
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/invitations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/invitations_controller_spec.rb
index 3257ae515e..9ba949a719 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/invitations_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/invitations_controller_spec.rb
@@ -90,4 +90,21 @@ RSpec.describe Spree::Api::V3::Admin::InvitationsController, type: :controller d
end
end
end
+
+ describe 'GET #index' do
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: ['read_staff']) }
+ let(:headers) { { 'x-spree-api-key' => caller_key.plaintext_token } }
+ let!(:invitation) { create(:invitation, resource: store, role: admin_role) }
+
+ # The token creates the account and grants the role, so a read-only
+ # principal must never see it.
+ it 'does not expose the acceptance token' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].first['id']).to eq(invitation.prefixed_id)
+ expect(response.body).not_to include(invitation.token)
+ expect(json_response['data'].first).not_to have_key('acceptance_url')
+ end
+ end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations/acceptance_links_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations/acceptance_links_controller_spec.rb
new file mode 100644
index 0000000000..b7f0636dc7
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations/acceptance_links_controller_spec.rb
@@ -0,0 +1,40 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::Sellers::Invitations::AcceptanceLinksController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin'
+
+ let(:seller) { create(:seller, store: store) }
+ let(:invitation) do
+ create(:invitation, resource: seller, role: seller.default_user_role, inviter: admin_user)
+ end
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #show' do
+ context 'with a key that can change sellers' do
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: ['write_sellers']) }
+ let(:headers) { { 'x-spree-api-key' => caller_key.plaintext_token } }
+
+ it 'returns the link with its token' do
+ get :show, params: { seller_id: seller.prefixed_id, invitation_id: invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['acceptance_url']).to include(invitation.token)
+ end
+ end
+
+ context 'with a key that can only read sellers' do
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: ['read_sellers']) }
+ let(:headers) { { 'x-spree-api-key' => caller_key.plaintext_token } }
+
+ it 'is forbidden' do
+ get :show, params: { seller_id: seller.prefixed_id, invitation_id: invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(response.body).not_to include(invitation.token)
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations_controller_spec.rb
index b8c1856de8..426330a4ec 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/sellers/invitations_controller_spec.rb
@@ -22,6 +22,14 @@ RSpec.describe Spree::Api::V3::Admin::Sellers::InvitationsController, type: :con
expect(json_response['data'].map { |row| row['id'] }).to include(invitation.prefixed_id)
end
+ it 'does not expose the acceptance token' do
+ invitation
+
+ get :index, params: { seller_id: seller.prefixed_id }, as: :json
+
+ expect(response.body).not_to include(invitation.token)
+ end
+
# An accepted invitation is a team member, which the team endpoint lists.
it 'leaves out one that has been accepted' do
invitation.update!(accepted_at: Time.current, status: 'accepted')
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/invitations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/invitations_controller_spec.rb
index 1769ed0213..5168a499fd 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/invitations_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/invitations_controller_spec.rb
@@ -32,10 +32,13 @@ RSpec.describe Spree::Api::V3::Seller::InvitationsController, type: :controller
expect(json_response['data'].pluck('email')).to include('[email protected]')
end
- it 'carries a link the panel can hand to a colleague' do
+ # The link is served on its own endpoint, so the listing never carries
+ # the token.
+ it 'does not expose the acceptance token' do
get :index, as: :json
- expect(json_response['data'].first['acceptance_url']).to include(invitation.prefixed_id)
+ expect(json_response['data'].first).not_to have_key('acceptance_url')
+ expect(response.body).not_to include(invitation.token)
end
# An accepted invitation is a team member, and the panel lists those
diff --git a/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb
index f3188f4539..289f0f8c44 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb
@@ -93,6 +93,36 @@ RSpec.describe 'Admin Invitations API', type: :request, swagger_doc: 'api-refere
end
end
+ path '/api/v3/admin/invitations/{invitation_id}/acceptance_link' do
+ let(:invitation_id) { invitation.prefixed_id }
+
+ get 'Get an invitation acceptance link' do
+ tags 'Staff'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Returns the link the invitee opens to accept a pending invitation. The link carries the ' \
+ 'invitation token, so it needs write access to staff and the right to grant the invitation\'s ' \
+ 'role; invitation listings never include it.'
+ admin_scope :write, :staff
+
+ admin_sdk_example 'invitations/acceptance-link'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :invitation_id, in: :path, type: :string, required: true
+
+ response '200', 'acceptance link found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+
+ schema '$ref' => '#/components/schemas/InvitationAcceptanceLink'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['acceptance_url']).to include('/accept-invitation/')
+ end
+ end
+ end
+ end
+
path '/api/v3/admin/invitations/{id}/resend' do
let(:id) { invitation.prefixed_id }
diff --git a/spree/api/spec/integration/spree/api/v3/seller/invitations_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/invitations_spec.rb
index bc55060fe4..6e8796bddc 100644
--- a/spree/api/spec/integration/spree/api/v3/seller/invitations_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/seller/invitations_spec.rb
@@ -52,6 +52,35 @@ RSpec.describe 'Seller Invitations API', type: :request, swagger_doc: 'api-refer
end
end
+ path '/api/v3/seller/invitations/{invitation_id}/acceptance_link' do
+ parameter name: :invitation_id, in: :path, type: :string, description: 'Invitation ID'
+
+ get 'Get an invitation acceptance link' do
+ tags 'Team'
+ produces 'application/json'
+ security [bearer_auth: []]
+ description <<~DESC
+ The link a colleague opens to join the team. It carries the invitation's
+ token, so the listing never includes it; fetch it when someone asks to
+ copy the link.
+ DESC
+
+ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true
+
+ response '200', 'acceptance link found' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:invitation_id) { pending_invitation.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/InvitationAcceptanceLink'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['acceptance_url']).to include(pending_invitation.token)
+ end
+ end
+ end
+ end
+
path '/api/v3/seller/invitations/{id}/resend' do
parameter name: :id, in: :path, type: :string, description: 'Invitation ID'
diff --git a/spree/api/spec/requests/spree/api/v3/seller/team_management_spec.rb b/spree/api/spec/requests/spree/api/v3/seller/team_management_spec.rb
index 8fef154081..d458082989 100644
--- a/spree/api/spec/requests/spree/api/v3/seller/team_management_spec.rb
+++ b/spree/api/spec/requests/spree/api/v3/seller/team_management_spec.rb
@@ -30,7 +30,12 @@ RSpec.describe 'Seller team management', type: :request do
get '/api/v3/seller/invitations', headers: headers
pending = json['data'].first
expect(pending['email']).to eq('[email protected]')
- expect(pending['acceptance_url']).to be_present
+ expect(pending).not_to have_key('acceptance_url')
+
+ # The link is fetched on demand, so the listing never carries the token.
+ get "/api/v3/seller/invitations/#{pending['id']}/acceptance_link", headers: headers
+ expect(response).to have_http_status(:ok)
+ expect(json['acceptance_url']).to include(Spree::Invitation.find_by(email: '[email protected]').token)
patch "/api/v3/seller/invitations/#{pending['id']}/resend", headers: headers
expect(response).to have_http_status(:ok)
diff --git a/spree/core/app/models/spree/invitation.rb b/spree/core/app/models/spree/invitation.rb
index 97f111b954..61a3569505 100644
--- a/spree/core/app/models/spree/invitation.rb
+++ b/spree/core/app/models/spree/invitation.rb
@@ -97,10 +97,22 @@ module Spree
true
end
- # Resends the invitation email if the invitation is pending and not expired
+ # The link that accepts this invitation. It carries the token, which is the
+ # only credential acceptance asks for, so hand it only to a caller who could
+ # have sent the invitation themselves.
+ #
+ # @return [String] an absolute URL when the app's origin is configured, otherwise a path
+ def acceptance_url
+ Rails.application.routes.url_helpers.admin_invitation_acceptance_url(self)
+ end
+
+ # Resends the invitation email if the invitation is pending and not expired.
+ # The token is rotated first, so a link that leaked with the earlier email
+ # stops working.
def resend!
return if expired? || deleted? || accepted?
+ regenerate_token
publish_event('invitation.resent')
end
diff --git a/spree/core/spec/models/spree/invitation_spec.rb b/spree/core/spec/models/spree/invitation_spec.rb
index 1e0f2803b4..7c3ee6f467 100644
--- a/spree/core/spec/models/spree/invitation_spec.rb
+++ b/spree/core/spec/models/spree/invitation_spec.rb
@@ -147,5 +147,22 @@ RSpec.describe Spree::Invitation, type: :model do
expect(invitation).not_to receive(:publish_event)
invitation.resend!
end
+
+ # A link that leaked with the earlier email must stop working.
+ it 'rotates the token' do
+ expect { invitation.resend! }.to change { invitation.reload.token }
+ end
+
+ it 'keeps the token of an expired invitation' do
+ invitation.update_column(:expires_at, 1.day.ago)
+
+ expect { invitation.resend! }.not_to change { invitation.reload.token }
+ end
+ end
+
+ describe '#acceptance_url' do
+ it 'carries the invitation and its token' do
+ expect(invitation.acceptance_url).to include("/accept-invitation/#{invitation.prefixed_id}?token=#{invitation.token}")
+ end
end
end