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.tsmodified+46-4
Changes to app/Services/Social/LinkedInService.ts
@@ -2,7 +2,7 @@ import type { CrosspostTargetResult, PublishContent } from '../../Support/Social
22import { db } from '@stacksjs/database'
33import { env } from '@stacksjs/env'
44import { LinkedInApiError, LinkedInDriver } from './Drivers/LinkedInDriver'
5import { ensureAccount, now, uuid } from './support'
5import { ensureAccount, expiresAt, isExpiringSoon, now, uuid } from './support'
66
77const database = db as any
88
@@ -15,6 +15,7 @@ type SocialIdentityRow = {
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}
@@ -125,6 +126,8 @@ export class LinkedInService {
125126
126127 const identity = await this.saveSession({
127128 accessToken: token.accessToken,
129 refreshToken: token.refreshToken,
130 expiresIn: token.expiresIn,
128131 authorUrn,
129132 name: profile?.name,
130133 })
@@ -204,6 +207,7 @@ export class LinkedInService {
204207 }, {
205208 text: post.body,
206209 ...(content?.external ? { external: content.external } : {}),
210 ...(content?.media?.length ? { media: content.media } : {}),
207211 })
208212
209213 await database.updateTable('post_targets').set({
@@ -238,7 +242,9 @@ export class LinkedInService {
238242
239243 private async requireIdentity(): Promise<SocialIdentityRow> {
240244 const existing = await this.findIdentity()
241 if (existing?.access_token && existing.auth_status === 'connected') return existing
245 if (existing?.access_token && existing.auth_status === 'connected') {
246 return await this.refreshIfExpiring(existing)
247 }
242248
243249 // Fall back to an env-configured token if one is available.
244250 if (this.config().accessToken) {
@@ -250,6 +256,41 @@ export class LinkedInService {
250256 throw new Error('Connect LinkedIn before publishing.')
251257 }
252258
259 /**
260 * Refresh the access token when it's within its pre-expiry window and a
261 * refresh token is on file (LinkedIn only issues one when the app is enrolled
262 * in the refresh-token program). Best-effort: any failure leaves the current
263 * token in place so a real auth failure still surfaces at publish time.
264 */
265 private async refreshIfExpiring(identity: SocialIdentityRow): Promise<SocialIdentityRow> {
266 const cfg = this.config()
267 if (!identity.refresh_token || !isExpiringSoon(identity.token_expires_at)) return identity
268 if (!cfg.clientId || !cfg.clientSecret) return identity
269
270 try {
271 const refreshed = await this.driver.refreshAccessToken({
272 clientId: cfg.clientId,
273 clientSecret: cfg.clientSecret,
274 refreshToken: identity.refresh_token,
275 })
276 const nextExpiry = expiresAt(refreshed.expiresIn)
277 // LinkedIn rotates the refresh token on some grants — keep the new one.
278 const nextRefresh = refreshed.refreshToken ?? identity.refresh_token
279 await database.updateTable('social_identities').set({
280 access_token: refreshed.accessToken,
281 refresh_token: nextRefresh,
282 token_expires_at: nextExpiry,
283 auth_status: 'connected',
284 updated_at: now(),
285 }).where('id', '=', identity.id).execute()
286
287 return { ...identity, access_token: refreshed.accessToken, refresh_token: nextRefresh, token_expires_at: nextExpiry }
288 }
289 catch {
290 return identity
291 }
292 }
293
253294 private async findIdentity(): Promise<SocialIdentityRow | undefined> {
254295 return await database
255296 .selectFrom('social_identities')
@@ -259,7 +300,7 @@ export class LinkedInService {
259300 .executeTakeFirst()
260301 }
261302
262 private async saveSession(input: { accessToken: string, authorUrn: string, name?: string }): Promise<SocialIdentityRow> {
303 private async saveSession(input: { accessToken: string, authorUrn: string, name?: string, refreshToken?: string, expiresIn?: number }): Promise<SocialIdentityRow> {
263304 const accountId = await ensureAccount()
264305 const driver = await this.ensureDriver()
265306 const existing = await this.findIdentity()
@@ -273,7 +314,8 @@ export class LinkedInService {
273314 external_id: input.authorUrn,
274315 auth_status: 'connected',
275316 access_token: input.accessToken,
276 refresh_token: null,
317 refresh_token: input.refreshToken ?? null,
318 token_expires_at: expiresAt(input.expiresIn),
277319 account_id: accountId,
278320 social_driver_id: driver.id,
279321 updated_at: savedAt,