ReviewOS

also looking at this

stacks/postline

feat: crossposting — media (LinkedIn/IG/Threads), OAuth token refresh, and X/Twitter

#30
Merged glennmichael123 wants to merge feat/crosspost-media-and-token-refresh into main
28 files +1810 -109
app/Services/Social/LinkedInService.ts app/Services/Social/TwitterService.tscopied+115-82
Changes to app/Services/Social/TwitterService.ts
@@ -1,8 +1,8 @@
11import type { CrosspostTargetResult, PublishContent } from '../../Support/Social/types'
22import { db } from '@stacksjs/database'
33import { env } from '@stacksjs/env'
4import { LinkedInApiError, LinkedInDriver } from './Drivers/LinkedInDriver'
5import { ensureAccount, now, uuid } from './support'
4import { TwitterApiError, TwitterDriver } from './Drivers/TwitterDriver'
5import { ensureAccount, expiresAt, isExpiringSoon, now, uuid } from './support'
66
77const database = db as any
88
@@ -10,30 +10,29 @@ type SocialIdentityRow = {
1010 id: number
1111 handle: string
1212 display_name?: string | null
13 provider: 'linkedin'
13 provider: 'twitter'
1414 external_id?: string | null
1515 auth_status: 'connected' | 'expired' | 'revoked' | 'missing'
1616 access_token?: string | null
1717 refresh_token?: string | null
18 token_expires_at?: string | null
1819 account_id?: number | null
1920 social_driver_id?: number | null
2021}
2122
2223type SocialDriverRow = {
2324 id: number
24 provider: 'linkedin'
25 provider: 'twitter'
2526 display_name: string
2627 status: 'active' | 'planned' | 'disabled'
2728 character_limit: number
2829}
2930
30interface LinkedInConfig {
31interface TwitterConfig {
3132 clientId: string
3233 clientSecret: string
3334 redirectUrl: string
34 apiVersion: string
3535 accessToken: string
36 authorUrn: string
3736 scopes: string[]
3837}
3938
@@ -43,25 +42,20 @@ function randomState(): string {
4342 return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('')
4443}
4544
46export 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.
45export 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.
5049 private pendingState: string | null = null
50 private pendingVerifier: string | null = null
5151
52 constructor() {
53 this.driver = new LinkedInDriver({ apiVersion: this.config().apiVersion })
54 }
55
56 private config(): LinkedInConfig {
52 private config(): TwitterConfig {
5753 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'],
6559 }
6660 }
6761
@@ -72,7 +66,7 @@ export class LinkedInService {
7266
7367 return {
7468 connected,
75 provider: 'linkedin',
69 provider: 'twitter',
7670 handle: identity?.handle || null,
7771 displayName: identity?.display_name || null,
7872 did: identity?.external_id || null,
@@ -80,53 +74,55 @@ export class LinkedInService {
8074 characterLimit: this.driver.characterLimit,
8175 canPublish: connected,
8276 configuredFromEnv: Boolean(cfg.accessToken),
83 oauthConfigured: Boolean(cfg.clientId && cfg.clientSecret && cfg.redirectUrl),
77 oauthConfigured: Boolean(cfg.clientId && cfg.redirectUrl),
8478 }
8579 }
8680
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> {
8983 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.')
9686
9787 this.pendingState = randomState()
98 return this.driver.getAuthUrl({
88 const { url, codeVerifier } = await this.driver.createAuthorization({
9989 clientId: cfg.clientId,
10090 redirectUrl: cfg.redirectUrl,
10191 scopes: cfg.scopes,
10292 state: this.pendingState,
10393 })
94 this.pendingVerifier = codeVerifier
95 return url
10496 }
10597
106 /** Handle the OAuth redirect: exchange the code and store the token. */
98 /** Handle the OAuth redirect: exchange the code and store the tokens. */
10799 async handleCallback(code: string, state: string) {
108100 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.')
110102 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.')
112104 }
105 const codeVerifier = this.pendingVerifier
106 if (!codeVerifier) throw new Error('Missing PKCE verifier — please start the X/Twitter connection again.')
113107 this.pendingState = null
108 this.pendingVerifier = null
114109
115110 const token = await this.driver.exchangeCode({
116111 clientId: cfg.clientId,
117 clientSecret: cfg.clientSecret,
112 clientSecret: cfg.clientSecret || undefined,
118113 redirectUrl: cfg.redirectUrl,
119114 code,
115 codeVerifier,
120116 })
121117
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)
126119 const identity = await this.saveSession({
127120 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,
130126 })
131127 return this.publicIdentity(identity)
132128 }
@@ -135,25 +131,23 @@ export class LinkedInService {
135131 async connectFromEnv() {
136132 const cfg = this.config()
137133 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.')
139135 }
140136
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 })
150144 return this.publicIdentity(identity)
151145 }
152146
153147 /**
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.
157151 */
158152 async publishToPost(
159153 post: { id: number, body: string },
@@ -166,14 +160,14 @@ export class LinkedInService {
166160 identity = await this.requireIdentity()
167161 }
168162 catch (error) {
169 return { provider: 'linkedin', ok: false, error: messageOf(error) }
163 return { provider: 'twitter', ok: false, error: messageOf(error) }
170164 }
171165
172166 if (post.body.length > this.driver.characterLimit) {
173167 return {
174 provider: 'linkedin',
168 provider: 'twitter',
175169 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.`,
177171 }
178172 }
179173
@@ -181,7 +175,7 @@ export class LinkedInService {
181175 const createdAt = now()
182176 await database.insertInto('post_targets').values({
183177 uuid: targetUuid,
184 provider: 'linkedin',
178 provider: 'twitter',
185179 status: 'publishing',
186180 post_id: post.id,
187181 social_driver_id: driver.id,
@@ -203,27 +197,30 @@ export class LinkedInService {
203197 accessToken: identity.access_token || undefined,
204198 }, {
205199 text: post.body,
206 ...(content?.external ? { external: content.external } : {}),
200 ...(content?.media?.length ? { media: content.media } : {}),
201 ...(content?.reply ? { reply: content.reply } : {}),
207202 })
208203
209204 await database.updateTable('post_targets').set({
210205 status: 'published',
211206 remote_uri: published.uri || null,
207 remote_cid: published.cid || null,
212208 failure_reason: null,
213209 updated_at: now(),
214210 }).where('id', '=', target.id).execute()
215211
216212 return {
217 provider: 'linkedin',
213 provider: 'twitter',
218214 ok: true,
219215 url: published.url,
220216 uri: published.uri,
217 cid: published.cid,
221218 targetId: Number(target.id),
222219 }
223220 }
224221 catch (error) {
225222 const message = messageOf(error)
226 if (error instanceof LinkedInApiError && error.isAuthError) {
223 if (error instanceof TwitterApiError && error.isAuthError) {
227224 await this.markExpired(identity.id)
228225 }
229226 await database.updateTable('post_targets').set({
@@ -232,48 +229,84 @@ export class LinkedInService {
232229 updated_at: now(),
233230 }).where('id', '=', target.id).execute()
234231
235 return { provider: 'linkedin', ok: false, error: message, targetId: Number(target.id) }
232 return { provider: 'twitter', ok: false, error: message, targetId: Number(target.id) }
236233 }
237234 }
238235
239236 private async requireIdentity(): Promise<SocialIdentityRow> {
240237 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 }
242241
243 // Fall back to an env-configured token if one is available.
244242 if (this.config().accessToken) {
245243 await this.connectFromEnv()
246244 const connected = await this.findIdentity()
247245 if (connected?.access_token) return connected
248246 }
249247
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 }
251284 }
252285
253286 private async findIdentity(): Promise<SocialIdentityRow | undefined> {
254287 return await database
255288 .selectFrom('social_identities')
256289 .selectAll()
257 .where('provider', '=', 'linkedin')
290 .where('provider', '=', 'twitter')
258291 .orderBy('updated_at', 'desc')
259292 .executeTakeFirst()
260293 }
261294
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> {
263296 const accountId = await ensureAccount()
264297 const driver = await this.ensureDriver()
265298 const existing = await this.findIdentity()
266299 const savedAt = now()
267 const handle = (input.name || input.authorUrn.replace('urn:li:person:', '')).trim()
268300
269301 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,
274306 auth_status: 'connected',
275307 access_token: input.accessToken,
276 refresh_token: null,
308 refresh_token: input.refreshToken ?? null,
309 token_expires_at: expiresAt(input.expiresIn),
277310 account_id: accountId,
278311 social_driver_id: driver.id,
279312 updated_at: savedAt,
@@ -304,7 +337,7 @@ export class LinkedInService {
304337 const existing = await database
305338 .selectFrom('social_drivers')
306339 .selectAll()
307 .where('provider', '=', 'linkedin')
340 .where('provider', '=', 'twitter')
308341 .executeTakeFirst()
309342
310343 if (existing) {
@@ -326,8 +359,8 @@ export class LinkedInService {
326359 const driverUuid = uuid()
327360 await database.insertInto('social_drivers').values({
328361 uuid: driverUuid,
329 provider: 'linkedin',
330 display_name: 'LinkedIn',
362 provider: 'twitter',
363 display_name: 'X (Twitter)',
331364 status: 'active',
332365 character_limit: this.driver.characterLimit,
333366 capabilities: JSON.stringify({ posts: true, timelines: false, oauth: true }),
@@ -346,7 +379,7 @@ export class LinkedInService {
346379 if (!row) {
347380 return {
348381 connected: false,
349 provider: 'linkedin',
382 provider: 'twitter',
350383 handle: null,
351384 displayName: null,
352385 did: null,
@@ -357,7 +390,7 @@ export class LinkedInService {
357390 const connected = row.auth_status === 'connected' && Boolean(row.access_token)
358391 return {
359392 connected,
360 provider: 'linkedin',
393 provider: 'twitter',
361394 handle: row.handle,
362395 displayName: row.display_name || null,
363396 did: row.external_id || null,
@@ -370,4 +403,4 @@ function messageOf(error: unknown): string {
370403 return error instanceof Error ? error.message : String(error)
371404}
372405
373export const linkedin = new LinkedInService()
406export const twitter = new TwitterService()