Inkspring / website / server / connect.mjs
| 1 | import { equal, hash, openTicket, publicKey, sealResult, sealTicket, signingPublicKey } from './connect-crypto.mjs'; |
| 2 | const ORIGIN = 'https://inkspring.ai'; |
| 3 | export class ReconnectRequired extends Error { |
| 4 | constructor() { |
| 5 | super('This connection must be authorized again. Open Connections in InkSpring and reconnect the account.'); |
| 6 | } |
| 7 | } |
| 8 | |
| 9 | // Existing native X connections use the official X API and their own developer app. |
| 10 | // This website brokers only these two managed OAuth providers. |
| 11 | export const providers = Object.freeze({ |
| 12 | instagram: { name: 'Instagram', prefix: 'IG_APP', authorize: 'https://www.instagram.com/oauth/authorize', token: 'https://api.instagram.com/oauth/access_token', scope: 'instagram_business_basic,instagram_business_content_publish' }, |
| 13 | linkedin: { name: 'LinkedIn', prefix: 'LINKEDIN_CLIENT', authorize: 'https://www.linkedin.com/oauth/v2/authorization', token: 'https://www.linkedin.com/oauth/v2/accessToken', scope: 'openid profile w_member_social' } |
| 14 | }); |
| 15 | export class RetiredProvider extends Error { |
| 16 | constructor() { |
| 17 | super('This publishing platform is no longer available. Use LinkedIn, X, or Instagram in Inkspring.'); |
| 18 | } |
| 19 | } |
| 20 | export const isRetiredProvider = provider => ['reddit', 'tiktok', 'substack', 'youtube', 'facebook', 'threads', 'bluesky', 'apify'].includes(provider); |
| 21 | function setting(provider, env) { |
| 22 | if (provider === 'x') throw new Error('X requires your own developer app in Inkspring.'); |
| 23 | if (isRetiredProvider(provider)) throw new RetiredProvider(); |
| 24 | if (!Object.hasOwn(providers, provider)) throw new Error('Unsupported social platform.'); |
| 25 | const definition = providers[provider]; |
| 26 | const clientId = env[`${definition.prefix}_ID`]?.trim() || ''; |
| 27 | const clientSecret = env[`${definition.prefix}_SECRET`]?.trim() || ''; |
| 28 | const redirectUri = `${ORIGIN}/api/auth/callback/${provider}`; |
| 29 | return { ...definition, clientId, clientSecret, redirectUri, available: Boolean(env.CONNECT_SECRET?.length >= 64 && clientId && clientSecret) }; |
| 30 | } |
| 31 | function requireSetting(provider, env) { const config = setting(provider, env); if (!config.available) throw new Error(`${config.name} connections are not available yet. Use your own developer app or try again later.`); return config; } |
| 32 | function cookieName(provider) { return `__Host-inkspring-connect-${provider}`; } |
| 33 | function cookie(value, name) { return String(value || '').split(';').map(p => p.trim()).find(p => p.startsWith(name + '='))?.slice(name.length + 1) || ''; } |
| 34 | function nativeState(provider, state) { if (typeof state !== 'string' || !new RegExp(`^${provider}\\.[A-Za-z0-9_-]{40,100}$`).test(state)) throw new Error('Invalid desktop sign-in state.'); return state; } |
| 35 | function text(value, max, label) { if (typeof value !== 'string' || !value.trim() || value.length > max) throw new Error(`Invalid ${label}.`); return value; } |
| 36 | function normalizedTokens(body, previous = {}) { |
| 37 | const data = body?.data?.[0] || body; |
| 38 | const accessToken = text(data?.access_token, 24000, 'platform access token'); |
| 39 | const permissions = data.scope ?? data.permissions; |
| 40 | const scopes = Array.isArray(permissions) |
| 41 | ? permissions.filter(permission => typeof permission === 'string').join(',') |
| 42 | : typeof permissions === 'string' ? permissions : ''; |
| 43 | return { accessToken, refreshToken: typeof data.refresh_token === 'string' ? text(data.refresh_token, 12000, 'refresh token') : previous.refreshToken || '', expiresAt: Date.now() + (Number(data.expires_in) > 0 ? Math.min(Number(data.expires_in), 31536000) : 3600) * 1000, scopes: scopes || previous.scopes || '' }; |
| 44 | } |
| 45 | async function platformRequest(url, options, fetchImpl) { |
| 46 | let response; |
| 47 | try { response = await fetchImpl(url, { ...options, redirect: 'error', signal: AbortSignal.timeout(20000) }); } |
| 48 | catch { throw new Error('The platform could not be reached. Try connecting again.'); } |
| 49 | // Provider errors can include submitted credentials. Never echo their response bodies. |
| 50 | if (!response.ok) throw new Error(`The platform declined the connection request (${response.status}). Reconnect or check the Inkspring app permissions.`); |
| 51 | const body = await response.text(); |
| 52 | if (body.length > 100000) throw new Error('The platform returned an unreadable response.'); |
| 53 | try { return JSON.parse(body); } catch { throw new Error('The platform returned an unreadable response.'); } |
| 54 | } |
| 55 | function tokenRequest(config, values) { |
| 56 | if (config.clientSecret) values.client_secret = config.clientSecret; |
| 57 | return { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(values).toString() }; |
| 58 | } |
| 59 | function refreshTicket(provider, config, session, env) { |
| 60 | return session.refreshToken ? sealTicket({ provider, clientId: config.clientId, tokenHash: hash(session.refreshToken), expiresAt: Date.now() + 90 * 86400000 }, env.CONNECT_SECRET, 'refresh') : ''; |
| 61 | } |
| 62 | export function createConnector({ env = process.env, fetchImpl = fetch } = {}) { |
| 63 | return { |
| 64 | config() { return { version: 1, signingKey: env.CONNECT_SECRET?.length >= 64 ? signingPublicKey(env.CONNECT_SECRET) : '', providers: Object.fromEntries(Object.keys(providers).map(provider => { const config = setting(provider, env); return [provider, { available: config.available, clientId: config.available ? config.clientId : '', redirectUri: config.redirectUri }]; })) }; }, |
| 65 | async start({ provider, state, publicKey: recipient }) { |
| 66 | const config = requireSetting(provider, env); |
| 67 | nativeState(provider, state); publicKey(recipient); |
| 68 | const ticket = await sealTicket({ provider, state, recipient, expiresAt: Date.now() + 600000 }, env.CONNECT_SECRET, 'state'); |
| 69 | const url = new URL(config.authorize); |
| 70 | url.search = new URLSearchParams({ response_type: 'code', client_id: config.clientId, redirect_uri: config.redirectUri, scope: config.scope, state: ticket }).toString(); |
| 71 | if (provider === 'instagram') url.searchParams.set('enable_fb_login', '0'); |
| 72 | return { location: url.href, cookie: `${cookieName(provider)}=${hash(ticket)}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=600` }; |
| 73 | }, |
| 74 | async callback({ provider, state: ticket, code, error, cookie: cookies }) { |
| 75 | const config = requireSetting(provider, env), request = await openTicket(ticket, env.CONNECT_SECRET, 'state'); |
| 76 | if (request.provider !== provider || !equal(cookie(cookies, cookieName(provider)), hash(ticket))) throw new Error('This sign-in belongs to another browser or has expired. Start again from Inkspring.'); |
| 77 | nativeState(provider, request.state); |
| 78 | let payload; |
| 79 | try { |
| 80 | if (error) throw new Error('Sign-in was declined or canceled. Your previous account connection is unchanged.'); |
| 81 | const values = { grant_type: 'authorization_code', client_id: config.clientId, redirect_uri: config.redirectUri, code: text(code, 8000, 'authorization code') }; |
| 82 | let session = normalizedTokens(await platformRequest(config.token, tokenRequest(config, values), fetchImpl)); |
| 83 | if (provider === 'instagram') { |
| 84 | const exchange = new URL('https://graph.instagram.com/access_token'); |
| 85 | exchange.search = new URLSearchParams({ grant_type: 'ig_exchange_token', client_secret: config.clientSecret, access_token: session.accessToken }).toString(); |
| 86 | session = normalizedTokens(await platformRequest(exchange.href, {}, fetchImpl), session); |
| 87 | } |
| 88 | session.managedTicket = await refreshTicket(provider, config, session, env); |
| 89 | payload = { session }; |
| 90 | } catch (failure) { payload = { error: failure.message }; } |
| 91 | const result = await sealResult(request.recipient, { ...payload, provider, state: request.state, expiresAt: Date.now() + 300000 }, env.CONNECT_SECRET); |
| 92 | const destination = new URL(`inkspring://oauth/${provider}`); |
| 93 | destination.searchParams.set('state', request.state); destination.hash = new URLSearchParams({ result }).toString(); |
| 94 | return { location: destination.href, cookie: `${cookieName(provider)}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`, success: !payload.error }; |
| 95 | }, |
| 96 | async refresh({ provider, refreshToken, ticket }) { |
| 97 | const config = requireSetting(provider, env); |
| 98 | text(refreshToken, 12000, 'refresh token'); |
| 99 | let claims; |
| 100 | try { |
| 101 | claims = await openTicket(ticket, env.CONNECT_SECRET, 'refresh'); |
| 102 | } catch { |
| 103 | throw new ReconnectRequired(); |
| 104 | } |
| 105 | if (claims.provider !== provider || claims.clientId !== config.clientId || !equal(claims.tokenHash, hash(refreshToken))) throw new ReconnectRequired(); |
| 106 | const session = normalizedTokens(await platformRequest(config.token, tokenRequest(config, { grant_type: 'refresh_token', client_id: config.clientId, refresh_token: refreshToken }), fetchImpl), { refreshToken }); |
| 107 | return { ...session, managedTicket: await refreshTicket(provider, config, session, env) }; |
| 108 | } |
| 109 | }; |
| 110 | } |
| 111 | export function callbackPage(result) { |
| 112 | const safeLink = result.location.replaceAll('&', '&').replaceAll('"', '"'); |
| 113 | return `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Return to Inkspring</title><style>body{font:16px system-ui;background:#f5f2ec;color:#302f24;max-width:560px;margin:12vh auto;padding:30px;line-height:1.7}a{display:inline-block;background:#3e5144;color:white;padding:12px 20px;border-radius:5px;text-decoration:none}h1{font:38px Georgia}p{color:#6f6b5f}</style><h1>${result.success ? 'Your sign-in is ready.' : 'Return to Inkspring.'}</h1><p>${result.success ? 'Return to the desktop app to finish connecting your account.' : 'Inkspring will show the sign-in result. Your previous connection is preserved.'}</p><a href="${safeLink}">Return to Inkspring</a><p>Your sign-in result is encrypted for the desktop app that started this request.</p></html>`; |
| 114 | } |