also looking at this
feat: crosspost to LinkedIn and Instagram
#1
31 files
+2335
-87
| @@ -0,0 +1,373 @@ | ||
| 1 | import type { CrosspostTargetResult, PublishContent } from '../../Support/Social/types' | |
| 2 | import { db } from '@stacksjs/database' | |
| 3 | import { env } from '@stacksjs/env' | |
| 4 | import { LinkedInApiError, LinkedInDriver } from './Drivers/LinkedInDriver' | |
| 5 | import { ensureAccount, now, uuid } from './support' | |
| 6 | ||
| 7 | const database = db as any | |
| 8 | ||
| 9 | type SocialIdentityRow = { | |
| 10 | id: number | |
| 11 | handle: string | |
| 12 | display_name?: string | null | |
| 13 | provider: 'linkedin' | |
| 14 | external_id?: string | null | |
| 15 | auth_status: 'connected' | 'expired' | 'revoked' | 'missing' | |
| 16 | access_token?: string | null | |
| 17 | refresh_token?: string | null | |
| 18 | account_id?: number | null | |
| 19 | social_driver_id?: number | null | |
| 20 | } | |
| 21 | ||
| 22 | type SocialDriverRow = { | |
| 23 | id: number | |
| 24 | provider: 'linkedin' | |
| 25 | display_name: string | |
| 26 | status: 'active' | 'planned' | 'disabled' | |
| 27 | character_limit: number | |
| 28 | } | |
| 29 | ||
| 30 | interface LinkedInConfig { | |
| 31 | clientId: string | |
| 32 | clientSecret: string | |
| 33 | redirectUrl: string | |
| 34 | apiVersion: string | |
| 35 | accessToken: string | |
| 36 | authorUrn: string | |
| 37 | scopes: string[] | |
| 38 | } | |
| 39 | ||
| 40 | function randomState(): string { | |
| 41 | const bytes = new Uint8Array(24) | |
| 42 | crypto.getRandomValues(bytes) | |
| 43 | return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('') | |
| 44 | } | |
| 45 | ||
| 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. | |
| 50 | private pendingState: string | null = null | |
| 51 | ||
| 52 | constructor() { | |
| 53 | this.driver = new LinkedInDriver({ apiVersion: this.config().apiVersion }) | |
| 54 | } | |
| 55 | ||
| 56 | private config(): LinkedInConfig { | |
| 57 | 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'], | |
| 65 | } | |
| 66 | } | |
| 67 | ||
| 68 | async status() { | |
| 69 | const identity = await this.findIdentity() | |
| 70 | const cfg = this.config() | |
| 71 | const connected = identity?.auth_status === 'connected' && Boolean(identity.access_token) | |
| 72 | ||
| 73 | return { | |
| 74 | connected, | |
| 75 | provider: 'linkedin', | |
| 76 | handle: identity?.handle || null, | |
| 77 | displayName: identity?.display_name || null, | |
| 78 | did: identity?.external_id || null, | |
| 79 | authStatus: connected ? 'connected' : (identity?.handle ? identity.auth_status : 'missing'), | |
| 80 | characterLimit: this.driver.characterLimit, | |
| 81 | canPublish: connected, | |
| 82 | configuredFromEnv: Boolean(cfg.accessToken), | |
| 83 | oauthConfigured: Boolean(cfg.clientId && cfg.clientSecret && cfg.redirectUrl), | |
| 84 | } | |
| 85 | } | |
| 86 | ||
| 87 | /** Build the LinkedIn consent URL and remember the CSRF state. */ | |
| 88 | getAuthUrl(): string { | |
| 89 | 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 | } | |
| 96 | ||
| 97 | this.pendingState = randomState() | |
| 98 | return this.driver.getAuthUrl({ | |
| 99 | clientId: cfg.clientId, | |
| 100 | redirectUrl: cfg.redirectUrl, | |
| 101 | scopes: cfg.scopes, | |
| 102 | state: this.pendingState, | |
| 103 | }) | |
| 104 | } | |
| 105 | ||
| 106 | /** Handle the OAuth redirect: exchange the code and store the token. */ | |
| 107 | async handleCallback(code: string, state: string) { | |
| 108 | const cfg = this.config() | |
| 109 | if (!code) throw new Error('LinkedIn did not return an authorization code.') | |
| 110 | if (this.pendingState && state !== this.pendingState) { | |
| 111 | throw new Error('LinkedIn OAuth state mismatch. Please start the connection again.') | |
| 112 | } | |
| 113 | this.pendingState = null | |
| 114 | ||
| 115 | const token = await this.driver.exchangeCode({ | |
| 116 | clientId: cfg.clientId, | |
| 117 | clientSecret: cfg.clientSecret, | |
| 118 | redirectUrl: cfg.redirectUrl, | |
| 119 | code, | |
| 120 | }) | |
| 121 | ||
| 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 | ||
| 126 | const identity = await this.saveSession({ | |
| 127 | accessToken: token.accessToken, | |
| 128 | authorUrn, | |
| 129 | name: profile?.name, | |
| 130 | }) | |
| 131 | return this.publicIdentity(identity) | |
| 132 | } | |
| 133 | ||
| 134 | /** Connect using a pre-obtained token from the environment. */ | |
| 135 | async connectFromEnv() { | |
| 136 | const cfg = this.config() | |
| 137 | if (!cfg.accessToken) { | |
| 138 | throw new Error('Set LINKEDIN_ACCESS_TOKEN (or connect via OAuth) before using LinkedIn.') | |
| 139 | } | |
| 140 | ||
| 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 }) | |
| 150 | return this.publicIdentity(identity) | |
| 151 | } | |
| 152 | ||
| 153 | /** | |
| 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. | |
| 157 | */ | |
| 158 | async publishToPost( | |
| 159 | post: { id: number, body: string }, | |
| 160 | content?: PublishContent, | |
| 161 | ): Promise<CrosspostTargetResult> { | |
| 162 | const driver = await this.ensureDriver() | |
| 163 | ||
| 164 | let identity: SocialIdentityRow | |
| 165 | try { | |
| 166 | identity = await this.requireIdentity() | |
| 167 | } | |
| 168 | catch (error) { | |
| 169 | return { provider: 'linkedin', ok: false, error: messageOf(error) } | |
| 170 | } | |
| 171 | ||
| 172 | if (post.body.length > this.driver.characterLimit) { | |
| 173 | return { | |
| 174 | provider: 'linkedin', | |
| 175 | ok: false, | |
| 176 | error: `LinkedIn posts must be ${this.driver.characterLimit} characters or fewer.`, | |
| 177 | } | |
| 178 | } | |
| 179 | ||
| 180 | const targetUuid = uuid() | |
| 181 | const createdAt = now() | |
| 182 | await database.insertInto('post_targets').values({ | |
| 183 | uuid: targetUuid, | |
| 184 | provider: 'linkedin', | |
| 185 | status: 'publishing', | |
| 186 | post_id: post.id, | |
| 187 | social_driver_id: driver.id, | |
| 188 | social_identity_id: identity.id, | |
| 189 | created_at: createdAt, | |
| 190 | updated_at: createdAt, | |
| 191 | }).execute() | |
| 192 | ||
| 193 | const target = await database | |
| 194 | .selectFrom('post_targets') | |
| 195 | .selectAll() | |
| 196 | .where('uuid', '=', targetUuid) | |
| 197 | .executeTakeFirstOrThrow() | |
| 198 | ||
| 199 | try { | |
| 200 | const published = await this.driver.publish({ | |
| 201 | handle: identity.handle, | |
| 202 | did: identity.external_id || undefined, | |
| 203 | accessToken: identity.access_token || undefined, | |
| 204 | }, { | |
| 205 | text: post.body, | |
| 206 | ...(content?.external ? { external: content.external } : {}), | |
| 207 | }) | |
| 208 | ||
| 209 | await database.updateTable('post_targets').set({ | |
| 210 | status: 'published', | |
| 211 | remote_uri: published.uri || null, | |
| 212 | failure_reason: null, | |
| 213 | updated_at: now(), | |
| 214 | }).where('id', '=', target.id).execute() | |
| 215 | ||
| 216 | return { | |
| 217 | provider: 'linkedin', | |
| 218 | ok: true, | |
| 219 | url: published.url, | |
| 220 | uri: published.uri, | |
| 221 | targetId: Number(target.id), | |
| 222 | } | |
| 223 | } | |
| 224 | catch (error) { | |
| 225 | const message = messageOf(error) | |
| 226 | if (error instanceof LinkedInApiError && error.isAuthError) { | |
| 227 | await this.markExpired(identity.id) | |
| 228 | } | |
| 229 | await database.updateTable('post_targets').set({ | |
| 230 | status: 'failed', | |
| 231 | failure_reason: message, | |
| 232 | updated_at: now(), | |
| 233 | }).where('id', '=', target.id).execute() | |
| 234 | ||
| 235 | return { provider: 'linkedin', ok: false, error: message, targetId: Number(target.id) } | |
| 236 | } | |
| 237 | } | |
| 238 | ||
| 239 | private async requireIdentity(): Promise<SocialIdentityRow> { | |
| 240 | const existing = await this.findIdentity() | |
| 241 | if (existing?.access_token && existing.auth_status === 'connected') return existing | |
| 242 | ||
| 243 | // Fall back to an env-configured token if one is available. | |
| 244 | if (this.config().accessToken) { | |
| 245 | await this.connectFromEnv() | |
| 246 | const connected = await this.findIdentity() | |
| 247 | if (connected?.access_token) return connected | |
| 248 | } | |
| 249 | ||
| 250 | throw new Error('Connect LinkedIn before publishing.') | |
| 251 | } | |
| 252 | ||
| 253 | private async findIdentity(): Promise<SocialIdentityRow | undefined> { | |
| 254 | return await database | |
| 255 | .selectFrom('social_identities') | |
| 256 | .selectAll() | |
| 257 | .where('provider', '=', 'linkedin') | |
| 258 | .orderBy('updated_at', 'desc') | |
| 259 | .executeTakeFirst() | |
| 260 | } | |
| 261 | ||
| 262 | private async saveSession(input: { accessToken: string, authorUrn: string, name?: string }): Promise<SocialIdentityRow> { | |
| 263 | const accountId = await ensureAccount() | |
| 264 | const driver = await this.ensureDriver() | |
| 265 | const existing = await this.findIdentity() | |
| 266 | const savedAt = now() | |
| 267 | const handle = (input.name || input.authorUrn.replace('urn:li:person:', '')).trim() | |
| 268 | ||
| 269 | const values = { | |
| 270 | handle, | |
| 271 | display_name: input.name || null, | |
| 272 | provider: 'linkedin', | |
| 273 | external_id: input.authorUrn, | |
| 274 | auth_status: 'connected', | |
| 275 | access_token: input.accessToken, | |
| 276 | refresh_token: null, | |
| 277 | account_id: accountId, | |
| 278 | social_driver_id: driver.id, | |
| 279 | updated_at: savedAt, | |
| 280 | } | |
| 281 | ||
| 282 | if (existing) { | |
| 283 | await database.updateTable('social_identities').set(values).where('id', '=', existing.id).execute() | |
| 284 | } | |
| 285 | else { | |
| 286 | await database.insertInto('social_identities').values({ | |
| 287 | uuid: uuid(), | |
| 288 | ...values, | |
| 289 | created_at: savedAt, | |
| 290 | }).execute() | |
| 291 | } | |
| 292 | ||
| 293 | return await this.findIdentity() as SocialIdentityRow | |
| 294 | } | |
| 295 | ||
| 296 | private async markExpired(id: number): Promise<void> { | |
| 297 | await database.updateTable('social_identities').set({ | |
| 298 | auth_status: 'expired', | |
| 299 | updated_at: now(), | |
| 300 | }).where('id', '=', id).execute() | |
| 301 | } | |
| 302 | ||
| 303 | private async ensureDriver(): Promise<SocialDriverRow> { | |
| 304 | const existing = await database | |
| 305 | .selectFrom('social_drivers') | |
| 306 | .selectAll() | |
| 307 | .where('provider', '=', 'linkedin') | |
| 308 | .executeTakeFirst() | |
| 309 | ||
| 310 | if (existing) { | |
| 311 | if (existing.status !== 'active' || existing.character_limit !== this.driver.characterLimit) { | |
| 312 | await database.updateTable('social_drivers').set({ | |
| 313 | status: 'active', | |
| 314 | character_limit: this.driver.characterLimit, | |
| 315 | updated_at: now(), | |
| 316 | }).where('id', '=', existing.id).execute() | |
| 317 | } | |
| 318 | ||
| 319 | return await database | |
| 320 | .selectFrom('social_drivers') | |
| 321 | .selectAll() | |
| 322 | .where('id', '=', existing.id) | |
| 323 | .executeTakeFirstOrThrow() | |
| 324 | } | |
| 325 | ||
| 326 | const driverUuid = uuid() | |
| 327 | await database.insertInto('social_drivers').values({ | |
| 328 | uuid: driverUuid, | |
| 329 | provider: 'linkedin', | |
| 330 | display_name: 'LinkedIn', | |
| 331 | status: 'active', | |
| 332 | character_limit: this.driver.characterLimit, | |
| 333 | capabilities: JSON.stringify({ posts: true, timelines: false, oauth: true }), | |
| 334 | created_at: now(), | |
| 335 | updated_at: now(), | |
| 336 | }).execute() | |
| 337 | ||
| 338 | return await database | |
| 339 | .selectFrom('social_drivers') | |
| 340 | .selectAll() | |
| 341 | .where('uuid', '=', driverUuid) | |
| 342 | .executeTakeFirstOrThrow() | |
| 343 | } | |
| 344 | ||
| 345 | private publicIdentity(row: SocialIdentityRow | undefined) { | |
| 346 | if (!row) { | |
| 347 | return { | |
| 348 | connected: false, | |
| 349 | provider: 'linkedin', | |
| 350 | handle: null, | |
| 351 | displayName: null, | |
| 352 | did: null, | |
| 353 | authStatus: 'missing', | |
| 354 | } | |
| 355 | } | |
| 356 | ||
| 357 | const connected = row.auth_status === 'connected' && Boolean(row.access_token) | |
| 358 | return { | |
| 359 | connected, | |
| 360 | provider: 'linkedin', | |
| 361 | handle: row.handle, | |
| 362 | displayName: row.display_name || null, | |
| 363 | did: row.external_id || null, | |
| 364 | authStatus: connected ? 'connected' : 'missing', | |
| 365 | } | |
| 366 | } | |
| 367 | } | |
| 368 | ||
| 369 | function messageOf(error: unknown): string { | |
| 370 | return error instanceof Error ? error.message : String(error) | |
| 371 | } | |
| 372 | ||
| 373 | export const linkedin = new LinkedInService() | |