diff --git a/README.md b/README.md index 135cd20..02e0c5d 100644 --- a/README.md +++ b/README.md @@ -91,8 +91,9 @@ CONTRIBKIT_GITHUB_LOGIN= CONTRIBKIT_MODE=sponsors ; Patreon provider. -; Create v2 API key at https://www.patreon.com/portal/registration/register-clients -; and use the "Creator’s Access Token". +; Uses the Patreon API v2. +; Register a v2 client at https://www.patreon.com/portal/registration/register-clients. +; Set the Creator's Access Token, which includes the required campaign scopes. CONTRIBKIT_PATREON_TOKEN= ; OpenCollective provider. diff --git a/src/providers/patreon.test.ts b/src/providers/patreon.test.ts new file mode 100644 index 0000000..d379fb3 --- /dev/null +++ b/src/providers/patreon.test.ts @@ -0,0 +1,260 @@ +import type { Mock } from 'vitest' +import type { PatreonMemberAttributes, PatreonUserAttributes } from './patreon.js' +import { $fetch } from 'ofetch' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { fetchPatreonSponsors } from './patreon.js' + +vi.mock('ofetch', () => ({ $fetch: vi.fn() })) + +const fetchMock = $fetch as unknown as Mock + +beforeEach(() => { + fetchMock.mockReset() +}) + +const CAMPAIGNS_URL = 'https://www.patreon.com/api/oauth2/v2/campaigns' + +function member(id: string, userId: string, attributes: PatreonMemberAttributes = {}, tierId?: string) { + return { + id, + type: 'member', + attributes: { + currently_entitled_amount_cents: 500, + patron_status: 'active_patron', + pledge_relationship_start: '2024-01-01T00:00:00+00:00', + ...attributes, + }, + relationships: { + user: { data: { id: userId, type: 'user' } }, + currently_entitled_tiers: { data: tierId ? [{ id: tierId, type: 'tier' }] : [] }, + }, + } +} + +function user(id: string, attributes: PatreonUserAttributes = {}) { + return { + id, + type: 'user', + attributes: { + first_name: 'Ada', + full_name: 'Ada Lovelace', + image_url: 'https://example.com/ada.png', + url: 'https://patreon.com/ada', + ...attributes, + }, + } +} + +describe('fetchPatreonSponsors', () => { + it('requires a token', async () => { + await expect(fetchPatreonSponsors('')) + .rejects + .toThrow('Patreon token is required') + }) + + it('uses the v2 campaigns endpoint instead of the retired v1 endpoint', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ data: [], included: [], links: {} }) + + await fetchPatreonSponsors('token') + + const urls = fetchMock.mock.calls.map(call => call[0]) + expect(urls[0]).toBe(CAMPAIGNS_URL) + expect(urls[1]).toContain('/api/oauth2/v2/campaigns/999/members?') + expect(urls.every((url: string) => !url.includes('/oauth2/api/'))).toBe(true) + }) + + it('requests exactly the fields it reads, and no deprecated ones', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ data: [], links: {} }) + + await fetchPatreonSponsors('token') + + const url = fetchMock.mock.calls[1][0] as string + expect(decodeURIComponent(url)).toContain('fields[member]=currently_entitled_amount_cents,patron_status,pledge_relationship_start') + expect(decodeURIComponent(url)).toContain('fields[user]=image_url,url,first_name,full_name') + expect(decodeURIComponent(url)).toContain('fields[tier]=amount_cents') + // Deprecated in the docs and never read, so it must not be requested. + expect(url).not.toContain('lifetime_support_cents') + }) + + it('sends bearer auth and a User-Agent header', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ data: [], included: [], links: {} }) + + await fetchPatreonSponsors('secret-token') + + const headers = fetchMock.mock.calls[0][1].headers + expect(headers.Authorization).toBe('bearer secret-token') + expect(headers['User-Agent']).toContain('ContribKit') + }) + + it('maps members into sponsorships', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ + data: [member('m-1', 'u-1', { currently_entitled_amount_cents: 1000 })], + included: [user('u-1')], + links: {}, + }) + + const sponsors = await fetchPatreonSponsors('token') + + expect(sponsors).toHaveLength(1) + expect(sponsors[0]).toMatchObject({ + isOneTime: false, + monthlyDollars: 10, + tierName: 'Patreon', + createdAt: '2024-01-01T00:00:00+00:00', + sponsor: { + type: 'User', + login: 'Ada', + name: 'Ada Lovelace', + avatarUrl: 'https://example.com/ada.png', + linkUrl: 'https://patreon.com/ada', + }, + }) + }) + + it('filters out members that have never pledged', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ + data: [ + member('m-1', 'u-1', { patron_status: null }), + member('m-2', 'u-2'), + ], + included: [user('u-1'), user('u-2')], + links: {}, + }) + + const sponsors = await fetchPatreonSponsors('token') + + expect(sponsors).toHaveLength(1) + expect(sponsors[0].sponsor.name).toBe('Ada Lovelace') + }) + + it('marks former and declined patrons as past sponsors', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ + data: [ + member('m-1', 'u-1', { patron_status: 'former_patron' }), + member('m-2', 'u-2', { patron_status: 'declined_patron' }), + ], + included: [user('u-1'), user('u-2')], + links: {}, + }) + + const sponsors = await fetchPatreonSponsors('token') + + expect(sponsors.map(s => s.monthlyDollars)).toEqual([-1, -1]) + }) + + it('falls back to the entitled tier amount for gifted memberships', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ + data: [member('m-1', 'u-1', { currently_entitled_amount_cents: 0 }, 't-1')], + included: [user('u-1'), { id: 't-1', type: 'tier', attributes: { amount_cents: 2500 } }], + links: {}, + }) + + const sponsors = await fetchPatreonSponsors('token') + + expect(sponsors[0].monthlyDollars).toBe(25) + }) + + it('follows the links.next cursor across pages', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ + data: [member('m-1', 'u-1')], + included: [user('u-1', { full_name: 'First' })], + links: { next: 'https://www.patreon.com/api/oauth2/v2/campaigns/999/members?page%5Bcursor%5D=NEXT' }, + }) + .mockResolvedValueOnce({ + data: [member('m-2', 'u-2')], + included: [user('u-2', { full_name: 'Second' })], + links: {}, + }) + + const sponsors = await fetchPatreonSponsors('token') + + expect(fetchMock).toHaveBeenCalledTimes(3) + expect(fetchMock.mock.calls[2][0]).toContain('page%5Bcursor%5D=NEXT') + // The cursor page is a fresh request, so it must carry the credentials too. + expect(fetchMock.mock.calls[2][1].headers.Authorization).toBe('bearer token') + expect(sponsors.map(s => s.sponsor.name)).toEqual(['First', 'Second']) + }) + + it('survives responses without an included array', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ data: [member('m-1', 'u-1')], links: {} }) + + const sponsors = await fetchPatreonSponsors('token') + + expect(sponsors).toHaveLength(1) + expect(sponsors[0].monthlyDollars).toBe(5) + }) + + it('handles an empty member collection', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ data: [], links: {} }) + + await expect(fetchPatreonSponsors('token')).resolves.toEqual([]) + }) + + it('fails loudly when a collection response has no data member', async () => { + // A collection document always carries `data`, so this is malformed and must fail rather + // than be read as "no sponsors". + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ links: {} }) + + await expect(fetchPatreonSponsors('token')) + .rejects + .toThrow(TypeError) + }) + + it('handles identity-masked members without throwing', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ + data: [member('m-1', 'u-1')], + included: [user('u-1', { first_name: null, full_name: null, image_url: null, url: null })], + links: {}, + }) + + const sponsors = await fetchPatreonSponsors('token') + + expect(sponsors[0].sponsor).toMatchObject({ + login: 'Anonymous', + name: 'Anonymous', + avatarUrl: '', + }) + }) + + it('reports a clear error when the token has no campaign', async () => { + fetchMock.mockResolvedValueOnce({ data: [] }) + + await expect(fetchPatreonSponsors('token')) + .rejects + .toThrow(/No Patreon campaign found/) + }) + + it('handles a member whose user resource is absent from included', async () => { + fetchMock.mockResolvedValueOnce({ data: [{ id: '999', type: 'campaign' }] }) + .mockResolvedValueOnce({ + data: [member('m-1', 'u-1')], + included: [{ id: 't-1', type: 'tier', attributes: { amount_cents: 300 } }], + links: {}, + }) + + const sponsors = await fetchPatreonSponsors('token') + + expect(sponsors[0].sponsor).toMatchObject({ login: 'Anonymous', name: 'Anonymous', avatarUrl: '' }) + expect(sponsors[0].monthlyDollars).toBe(5) + }) + + it('propagates HTTP failures unchanged', async () => { + fetchMock.mockRejectedValueOnce(new Error('[GET] "https://www.patreon.com/api/oauth2/v2/campaigns": 401 Unauthorized')) + + await expect(fetchPatreonSponsors('token')) + .rejects + .toThrow(/401 Unauthorized/) + }) +}) diff --git a/src/providers/patreon.ts b/src/providers/patreon.ts index afddc98..261f958 100644 --- a/src/providers/patreon.ts +++ b/src/providers/patreon.ts @@ -14,78 +14,184 @@ export const PatreonProvider: Provider = { }, } +/** Patreon's v2 API base. The v1 API was retired on 2026-10-07. */ +const PATREON_API = 'https://www.patreon.com/api/oauth2/v2' + +/** A JSON:API resource identifier; both members are required, except for client-originated resources. */ +interface PatreonIdentifier { + id: string + type: string +} + +/** A relationship may carry `links` instead of `data`, so both are optional here. */ +interface PatreonRelationship { + data?: PatreonIdentifier | PatreonIdentifier[] | null + links?: { self?: string, related?: string } +} + +/** A JSON:API resource; relationships carry the ids used to join `included` back to members. */ +interface PatreonResource { + id?: string + type?: string + attributes?: A + relationships?: Record +} + +export interface PatreonMemberAttributes { + currently_entitled_amount_cents?: number | null + patron_status?: string | null + pledge_relationship_start?: string | null +} + +/** Patreon sends `null` when a member has opted out of sharing their profile. */ +export interface PatreonUserAttributes { + first_name?: string | null + full_name?: string | null + image_url?: string | null + url?: string | null +} + +interface PatreonTierAttributes { + amount_cents?: number | null +} + +/** Discriminated on `type` so the two resource kinds can be separated by a type guard. */ +interface PatreonUserResource extends PatreonResource { + type: 'user' +} + +interface PatreonTierResource extends PatreonResource { + type: 'tier' +} + +interface PatreonMembersData { + /** A collection document always carries `data`; `[]` when there are no members. */ + data: PatreonResource[] + /** Only present when `include` matched something; joined to members by `firstRelatedId`. */ + included?: (PatreonUserResource | PatreonTierResource)[] + links?: { next?: string | null } +} + +/** A collection document carries `data`; only the campaign `id` is read. */ +interface PatreonCampaignsData { + data: { id: string }[] +} + +/** A member joined to the user and tier it references. */ +interface PatreonSponsorRecord { + membership: PatreonResource + patron: PatreonUserResource | undefined + tier: PatreonTierResource | undefined +} + +/** `patron_status` is documented only as a nullable string; these two mark a lapsed sponsor. */ +const PAST_PATRON_STATUSES = new Set(['former_patron', 'declined_patron']) + export async function fetchPatreonSponsors(token: string | undefined): Promise { if (!token) throw new Error('Patreon token is required') - // Get the authenticated creator's campaign ID using API v2. - const userData = await $fetch( - 'https://www.patreon.com/api/oauth2/v2/campaigns', - { - method: 'GET', - headers: { - 'Authorization': `bearer ${token}`, - 'Content-Type': 'application/json', - }, - responseType: 'json', - }, - ) - const userCampaignId = userData.data[0].id + const campaignId = await fetchPatreonCampaignId(token) + + // v2 pages up to 1000 members and returns a `links.next` cursor. + const sponsors: PatreonSponsorRecord[] = [] + let sponsorshipApi: string | undefined = `${PATREON_API}/campaigns/${campaignId}/members?include=user,currently_entitled_tiers&fields%5Bmember%5D=currently_entitled_amount_cents,patron_status,pledge_relationship_start&fields%5Buser%5D=image_url,url,first_name,full_name&fields%5Btier%5D=amount_cents` - const sponsors: any[] = [] - let sponsorshipApi = `https://www.patreon.com/api/oauth2/v2/campaigns/${userCampaignId}/members?include=user,currently_entitled_tiers&fields%5Bmember%5D=currently_entitled_amount_cents,patron_status,pledge_relationship_start,lifetime_support_cents&fields%5Buser%5D=image_url,url,first_name,full_name&fields%5Btier%5D=amount_cents&page%5Bcount%5D=100` do { - // Get pledges from the campaign - const sponsorshipData = await $fetch(sponsorshipApi, { // NOSONAR(typescript:S9382): The next page URL is supplied by this response. + // The annotation is needed: this loop feeds `links.next` back into `sponsorshipApi`, and + // TypeScript cannot infer the response through that cycle. + const { included = [], data: members, links }: PatreonMembersData = await $fetch(sponsorshipApi, { // NOSONAR(typescript:S9382): The next page URL is supplied by this response. method: 'GET', - headers: { - 'Authorization': `bearer ${token}`, - 'Content-Type': 'application/json', - }, + headers: patreonHeaders(token), responseType: 'json', }) + // Split by kind so each lookup below searches a homogeneous array. + const users = included.filter(v => v.type === 'user') + const tiers = included.filter(v => v.type === 'tier') + sponsors.push( - ...sponsorshipData.data - // Filter out "never pledged" members - .filter((membership: any) => membership.attributes.patron_status !== null) - .map((membership: any) => ({ + ...members + .filter(membership => membership.attributes?.patron_status != null) + .map(membership => ({ membership, - patron: sponsorshipData.included.find( - (v: any) => v.type === 'user' && v.id === membership.relationships.user.data.id, - ), - tier: sponsorshipData.included.find( - (v: any) => v.type === 'tier' && v.id === membership.relationships.currently_entitled_tiers.data[0]?.id, - ), + patron: users.find(v => v.id === firstRelatedId(membership, 'user')), + tier: tiers.find(v => v.id === firstRelatedId(membership, 'currently_entitled_tiers')), })), ) - sponsorshipApi = sponsorshipData.links?.next + sponsorshipApi = links?.next ?? undefined } while (sponsorshipApi) - const processed = sponsors.map((raw: any): Sponsorship => { + return sponsors.map((raw): Sponsorship => { + const attributes = raw.membership.attributes + // Patreon masks the identity of members who opted out of sharing their profile. + const patronAttributes = raw.patron?.attributes + const name = patronAttributes?.full_name || patronAttributes?.first_name || 'Anonymous' + + // A gifted membership can have no entitled amount but still name a paid tier. + const entitledCents = attributes?.currently_entitled_amount_cents + const tierCents = raw.tier?.attributes?.amount_cents + const monthlyDollars = entitledCents == null || entitledCents <= 0 + ? Math.floor((tierCents ?? 0) / 100) + : Math.floor(entitledCents / 100) + const sponsor: Sponsorship = { sponsor: { - avatarUrl: raw.patron.attributes.image_url, - login: raw.patron.attributes.first_name, - name: raw.patron.attributes.full_name, + avatarUrl: patronAttributes?.image_url || '', + login: patronAttributes?.first_name || name, + name, type: 'User', // Patreon only support user - linkUrl: raw.patron.attributes.url, + linkUrl: patronAttributes?.url ?? undefined, }, isOneTime: false, // One-time pledges not supported - monthlyDollars: Math.floor(raw.membership.attributes.currently_entitled_amount_cents / 100), + monthlyDollars, privacyLevel: 'PUBLIC', // Patreon is all public tierName: 'Patreon', - createdAt: raw.membership.attributes.pledge_relationship_start, + createdAt: attributes?.pledge_relationship_start ?? undefined, } - // The "former_patron" and "declined_patron" both is past sponsors - if (['former_patron', 'declined_patron'].includes(raw.membership.attributes.patron_status)) + // "former_patron" and "declined_patron" are both past sponsors + const status = attributes?.patron_status + if (status != null && PAST_PATRON_STATUSES.has(status)) sponsor.monthlyDollars = -1 - // If the sponsor is not a patron but has a gifted membership, we can still show the tier amount - else if (sponsor.monthlyDollars <= 0 && (raw.tier?.attributes.amount_cents || 0) > 0) - sponsor.monthlyDollars = Math.floor(raw.tier.attributes.amount_cents / 100) return sponsor }) +} + +/** Resolve the campaign owned by the authenticated user. */ +async function fetchPatreonCampaignId(token: string): Promise { + const { data: campaigns } = await $fetch(`${PATREON_API}/campaigns`, { + method: 'GET', + headers: patreonHeaders(token), + responseType: 'json', + }) + const campaignId = campaigns[0]?.id + if (!campaignId) { + throw new Error( + 'No Patreon campaign found for the given token. ' + + 'Make sure the token belongs to a creator account and was created for a v2 client ' + + '(the v2 `campaigns` scope is required).', + ) + } + return campaignId +} + +/** + * The first id of a relationship that may be a to-one or a to-many. The optional chain is + * load-bearing: an empty to-many relationship yields `undefined`, which the type of `data[0]` does + * not show because `noUncheckedIndexedAccess` is off. + */ +function firstRelatedId(resource: PatreonResource, name: string): string | undefined { + const data = resource.relationships?.[name]?.data + const entry = Array.isArray(data) ? data[0] : data + return entry?.id +} - return processed +/** Shared by both calls so their headers cannot drift apart. */ +function patreonHeaders(token: string) { + return { + 'Authorization': `bearer ${token}`, + // Patreon may drop requests without one. + 'User-Agent': 'ContribKit (https://github.com/LizardByte/contribkit)', + } }