import 'server-only'; import { env } from './env'; import { commerceDb } from './commerce-db'; // Key used to store the refresh token in the `integrations` table. const RTK_KEY = 'pinterest:refresh_token'; /** Read the refresh token from the DB (`integrations` table). Returns null * if missing or unreadable. Reads via the service-role client; the * integrations table has RLS on with no policies, so only this path can * touch it. */ async function readRefreshTokenFromDb(): Promise { try { const { data, error } = await commerceDb() .from('integrations') .select('value') .eq('key', RTK_KEY) .maybeSingle(); if (error || !data) return null; return (data.value as string) || null; } catch { return null; } } /** Upsert the refresh token to the DB. Called by the OAuth callback so the * studio doesn't have to copy/paste it into env and restart. */ export async function saveRefreshToken(token: string): Promise { const { error } = await commerceDb() .from('integrations') .upsert({ key: RTK_KEY, value: token }, { onConflict: 'key' }); if (error) throw new Error(`save refresh token: ${error.message}`); // Invalidate the in-process access-token cache so the next call mints a // fresh one with the new refresh token. cachedToken = null; } /** Delete the stored refresh token. Called by /api/admin/pinterest/disconnect. */ export async function clearRefreshToken(): Promise { const { error } = await commerceDb() .from('integrations') .delete() .eq('key', RTK_KEY); if (error) throw new Error(`clear refresh token: ${error.message}`); cachedToken = null; } /** Resolve the refresh token to use for token exchange. DB is the single * source of truth — set by the OAuth callback, cleared by Disconnect. * (PINTEREST_REFRESH_TOKEN env was a legacy migration fallback; it was * removed because it made Disconnect a no-op when env still had a value.) */ async function getRefreshTokenForExchange(): Promise { return await readRefreshTokenFromDb(); } // Thin client for Pinterest API v5. Designed for a SINGLE Pinterest account // (the studio's @lumengesso). We store a long-lived refresh token in env // and mint short-lived access tokens on demand, caching them in-process. // // Docs: https://developers.pinterest.com/docs/api/v5/ // Scopes we use: pins:read, pins:write, boards:read const API_BASE = 'https://api.pinterest.com/v5'; const OAUTH_AUTHORIZE = 'https://www.pinterest.com/oauth/'; const OAUTH_TOKEN = `${API_BASE}/oauth/token`; // `boards:write` is required by /v5/pins even though we're not creating // boards — Pinterest treats writing TO a board as a "boards:write" action. // Confirmed empirically: a token with pins:write but not boards:write 401s // with `Missing: ['boards:write', 'pins:write']` from POST /v5/pins. export const PINTEREST_SCOPES = [ 'pins:read', 'pins:write', 'boards:read', 'boards:write', ] as const; /** Callback URL Pinterest redirects to after the user grants access. Must * exactly match a redirect URI registered on the app in the Pinterest * dev portal (per environment — dev usually points at the ngrok URL). */ export function callbackUrl(): string { // env.site.url() defaults to http://localhost:3000; .env.local sets it to // https://lumengesso.ngrok.app, prod sets it to https://www.lumengesso.com. return `${env.site.url().replace(/\/$/, '')}/api/admin/pinterest/callback`; } /** URL to redirect the admin to in order to start the OAuth handshake. */ export function authorizeUrl(state: string): string { const u = new URL(OAUTH_AUTHORIZE); u.searchParams.set('client_id', env.pinterest.clientId()); u.searchParams.set('redirect_uri', callbackUrl()); u.searchParams.set('response_type', 'code'); u.searchParams.set('scope', PINTEREST_SCOPES.join(',')); u.searchParams.set('state', state); return u.toString(); } type TokenResponse = { access_token: string; refresh_token?: string; token_type: string; expires_in: number; refresh_token_expires_in?: number; scope: string; }; function basicAuthHeader(): string { const creds = `${env.pinterest.clientId()}:${env.pinterest.clientSecret()}`; return `Basic ${Buffer.from(creds, 'utf8').toString('base64')}`; } /** Exchange the one-time auth `code` returned by Pinterest for an access + * refresh token pair. Called from the OAuth callback route. */ export async function exchangeCodeForTokens(code: string): Promise { const body = new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: callbackUrl(), }); const res = await fetch(OAUTH_TOKEN, { method: 'POST', headers: { Authorization: basicAuthHeader(), 'Content-Type': 'application/x-www-form-urlencoded', }, body, }); if (!res.ok) { throw new Error(`Pinterest token exchange ${res.status}: ${(await res.text()).slice(0, 400)}`); } return (await res.json()) as TokenResponse; } // In-process access-token cache. Refresh tokens last ~1 year; access tokens // ~30 days but we re-mint on the cheap side (every 25m) to dodge clock-skew. let cachedToken: { token: string; expiresAt: number } | null = null; async function getAccessToken(): Promise { // Direct-bearer mode: if PINTEREST_ACCESS_TOKEN is set, use it as-is and // skip the refresh dance entirely. This is the trial / dev-console path // — the token comes pre-issued and is not refreshable. const direct = env.pinterest.accessTokenMaybe(); if (direct) return direct; const now = Date.now(); if (cachedToken && cachedToken.expiresAt > now + 60_000) return cachedToken.token; const refreshToken = await getRefreshTokenForExchange(); if (!refreshToken) { throw new Error('Pinterest not connected — visit /admin/pinterest to authorize the app.'); } // Pinterest v5 rejects `scope` on refresh_token grants with code 282 // "scope unsupported" — scope is only honored on the initial auth_code // grant. The refresh token already encodes the scopes it was issued for. const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, }); const res = await fetch(OAUTH_TOKEN, { method: 'POST', headers: { Authorization: basicAuthHeader(), 'Content-Type': 'application/x-www-form-urlencoded', }, body, }); if (!res.ok) { cachedToken = null; throw new Error(`Pinterest refresh ${res.status}: ${(await res.text()).slice(0, 400)}`); } const json = (await res.json()) as TokenResponse; // expires_in is seconds; cap at 25 minutes for skew safety. const ttlMs = Math.min(json.expires_in * 1000, 25 * 60 * 1000); cachedToken = { token: json.access_token, expiresAt: now + ttlMs }; return cachedToken.token; } /** Authenticated GET/POST against the v5 API, JSON in/out. */ async function pinterestFetch(path: string, init: RequestInit = {}): Promise { const token = await getAccessToken(); const res = await fetch(`${API_BASE}${path}`, { ...init, headers: { ...(init.headers || {}), Authorization: `Bearer ${token}`, ...(init.body ? { 'Content-Type': 'application/json' } : {}), }, }); if (!res.ok) { throw new Error(`Pinterest ${path} ${res.status}: ${(await res.text()).slice(0, 400)}`); } return (await res.json()) as T; } export type PinterestBoard = { id: string; name: string; privacy?: string }; /** List the studio's boards (paginated, up to 250 — plenty for our use). */ export async function listBoards(): Promise { type Resp = { items: PinterestBoard[]; bookmark?: string }; const out: PinterestBoard[] = []; let bookmark: string | undefined; for (let guard = 0; guard < 10; guard++) { const q = new URLSearchParams({ page_size: '100' }); if (bookmark) q.set('bookmark', bookmark); const r = await pinterestFetch(`/boards?${q.toString()}`); out.push(...(r.items || [])); if (!r.bookmark) break; bookmark = r.bookmark; } return out; } export type CreatePinInput = { boardId: string; imageUrl: string; title?: string; // ≤ 100 chars description?: string; // ≤ 500 chars link?: string; // outbound link the pin opens altText?: string; // ≤ 500 chars }; export type CreatedPin = { id: string; url?: string }; /** Create a single image pin from a publicly-fetchable URL (CF Images works). */ export async function createPin(input: CreatePinInput): Promise { const body: Record = { board_id: input.boardId, media_source: { source_type: 'image_url', url: input.imageUrl }, }; if (input.title) body.title = input.title.slice(0, 100); if (input.description) body.description = input.description.slice(0, 500); if (input.link) body.link = input.link; if (input.altText) body.alt_text = input.altText.slice(0, 500); const pin = await pinterestFetch('/pins', { method: 'POST', body: JSON.stringify(body), }); return pin; } /** Status helper used by the /admin/pinterest setup page. Async because * it needs to query the integrations table for the refresh token. * `mode`: * - 'access-token' → direct-bearer env var; client id/secret/refresh ignored. * - 'oauth' → client id/secret in env + refresh token in DB (or env legacy). * - 'unconfigured' → neither path is set. * `ready` is true when the studio can actually call the API. * `refreshTokenSource` tells the UI where the refresh token currently lives. */ export async function pinterestSetupStatus(): Promise<{ mode: 'access-token' | 'oauth' | 'unconfigured'; ready: boolean; hasClient: boolean; hasRefreshToken: boolean; hasAccessToken: boolean; refreshTokenSource: 'db' | 'env' | 'none'; }> { const hasAccessToken = !!env.pinterest.accessTokenMaybe(); const hasClient = !!env.pinterest.clientIdMaybe(); const fromDb = await readRefreshTokenFromDb(); const refreshTokenSource: 'db' | 'env' | 'none' = fromDb ? 'db' : 'none'; const hasRefreshToken = refreshTokenSource !== 'none'; const mode: 'access-token' | 'oauth' | 'unconfigured' = hasAccessToken ? 'access-token' : (hasClient && hasRefreshToken ? 'oauth' : 'unconfigured'); const ready = mode === 'access-token' || mode === 'oauth'; return { mode, ready, hasClient, hasRefreshToken, hasAccessToken, refreshTokenSource }; }