also looking at this
feat: crossposting — media (LinkedIn/IG/Threads), OAuth token refresh, and X/Twitter
#30
28 files
+1810
-109
| @@ -1,8 +1,8 @@ | ||
| 1 | 1 | import type { CrosspostTargetResult, PublishContent } from '../../Support/Social/types' |
| 2 | 2 | import { db } from '@stacksjs/database' |
| 3 | 3 | import { env } from '@stacksjs/env' |
| 4 | import { LinkedInApiError, LinkedInDriver } from './Drivers/LinkedInDriver' | |
| 5 | import { ensureAccount, now, uuid } from './support' | |
| 4 | import { TwitterApiError, TwitterDriver } from './Drivers/TwitterDriver' | |
| 5 | import { ensureAccount, expiresAt, isExpiringSoon, now, uuid } from './support' | |
| 6 | 6 | |
| 7 | 7 | const database = db as any |
| 8 | 8 | |
| @@ -10,30 +10,29 @@ type SocialIdentityRow = { | ||
| 10 | 10 | id: number |
| 11 | 11 | handle: string |
| 12 | 12 | display_name?: string | null |
| 13 | provider: 'linkedin' | |
| 13 | provider: 'twitter' | |
| 14 | 14 | external_id?: string | null |
| 15 | 15 | auth_status: 'connected' | 'expired' | 'revoked' | 'missing' |
| 16 | 16 | access_token?: string | null |
| 17 | 17 | refresh_token?: string | null |
| 18 | token_expires_at?: string | null | |
| 18 | 19 | account_id?: number | null |
| 19 | 20 | social_driver_id?: number | null |
| 20 | 21 | } |
| 21 | 22 | |
| 22 | 23 | type SocialDriverRow = { |
| 23 | 24 | id: number |
| 24 | provider: 'linkedin' | |
| 25 | provider: 'twitter' | |
| 25 | 26 | display_name: string |
| 26 | 27 | status: 'active' | 'planned' | 'disabled' |
| 27 | 28 | character_limit: number |
| 28 | 29 | } |
| 29 | 30 | |
| 30 | interface LinkedInConfig { | |
| 31 | interface TwitterConfig { | |
| 31 | 32 | clientId: string |
| 32 | 33 | clientSecret: string |
| 33 | 34 | redirectUrl: string |
| 34 | apiVersion: string | |
| 35 | 35 | accessToken: string |
| 36 | authorUrn: string | |
| 37 | 36 | scopes: string[] |
| 38 | 37 | } |
| 39 | 38 | |
| @@ -43,25 +42,20 @@ function randomState(): string { | ||
| 43 | 42 | return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('') |
| 44 | 43 | } |
| 45 | 44 | |
| 46 | export class LinkedInService { | |
| 47 | private driver: LinkedInDriver | |
| 48 | // OAuth CSRF token stashed between the auth redirect and the callback. | |
| 49 | // Postline runs single-user, so module memory is an adequate store. | |
| 45 | export class TwitterService { | |
| 46 | private driver = new TwitterDriver() | |
| 47 | // OAuth CSRF token + PKCE verifier stashed between the auth redirect and the | |
| 48 | // callback. Postline runs single-user, so module memory is an adequate store. | |
| 50 | 49 | private pendingState: string | null = null |
| 50 | private pendingVerifier: string | null = null | |
| 51 | 51 | |
| 52 | constructor() { | |
| 53 | this.driver = new LinkedInDriver({ apiVersion: this.config().apiVersion }) | |
| 54 | } | |
| 55 | ||
| 56 | private config(): LinkedInConfig { | |
| 52 | private config(): TwitterConfig { | |
| 57 | 53 | return { |
| 58 | clientId: String(env.LINKEDIN_CLIENT_ID || '').trim(), | |
| 59 | clientSecret: String(env.LINKEDIN_CLIENT_SECRET || '').trim(), | |
| 60 | redirectUrl: String(env.LINKEDIN_REDIRECT_URL || '').trim(), | |
| 61 | apiVersion: String(env.LINKEDIN_API_VERSION || '202405').trim(), | |
| 62 | accessToken: String(env.LINKEDIN_ACCESS_TOKEN || '').trim(), | |
| 63 | authorUrn: String(env.LINKEDIN_AUTHOR_URN || '').trim(), | |
| 64 | scopes: ['openid', 'profile', 'w_member_social'], | |
| 54 | clientId: String(env.TWITTER_CLIENT_ID || '').trim(), | |
| 55 | clientSecret: String(env.TWITTER_CLIENT_SECRET || '').trim(), | |
| 56 | redirectUrl: String(env.TWITTER_REDIRECT_URL || '').trim(), | |
| 57 | accessToken: String(env.TWITTER_ACCESS_TOKEN || '').trim(), | |
| 58 | scopes: ['tweet.read', 'tweet.write', 'users.read', 'offline.access'], | |
| 65 | 59 | } |
| 66 | 60 | } |
| 67 | 61 | |
| @@ -72,7 +66,7 @@ export class LinkedInService { | ||
| 72 | 66 | |
| 73 | 67 | return { |
| 74 | 68 | connected, |
| 75 | provider: 'linkedin', | |
| 69 | provider: 'twitter', | |
| 76 | 70 | handle: identity?.handle || null, |
| 77 | 71 | displayName: identity?.display_name || null, |
| 78 | 72 | did: identity?.external_id || null, |
| @@ -80,53 +74,55 @@ export class LinkedInService { | ||
| 80 | 74 | characterLimit: this.driver.characterLimit, |
| 81 | 75 | canPublish: connected, |
| 82 | 76 | configuredFromEnv: Boolean(cfg.accessToken), |
| 83 | oauthConfigured: Boolean(cfg.clientId && cfg.clientSecret && cfg.redirectUrl), | |
| 77 | oauthConfigured: Boolean(cfg.clientId && cfg.redirectUrl), | |
| 84 | 78 | } |
| 85 | 79 | } |
| 86 | 80 | |
| 87 | /** Build the LinkedIn consent URL and remember the CSRF state. */ | |
| 88 | getAuthUrl(): string { | |
| 81 | /** Build the X consent URL (with PKCE) and remember the CSRF state + verifier. */ | |
| 82 | async getAuthUrl(): Promise<string> { | |
| 89 | 83 | const cfg = this.config() |
| 90 | if (!cfg.clientId || !cfg.clientSecret) { | |
| 91 | throw new Error('Set LINKEDIN_CLIENT_ID and LINKEDIN_CLIENT_SECRET to connect with LinkedIn.') | |
| 92 | } | |
| 93 | if (!cfg.redirectUrl) { | |
| 94 | throw new Error('Set LINKEDIN_REDIRECT_URL to connect with LinkedIn.') | |
| 95 | } | |
| 84 | if (!cfg.clientId) throw new Error('Set TWITTER_CLIENT_ID to connect X/Twitter.') | |
| 85 | if (!cfg.redirectUrl) throw new Error('Set TWITTER_REDIRECT_URL to connect X/Twitter.') | |
| 96 | 86 | |
| 97 | 87 | this.pendingState = randomState() |
| 98 | return this.driver.getAuthUrl({ | |
| 88 | const { url, codeVerifier } = await this.driver.createAuthorization({ | |
| 99 | 89 | clientId: cfg.clientId, |
| 100 | 90 | redirectUrl: cfg.redirectUrl, |
| 101 | 91 | scopes: cfg.scopes, |
| 102 | 92 | state: this.pendingState, |
| 103 | 93 | }) |
| 94 | this.pendingVerifier = codeVerifier | |
| 95 | return url | |
| 104 | 96 | } |
| 105 | 97 | |
| 106 | /** Handle the OAuth redirect: exchange the code and store the token. */ | |
| 98 | /** Handle the OAuth redirect: exchange the code and store the tokens. */ | |
| 107 | 99 | async handleCallback(code: string, state: string) { |
| 108 | 100 | const cfg = this.config() |
| 109 | if (!code) throw new Error('LinkedIn did not return an authorization code.') | |
| 101 | if (!code) throw new Error('X/Twitter did not return an authorization code.') | |
| 110 | 102 | if (this.pendingState && state !== this.pendingState) { |
| 111 | throw new Error('LinkedIn OAuth state mismatch. Please start the connection again.') | |
| 103 | throw new Error('X/Twitter OAuth state mismatch. Please start the connection again.') | |
| 112 | 104 | } |
| 105 | const codeVerifier = this.pendingVerifier | |
| 106 | if (!codeVerifier) throw new Error('Missing PKCE verifier — please start the X/Twitter connection again.') | |
| 113 | 107 | this.pendingState = null |
| 108 | this.pendingVerifier = null | |
| 114 | 109 | |
| 115 | 110 | const token = await this.driver.exchangeCode({ |
| 116 | 111 | clientId: cfg.clientId, |
| 117 | clientSecret: cfg.clientSecret, | |
| 112 | clientSecret: cfg.clientSecret || undefined, | |
| 118 | 113 | redirectUrl: cfg.redirectUrl, |
| 119 | 114 | code, |
| 115 | codeVerifier, | |
| 120 | 116 | }) |
| 121 | 117 | |
| 122 | const profile = await this.driver.getProfile(token.accessToken).catch(() => undefined) | |
| 123 | const authorUrn = profile?.sub ? `urn:li:person:${profile.sub}` : cfg.authorUrn | |
| 124 | if (!authorUrn) throw new Error('Could not resolve your LinkedIn member URN.') | |
| 125 | ||
| 118 | const profile = await this.driver.getProfile(token.accessToken) | |
| 126 | 119 | const identity = await this.saveSession({ |
| 127 | 120 | accessToken: token.accessToken, |
| 128 | authorUrn, | |
| 129 | name: profile?.name, | |
| 121 | refreshToken: token.refreshToken, | |
| 122 | expiresIn: token.expiresIn, | |
| 123 | userId: profile.id, | |
| 124 | username: profile.username, | |
| 125 | name: profile.name, | |
| 130 | 126 | }) |
| 131 | 127 | return this.publicIdentity(identity) |
| 132 | 128 | } |
| @@ -135,25 +131,23 @@ export class LinkedInService { | ||
| 135 | 131 | async connectFromEnv() { |
| 136 | 132 | const cfg = this.config() |
| 137 | 133 | if (!cfg.accessToken) { |
| 138 | throw new Error('Set LINKEDIN_ACCESS_TOKEN (or connect via OAuth) before using LinkedIn.') | |
| 134 | throw new Error('Set TWITTER_ACCESS_TOKEN (or connect via OAuth) before using X/Twitter.') | |
| 139 | 135 | } |
| 140 | 136 | |
| 141 | let authorUrn = cfg.authorUrn | |
| 142 | let name: string | undefined | |
| 143 | if (!authorUrn) { | |
| 144 | const profile = await this.driver.getProfile(cfg.accessToken) | |
| 145 | authorUrn = `urn:li:person:${profile.sub}` | |
| 146 | name = profile.name | |
| 147 | } | |
| 148 | ||
| 149 | const identity = await this.saveSession({ accessToken: cfg.accessToken, authorUrn, name }) | |
| 137 | const profile = await this.driver.getProfile(cfg.accessToken) | |
| 138 | const identity = await this.saveSession({ | |
| 139 | accessToken: cfg.accessToken, | |
| 140 | userId: profile.id, | |
| 141 | username: profile.username, | |
| 142 | name: profile.name, | |
| 143 | }) | |
| 150 | 144 | return this.publicIdentity(identity) |
| 151 | 145 | } |
| 152 | 146 | |
| 153 | 147 | /** |
| 154 | * Publish an already-created post row to LinkedIn as a new target. Never | |
| 155 | * throws — failures are recorded on the target and returned so a crosspost | |
| 156 | * to other providers can still succeed. | |
| 148 | * Publish an already-created post row to X/Twitter. Never throws — failures | |
| 149 | * are recorded on the target and returned so a crosspost to other providers | |
| 150 | * can still succeed. | |
| 157 | 151 | */ |
| 158 | 152 | async publishToPost( |
| 159 | 153 | post: { id: number, body: string }, |
| @@ -166,14 +160,14 @@ export class LinkedInService { | ||
| 166 | 160 | identity = await this.requireIdentity() |
| 167 | 161 | } |
| 168 | 162 | catch (error) { |
| 169 | return { provider: 'linkedin', ok: false, error: messageOf(error) } | |
| 163 | return { provider: 'twitter', ok: false, error: messageOf(error) } | |
| 170 | 164 | } |
| 171 | 165 | |
| 172 | 166 | if (post.body.length > this.driver.characterLimit) { |
| 173 | 167 | return { |
| 174 | provider: 'linkedin', | |
| 168 | provider: 'twitter', | |
| 175 | 169 | ok: false, |
| 176 | error: `LinkedIn posts must be ${this.driver.characterLimit} characters or fewer.`, | |
| 170 | error: `Twitter posts must be ${this.driver.characterLimit} characters or fewer.`, | |
| 177 | 171 | } |
| 178 | 172 | } |
| 179 | 173 | |
| @@ -181,7 +175,7 @@ export class LinkedInService { | ||
| 181 | 175 | const createdAt = now() |
| 182 | 176 | await database.insertInto('post_targets').values({ |
| 183 | 177 | uuid: targetUuid, |
| 184 | provider: 'linkedin', | |
| 178 | provider: 'twitter', | |
| 185 | 179 | status: 'publishing', |
| 186 | 180 | post_id: post.id, |
| 187 | 181 | social_driver_id: driver.id, |
| @@ -203,27 +197,30 @@ export class LinkedInService { | ||
| 203 | 197 | accessToken: identity.access_token || undefined, |
| 204 | 198 | }, { |
| 205 | 199 | text: post.body, |
| 206 | ...(content?.external ? { external: content.external } : {}), | |
| 200 | ...(content?.media?.length ? { media: content.media } : {}), | |
| 201 | ...(content?.reply ? { reply: content.reply } : {}), | |
| 207 | 202 | }) |
| 208 | 203 | |
| 209 | 204 | await database.updateTable('post_targets').set({ |
| 210 | 205 | status: 'published', |
| 211 | 206 | remote_uri: published.uri || null, |
| 207 | remote_cid: published.cid || null, | |
| 212 | 208 | failure_reason: null, |
| 213 | 209 | updated_at: now(), |
| 214 | 210 | }).where('id', '=', target.id).execute() |
| 215 | 211 | |
| 216 | 212 | return { |
| 217 | provider: 'linkedin', | |
| 213 | provider: 'twitter', | |
| 218 | 214 | ok: true, |
| 219 | 215 | url: published.url, |
| 220 | 216 | uri: published.uri, |
| 217 | cid: published.cid, | |
| 221 | 218 | targetId: Number(target.id), |
| 222 | 219 | } |
| 223 | 220 | } |
| 224 | 221 | catch (error) { |
| 225 | 222 | const message = messageOf(error) |
| 226 | if (error instanceof LinkedInApiError && error.isAuthError) { | |
| 223 | if (error instanceof TwitterApiError && error.isAuthError) { | |
| 227 | 224 | await this.markExpired(identity.id) |
| 228 | 225 | } |
| 229 | 226 | await database.updateTable('post_targets').set({ |
| @@ -232,48 +229,84 @@ export class LinkedInService { | ||
| 232 | 229 | updated_at: now(), |
| 233 | 230 | }).where('id', '=', target.id).execute() |
| 234 | 231 | |
| 235 | return { provider: 'linkedin', ok: false, error: message, targetId: Number(target.id) } | |
| 232 | return { provider: 'twitter', ok: false, error: message, targetId: Number(target.id) } | |
| 236 | 233 | } |
| 237 | 234 | } |
| 238 | 235 | |
| 239 | 236 | private async requireIdentity(): Promise<SocialIdentityRow> { |
| 240 | 237 | const existing = await this.findIdentity() |
| 241 | if (existing?.access_token && existing.auth_status === 'connected') return existing | |
| 238 | if (existing?.access_token && existing.auth_status === 'connected') { | |
| 239 | return await this.refreshIfExpiring(existing) | |
| 240 | } | |
| 242 | 241 | |
| 243 | // Fall back to an env-configured token if one is available. | |
| 244 | 242 | if (this.config().accessToken) { |
| 245 | 243 | await this.connectFromEnv() |
| 246 | 244 | const connected = await this.findIdentity() |
| 247 | 245 | if (connected?.access_token) return connected |
| 248 | 246 | } |
| 249 | 247 | |
| 250 | throw new Error('Connect LinkedIn before publishing.') | |
| 248 | throw new Error('Connect X/Twitter before publishing.') | |
| 249 | } | |
| 250 | ||
| 251 | /** | |
| 252 | * Refresh the access token when it's within its pre-expiry window and a | |
| 253 | * refresh token is on file (present when connected with the `offline.access` | |
| 254 | * scope). Best-effort: any failure leaves the current token in place so a real | |
| 255 | * auth failure still surfaces at publish time. | |
| 256 | */ | |
| 257 | private async refreshIfExpiring(identity: SocialIdentityRow): Promise<SocialIdentityRow> { | |
| 258 | const cfg = this.config() | |
| 259 | if (!identity.refresh_token || !isExpiringSoon(identity.token_expires_at)) return identity | |
| 260 | if (!cfg.clientId) return identity | |
| 261 | ||
| 262 | try { | |
| 263 | const refreshed = await this.driver.refreshAccessToken({ | |
| 264 | clientId: cfg.clientId, | |
| 265 | clientSecret: cfg.clientSecret || undefined, | |
| 266 | refreshToken: identity.refresh_token, | |
| 267 | }) | |
| 268 | const nextExpiry = expiresAt(refreshed.expiresIn) | |
| 269 | // X rotates the refresh token on every refresh — always keep the new one. | |
| 270 | const nextRefresh = refreshed.refreshToken ?? identity.refresh_token | |
| 271 | await database.updateTable('social_identities').set({ | |
| 272 | access_token: refreshed.accessToken, | |
| 273 | refresh_token: nextRefresh, | |
| 274 | token_expires_at: nextExpiry, | |
| 275 | auth_status: 'connected', | |
| 276 | updated_at: now(), | |
| 277 | }).where('id', '=', identity.id).execute() | |
| 278 | ||
| 279 | return { ...identity, access_token: refreshed.accessToken, refresh_token: nextRefresh, token_expires_at: nextExpiry } | |
| 280 | } | |
| 281 | catch { | |
| 282 | return identity | |
| 283 | } | |
| 251 | 284 | } |
| 252 | 285 | |
| 253 | 286 | private async findIdentity(): Promise<SocialIdentityRow | undefined> { |
| 254 | 287 | return await database |
| 255 | 288 | .selectFrom('social_identities') |
| 256 | 289 | .selectAll() |
| 257 | .where('provider', '=', 'linkedin') | |
| 290 | .where('provider', '=', 'twitter') | |
| 258 | 291 | .orderBy('updated_at', 'desc') |
| 259 | 292 | .executeTakeFirst() |
| 260 | 293 | } |
| 261 | 294 | |
| 262 | private async saveSession(input: { accessToken: string, authorUrn: string, name?: string }): Promise<SocialIdentityRow> { | |
| 295 | private async saveSession(input: { accessToken: string, refreshToken?: string, expiresIn?: number, userId: string, username: string, name?: string }): Promise<SocialIdentityRow> { | |
| 263 | 296 | const accountId = await ensureAccount() |
| 264 | 297 | const driver = await this.ensureDriver() |
| 265 | 298 | const existing = await this.findIdentity() |
| 266 | 299 | const savedAt = now() |
| 267 | const handle = (input.name || input.authorUrn.replace('urn:li:person:', '')).trim() | |
| 268 | 300 | |
| 269 | 301 | const values = { |
| 270 | handle, | |
| 271 | display_name: input.name || null, | |
| 272 | provider: 'linkedin', | |
| 273 | external_id: input.authorUrn, | |
| 302 | handle: input.username, | |
| 303 | display_name: input.name || input.username, | |
| 304 | provider: 'twitter', | |
| 305 | external_id: input.userId, | |
| 274 | 306 | auth_status: 'connected', |
| 275 | 307 | access_token: input.accessToken, |
| 276 | refresh_token: null, | |
| 308 | refresh_token: input.refreshToken ?? null, | |
| 309 | token_expires_at: expiresAt(input.expiresIn), | |
| 277 | 310 | account_id: accountId, |
| 278 | 311 | social_driver_id: driver.id, |
| 279 | 312 | updated_at: savedAt, |
| @@ -304,7 +337,7 @@ export class LinkedInService { | ||
| 304 | 337 | const existing = await database |
| 305 | 338 | .selectFrom('social_drivers') |
| 306 | 339 | .selectAll() |
| 307 | .where('provider', '=', 'linkedin') | |
| 340 | .where('provider', '=', 'twitter') | |
| 308 | 341 | .executeTakeFirst() |
| 309 | 342 | |
| 310 | 343 | if (existing) { |
| @@ -326,8 +359,8 @@ export class LinkedInService { | ||
| 326 | 359 | const driverUuid = uuid() |
| 327 | 360 | await database.insertInto('social_drivers').values({ |
| 328 | 361 | uuid: driverUuid, |
| 329 | provider: 'linkedin', | |
| 330 | display_name: 'LinkedIn', | |
| 362 | provider: 'twitter', | |
| 363 | display_name: 'X (Twitter)', | |
| 331 | 364 | status: 'active', |
| 332 | 365 | character_limit: this.driver.characterLimit, |
| 333 | 366 | capabilities: JSON.stringify({ posts: true, timelines: false, oauth: true }), |
| @@ -346,7 +379,7 @@ export class LinkedInService { | ||
| 346 | 379 | if (!row) { |
| 347 | 380 | return { |
| 348 | 381 | connected: false, |
| 349 | provider: 'linkedin', | |
| 382 | provider: 'twitter', | |
| 350 | 383 | handle: null, |
| 351 | 384 | displayName: null, |
| 352 | 385 | did: null, |
| @@ -357,7 +390,7 @@ export class LinkedInService { | ||
| 357 | 390 | const connected = row.auth_status === 'connected' && Boolean(row.access_token) |
| 358 | 391 | return { |
| 359 | 392 | connected, |
| 360 | provider: 'linkedin', | |
| 393 | provider: 'twitter', | |
| 361 | 394 | handle: row.handle, |
| 362 | 395 | displayName: row.display_name || null, |
| 363 | 396 | did: row.external_id || null, |
| @@ -370,4 +403,4 @@ function messageOf(error: unknown): string { | ||
| 370 | 403 | return error instanceof Error ? error.message : String(error) |
| 371 | 404 | } |
| 372 | 405 | |
| 373 | export const linkedin = new LinkedInService() | |
| 406 | export const twitter = new TwitterService() | |