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/Drivers/LinkedInDriver.tsmodified+262-1
Changes to app/Services/Social/Drivers/LinkedInDriver.ts
@@ -1,1 +1,262 @@
1export { LinkedInApiError, LinkedInPublishingDriver as LinkedInDriver } from '@stacksjs/socials'
1import type { LinkedInTokenExchangeInput, PublishedPost, PublishPostInput, SocialIdentityCredentials } from '@stacksjs/socials'
2import { escapeLinkedInText, LinkedInApiError, LinkedInPublishingDriver } from '@stacksjs/socials'
3
4export { LinkedInApiError }
5
6interface InitializeUploadResponse {
7 value?: { uploadUrl?: string, image?: string }
8}
9
10export interface LinkedInRefreshInput {
11 clientId: string
12 clientSecret: string
13 refreshToken: string
14}
15
16export interface LinkedInRefreshedToken {
17 accessToken: string
18 expiresIn?: number
19 /** Present only when the app is enrolled in LinkedIn's refresh-token program. */
20 refreshToken?: string
21 refreshTokenExpiresIn?: number
22}
23
24/**
25 * App-owned LinkedIn driver. Extends the vendored `@stacksjs/socials` driver to
26 * add image posting — the base driver only supports text and article link
27 * cards. Kept here in `app/` (not patched into `storage/framework/`) so a
28 * framework upgrade can't clobber it, the same "re-home into app code" rule the
29 * app-owned Mastodon driver and the auth bridge follow.
30 *
31 * Everything else (OAuth `getAuthUrl`/`exchangeCode`/`getProfile`, the versioned
32 * REST plumbing) is inherited unchanged. Only `publish` is overridden, and a
33 * single `uploadImage` step is added.
34 */
35export class LinkedInDriver extends LinkedInPublishingDriver {
36 /**
37 * Exchange an authorization code for a token, additionally surfacing the
38 * `refresh_token` the base driver drops. LinkedIn only returns one when the
39 * app is enrolled in the refresh-token program; when absent, the field is
40 * simply undefined and the connection falls back to reconnect-on-expiry.
41 */
42 async exchangeCode(input: LinkedInTokenExchangeInput): Promise<LinkedInRefreshedToken & { scope?: string }> {
43 const body = new URLSearchParams({
44 grant_type: 'authorization_code',
45 code: input.code,
46 redirect_uri: input.redirectUrl,
47 client_id: input.clientId,
48 client_secret: input.clientSecret,
49 })
50
51 const payload = await this.request<{
52 access_token: string
53 expires_in?: number
54 scope?: string
55 refresh_token?: string
56 refresh_token_expires_in?: number
57 }>(`${this.authBase}/oauth/v2/accessToken`, {
58 method: 'POST',
59 headers: { 'content-type': 'application/x-www-form-urlencoded' },
60 body: body.toString(),
61 })
62
63 if (!payload.access_token) {
64 throw new LinkedInApiError('LinkedIn did not return an access token.', 400, JSON.stringify(payload))
65 }
66
67 return {
68 accessToken: payload.access_token,
69 expiresIn: payload.expires_in,
70 scope: payload.scope,
71 refreshToken: payload.refresh_token,
72 refreshTokenExpiresIn: payload.refresh_token_expires_in,
73 }
74 }
75
76 /** Mint a fresh access token from a stored refresh token. */
77 async refreshAccessToken(input: LinkedInRefreshInput): Promise<LinkedInRefreshedToken> {
78 const body = new URLSearchParams({
79 grant_type: 'refresh_token',
80 refresh_token: input.refreshToken,
81 client_id: input.clientId,
82 client_secret: input.clientSecret,
83 })
84
85 const payload = await this.request<{
86 access_token: string
87 expires_in?: number
88 refresh_token?: string
89 refresh_token_expires_in?: number
90 }>(`${this.authBase}/oauth/v2/accessToken`, {
91 method: 'POST',
92 headers: { 'content-type': 'application/x-www-form-urlencoded' },
93 body: body.toString(),
94 })
95
96 if (!payload.access_token) {
97 throw new LinkedInApiError('LinkedIn did not return a refreshed access token.', 400, JSON.stringify(payload))
98 }
99
100 return {
101 accessToken: payload.access_token,
102 expiresIn: payload.expires_in,
103 refreshToken: payload.refresh_token,
104 refreshTokenExpiresIn: payload.refresh_token_expires_in,
105 }
106 }
107
108 /**
109 * Register and upload one image via LinkedIn's versioned Images API, then
110 * return its `urn:li:image:...` id for attachment.
111 *
112 * 1. POST /rest/images?action=initializeUpload → { uploadUrl, image URN }
113 * 2. PUT the raw bytes to `uploadUrl`
114 *
115 * `owner` is the author URN (`urn:li:person:{sub}`) that owns the asset.
116 */
117 async uploadImage(accessToken: string, owner: string, bytes: Uint8Array, mimeType?: string): Promise<string> {
118 const initialized = await this.request<InitializeUploadResponse>(
119 `${this.apiBase}/rest/images?action=initializeUpload`,
120 {
121 method: 'POST',
122 headers: {
123 'authorization': `Bearer ${accessToken}`,
124 'content-type': 'application/json',
125 'linkedin-version': this.apiVersion,
126 'x-restli-protocol-version': '2.0.0',
127 },
128 body: JSON.stringify({ initializeUploadRequest: { owner } }),
129 },
130 )
131
132 const uploadUrl = initialized.value?.uploadUrl
133 const image = initialized.value?.image
134 if (!uploadUrl || !image) {
135 throw new LinkedInApiError('LinkedIn did not return an image upload URL.', 400, JSON.stringify(initialized))
136 }
137
138 const upload = await fetch(uploadUrl, {
139 method: 'PUT',
140 headers: {
141 'authorization': `Bearer ${accessToken}`,
142 'content-type': mimeType || 'image/jpeg',
143 },
144 body: bytes as unknown as BodyInit,
145 })
146
147 if (!upload.ok) {
148 const text = await upload.text().catch(() => '')
149 throw new LinkedInApiError(
150 `LinkedIn image upload failed (${upload.status}): ${text || upload.statusText}`,
151 upload.status,
152 text,
153 )
154 }
155
156 return image
157 }
158
159 /**
160 * Publish a member share. Extends the base text/article flow with a single
161 * attached image (`post.media[0]`): the image is uploaded first, then
162 * referenced under `content.media`. LinkedIn's `content` is a one-of, so an
163 * image supersedes an article link card when both are present (matching how
164 * Bluesky lets an image override the link card).
165 *
166 * The record shape is duplicated from the base driver by necessity — the base
167 * `publish` builds it inline with no seam to inject media — and is pinned by
168 * tests/unit/linkedin-driver.test.ts so upgrade drift surfaces immediately.
169 */
170 async publish(identity: SocialIdentityCredentials, post: PublishPostInput): Promise<PublishedPost> {
171 if (!identity.accessToken) throw new Error('LinkedIn access token is missing for this identity.')
172
173 // `did` carries the member URN (urn:li:person:{sub}) for LinkedIn identities.
174 const author = identity.did
175 if (!author) throw new Error('LinkedIn member URN is required to publish.')
176
177 if (post.text.length > this.characterLimit) {
178 throw new Error(`LinkedIn posts must be ${this.characterLimit} characters or fewer.`)
179 }
180
181 // Resolve an attached image to bytes — uploaded files arrive as `bytes`;
182 // a bare `url` is fetched first (same handling as the Mastodon driver).
183 const media = post.media?.[0]
184 let imageUrn: string | undefined
185 if (media) {
186 let bytes = media.bytes
187 let mimeType = media.mimeType
188 if (!bytes?.length && media.url) {
189 const response = await fetch(media.url)
190 if (response.ok) {
191 bytes = new Uint8Array(await response.arrayBuffer())
192 mimeType = mimeType || response.headers.get('content-type') || 'image/jpeg'
193 }
194 }
195 if (bytes?.length) {
196 imageUrn = await this.uploadImage(identity.accessToken, author, bytes, mimeType)
197 }
198 }
199
200 const record: Record<string, unknown> = {
201 author,
202 commentary: escapeLinkedInText(post.text),
203 visibility: 'PUBLIC',
204 distribution: {
205 feedDistribution: 'MAIN_FEED',
206 targetEntities: [],
207 thirdPartyDistributionChannels: [],
208 },
209 lifecycleState: 'PUBLISHED',
210 isReshareDisabledByAuthor: false,
211 }
212
213 if (imageUrn) {
214 record.content = {
215 media: {
216 id: imageUrn,
217 ...(media?.altText ? { altText: media.altText } : {}),
218 },
219 }
220 }
221 else if (post.external) {
222 record.content = {
223 article: {
224 source: post.external.uri,
225 title: post.external.title,
226 description: post.external.description || '',
227 },
228 }
229 }
230
231 const response = await fetch(`${this.apiBase}/rest/posts`, {
232 method: 'POST',
233 headers: {
234 'authorization': `Bearer ${identity.accessToken}`,
235 'content-type': 'application/json',
236 'linkedin-version': this.apiVersion,
237 'x-restli-protocol-version': '2.0.0',
238 },
239 body: JSON.stringify(record),
240 })
241
242 const text = await response.text()
243 if (!response.ok) {
244 throw new LinkedInApiError(
245 `LinkedIn API failed (${response.status}): ${text || response.statusText}`,
246 response.status,
247 text,
248 )
249 }
250
251 // The created post URN comes back in a response header, not the body.
252 const uri = response.headers.get('x-restli-id')
253 || response.headers.get('x-linkedin-id')
254 || ''
255
256 return {
257 provider: this.provider,
258 uri,
259 url: uri ? `https://www.linkedin.com/feed/update/${uri}` : undefined,
260 }
261 }
262}