Lumen & Gesso / website · lumengesso.com / app / lib / pinterest.ts
| 1 | import 'server-only'; |
| 2 | import { env } from './env'; |
| 3 | import { commerceDb } from './commerce-db'; |
| 4 | |
| 5 | // Key used to store the refresh token in the `integrations` table. |
| 6 | const RTK_KEY = 'pinterest:refresh_token'; |
| 7 | |
| 8 | /** Read the refresh token from the DB (`integrations` table). Returns null |
| 9 | * if missing or unreadable. Reads via the service-role client; the |
| 10 | * integrations table has RLS on with no policies, so only this path can |
| 11 | * touch it. */ |
| 12 | async function readRefreshTokenFromDb(): Promise<string | null> { |
| 13 | try { |
| 14 | const { data, error } = await commerceDb() |
| 15 | .from('integrations') |
| 16 | .select('value') |
| 17 | .eq('key', RTK_KEY) |
| 18 | .maybeSingle(); |
| 19 | if (error || !data) return null; |
| 20 | return (data.value as string) || null; |
| 21 | } catch { |
| 22 | return null; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | /** Upsert the refresh token to the DB. Called by the OAuth callback so the |
| 27 | * studio doesn't have to copy/paste it into env and restart. */ |
| 28 | export async function saveRefreshToken(token: string): Promise<void> { |
| 29 | const { error } = await commerceDb() |
| 30 | .from('integrations') |
| 31 | .upsert({ key: RTK_KEY, value: token }, { onConflict: 'key' }); |
| 32 | if (error) throw new Error(`save refresh token: ${error.message}`); |
| 33 | // Invalidate the in-process access-token cache so the next call mints a |
| 34 | // fresh one with the new refresh token. |
| 35 | cachedToken = null; |
| 36 | } |
| 37 | |
| 38 | /** Delete the stored refresh token. Called by /api/admin/pinterest/disconnect. */ |
| 39 | export async function clearRefreshToken(): Promise<void> { |
| 40 | const { error } = await commerceDb() |
| 41 | .from('integrations') |
| 42 | .delete() |
| 43 | .eq('key', RTK_KEY); |
| 44 | if (error) throw new Error(`clear refresh token: ${error.message}`); |
| 45 | cachedToken = null; |
| 46 | } |
| 47 | |
| 48 | /** Resolve the refresh token to use for token exchange. DB is the single |
| 49 | * source of truth — set by the OAuth callback, cleared by Disconnect. |
| 50 | * (PINTEREST_REFRESH_TOKEN env was a legacy migration fallback; it was |
| 51 | * removed because it made Disconnect a no-op when env still had a value.) */ |
| 52 | async function getRefreshTokenForExchange(): Promise<string | null> { |
| 53 | return await readRefreshTokenFromDb(); |
| 54 | } |
| 55 | |
| 56 | // Thin client for Pinterest API v5. Designed for a SINGLE Pinterest account |
| 57 | // (the studio's @lumengesso). We store a long-lived refresh token in env |
| 58 | // and mint short-lived access tokens on demand, caching them in-process. |
| 59 | // |
| 60 | // Docs: https://developers.pinterest.com/docs/api/v5/ |
| 61 | // Scopes we use: pins:read, pins:write, boards:read |
| 62 | |
| 63 | const API_BASE = 'https://api.pinterest.com/v5'; |
| 64 | const OAUTH_AUTHORIZE = 'https://www.pinterest.com/oauth/'; |
| 65 | const OAUTH_TOKEN = `${API_BASE}/oauth/token`; |
| 66 | |
| 67 | // `boards:write` is required by /v5/pins even though we're not creating |
| 68 | // boards — Pinterest treats writing TO a board as a "boards:write" action. |
| 69 | // Confirmed empirically: a token with pins:write but not boards:write 401s |
| 70 | // with `Missing: ['boards:write', 'pins:write']` from POST /v5/pins. |
| 71 | export const PINTEREST_SCOPES = [ |
| 72 | 'pins:read', |
| 73 | 'pins:write', |
| 74 | 'boards:read', |
| 75 | 'boards:write', |
| 76 | ] as const; |
| 77 | |
| 78 | /** Callback URL Pinterest redirects to after the user grants access. Must |
| 79 | * exactly match a redirect URI registered on the app in the Pinterest |
| 80 | * dev portal (per environment — dev usually points at the ngrok URL). */ |
| 81 | export function callbackUrl(): string { |
| 82 | // env.site.url() defaults to http://localhost:3000; .env.local sets it to |
| 83 | // https://lumengesso.ngrok.app, prod sets it to https://www.lumengesso.com. |
| 84 | return `${env.site.url().replace(/\/$/, '')}/api/admin/pinterest/callback`; |
| 85 | } |
| 86 | |
| 87 | /** URL to redirect the admin to in order to start the OAuth handshake. */ |
| 88 | export function authorizeUrl(state: string): string { |
| 89 | const u = new URL(OAUTH_AUTHORIZE); |
| 90 | u.searchParams.set('client_id', env.pinterest.clientId()); |
| 91 | u.searchParams.set('redirect_uri', callbackUrl()); |
| 92 | u.searchParams.set('response_type', 'code'); |
| 93 | u.searchParams.set('scope', PINTEREST_SCOPES.join(',')); |
| 94 | u.searchParams.set('state', state); |
| 95 | return u.toString(); |
| 96 | } |
| 97 | |
| 98 | type TokenResponse = { |
| 99 | access_token: string; |
| 100 | refresh_token?: string; |
| 101 | token_type: string; |
| 102 | expires_in: number; |
| 103 | refresh_token_expires_in?: number; |
| 104 | scope: string; |
| 105 | }; |
| 106 | |
| 107 | function basicAuthHeader(): string { |
| 108 | const creds = `${env.pinterest.clientId()}:${env.pinterest.clientSecret()}`; |
| 109 | return `Basic ${Buffer.from(creds, 'utf8').toString('base64')}`; |
| 110 | } |
| 111 | |
| 112 | /** Exchange the one-time auth `code` returned by Pinterest for an access + |
| 113 | * refresh token pair. Called from the OAuth callback route. */ |
| 114 | export async function exchangeCodeForTokens(code: string): Promise<TokenResponse> { |
| 115 | const body = new URLSearchParams({ |
| 116 | grant_type: 'authorization_code', |
| 117 | code, |
| 118 | redirect_uri: callbackUrl(), |
| 119 | }); |
| 120 | const res = await fetch(OAUTH_TOKEN, { |
| 121 | method: 'POST', |
| 122 | headers: { |
| 123 | Authorization: basicAuthHeader(), |
| 124 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 125 | }, |
| 126 | body, |
| 127 | }); |
| 128 | if (!res.ok) { |
| 129 | throw new Error(`Pinterest token exchange ${res.status}: ${(await res.text()).slice(0, 400)}`); |
| 130 | } |
| 131 | return (await res.json()) as TokenResponse; |
| 132 | } |
| 133 | |
| 134 | // In-process access-token cache. Refresh tokens last ~1 year; access tokens |
| 135 | // ~30 days but we re-mint on the cheap side (every 25m) to dodge clock-skew. |
| 136 | let cachedToken: { token: string; expiresAt: number } | null = null; |
| 137 | |
| 138 | async function getAccessToken(): Promise<string> { |
| 139 | // Direct-bearer mode: if PINTEREST_ACCESS_TOKEN is set, use it as-is and |
| 140 | // skip the refresh dance entirely. This is the trial / dev-console path |
| 141 | // — the token comes pre-issued and is not refreshable. |
| 142 | const direct = env.pinterest.accessTokenMaybe(); |
| 143 | if (direct) return direct; |
| 144 | |
| 145 | const now = Date.now(); |
| 146 | if (cachedToken && cachedToken.expiresAt > now + 60_000) return cachedToken.token; |
| 147 | |
| 148 | const refreshToken = await getRefreshTokenForExchange(); |
| 149 | if (!refreshToken) { |
| 150 | throw new Error('Pinterest not connected — visit /admin/pinterest to authorize the app.'); |
| 151 | } |
| 152 | |
| 153 | // Pinterest v5 rejects `scope` on refresh_token grants with code 282 |
| 154 | // "scope unsupported" — scope is only honored on the initial auth_code |
| 155 | // grant. The refresh token already encodes the scopes it was issued for. |
| 156 | const body = new URLSearchParams({ |
| 157 | grant_type: 'refresh_token', |
| 158 | refresh_token: refreshToken, |
| 159 | }); |
| 160 | const res = await fetch(OAUTH_TOKEN, { |
| 161 | method: 'POST', |
| 162 | headers: { |
| 163 | Authorization: basicAuthHeader(), |
| 164 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 165 | }, |
| 166 | body, |
| 167 | }); |
| 168 | if (!res.ok) { |
| 169 | cachedToken = null; |
| 170 | throw new Error(`Pinterest refresh ${res.status}: ${(await res.text()).slice(0, 400)}`); |
| 171 | } |
| 172 | const json = (await res.json()) as TokenResponse; |
| 173 | // expires_in is seconds; cap at 25 minutes for skew safety. |
| 174 | const ttlMs = Math.min(json.expires_in * 1000, 25 * 60 * 1000); |
| 175 | cachedToken = { token: json.access_token, expiresAt: now + ttlMs }; |
| 176 | return cachedToken.token; |
| 177 | } |
| 178 | |
| 179 | /** Authenticated GET/POST against the v5 API, JSON in/out. */ |
| 180 | async function pinterestFetch<T>(path: string, init: RequestInit = {}): Promise<T> { |
| 181 | const token = await getAccessToken(); |
| 182 | const res = await fetch(`${API_BASE}${path}`, { |
| 183 | ...init, |
| 184 | headers: { |
| 185 | ...(init.headers || {}), |
| 186 | Authorization: `Bearer ${token}`, |
| 187 | ...(init.body ? { 'Content-Type': 'application/json' } : {}), |
| 188 | }, |
| 189 | }); |
| 190 | if (!res.ok) { |
| 191 | throw new Error(`Pinterest ${path} ${res.status}: ${(await res.text()).slice(0, 400)}`); |
| 192 | } |
| 193 | return (await res.json()) as T; |
| 194 | } |
| 195 | |
| 196 | export type PinterestBoard = { id: string; name: string; privacy?: string }; |
| 197 | |
| 198 | /** List the studio's boards (paginated, up to 250 — plenty for our use). */ |
| 199 | export async function listBoards(): Promise<PinterestBoard[]> { |
| 200 | type Resp = { items: PinterestBoard[]; bookmark?: string }; |
| 201 | const out: PinterestBoard[] = []; |
| 202 | let bookmark: string | undefined; |
| 203 | for (let guard = 0; guard < 10; guard++) { |
| 204 | const q = new URLSearchParams({ page_size: '100' }); |
| 205 | if (bookmark) q.set('bookmark', bookmark); |
| 206 | const r = await pinterestFetch<Resp>(`/boards?${q.toString()}`); |
| 207 | out.push(...(r.items || [])); |
| 208 | if (!r.bookmark) break; |
| 209 | bookmark = r.bookmark; |
| 210 | } |
| 211 | return out; |
| 212 | } |
| 213 | |
| 214 | export type CreatePinInput = { |
| 215 | boardId: string; |
| 216 | imageUrl: string; |
| 217 | title?: string; // ≤ 100 chars |
| 218 | description?: string; // ≤ 500 chars |
| 219 | link?: string; // outbound link the pin opens |
| 220 | altText?: string; // ≤ 500 chars |
| 221 | }; |
| 222 | |
| 223 | export type CreatedPin = { id: string; url?: string }; |
| 224 | |
| 225 | /** Create a single image pin from a publicly-fetchable URL (CF Images works). */ |
| 226 | export async function createPin(input: CreatePinInput): Promise<CreatedPin> { |
| 227 | const body: Record<string, unknown> = { |
| 228 | board_id: input.boardId, |
| 229 | media_source: { source_type: 'image_url', url: input.imageUrl }, |
| 230 | }; |
| 231 | if (input.title) body.title = input.title.slice(0, 100); |
| 232 | if (input.description) body.description = input.description.slice(0, 500); |
| 233 | if (input.link) body.link = input.link; |
| 234 | if (input.altText) body.alt_text = input.altText.slice(0, 500); |
| 235 | const pin = await pinterestFetch<CreatedPin>('/pins', { |
| 236 | method: 'POST', |
| 237 | body: JSON.stringify(body), |
| 238 | }); |
| 239 | return pin; |
| 240 | } |
| 241 | |
| 242 | /** Status helper used by the /admin/pinterest setup page. Async because |
| 243 | * it needs to query the integrations table for the refresh token. |
| 244 | * `mode`: |
| 245 | * - 'access-token' → direct-bearer env var; client id/secret/refresh ignored. |
| 246 | * - 'oauth' → client id/secret in env + refresh token in DB (or env legacy). |
| 247 | * - 'unconfigured' → neither path is set. |
| 248 | * `ready` is true when the studio can actually call the API. |
| 249 | * `refreshTokenSource` tells the UI where the refresh token currently lives. */ |
| 250 | export async function pinterestSetupStatus(): Promise<{ |
| 251 | mode: 'access-token' | 'oauth' | 'unconfigured'; |
| 252 | ready: boolean; |
| 253 | hasClient: boolean; |
| 254 | hasRefreshToken: boolean; |
| 255 | hasAccessToken: boolean; |
| 256 | refreshTokenSource: 'db' | 'env' | 'none'; |
| 257 | }> { |
| 258 | const hasAccessToken = !!env.pinterest.accessTokenMaybe(); |
| 259 | const hasClient = !!env.pinterest.clientIdMaybe(); |
| 260 | const fromDb = await readRefreshTokenFromDb(); |
| 261 | const refreshTokenSource: 'db' | 'env' | 'none' = fromDb ? 'db' : 'none'; |
| 262 | const hasRefreshToken = refreshTokenSource !== 'none'; |
| 263 | const mode: 'access-token' | 'oauth' | 'unconfigured' = hasAccessToken |
| 264 | ? 'access-token' |
| 265 | : (hasClient && hasRefreshToken ? 'oauth' : 'unconfigured'); |
| 266 | const ready = mode === 'access-token' || mode === 'oauth'; |
| 267 | return { mode, ready, hasClient, hasRefreshToken, hasAccessToken, refreshTokenSource }; |
| 268 | } |