also looking at this
feat: crossposting — media (LinkedIn/IG/Threads), OAuth token refresh, and X/Twitter
#30
28 files
+1810
-109
| @@ -0,0 +1,261 @@ | ||
| 1 | import type { PublishedPost, PublishPostInput, SocialIdentityCredentials } from '@stacksjs/socials' | |
| 2 | ||
| 3 | /** | |
| 4 | * Full app-owned X/Twitter publishing driver. The published `@stacksjs/socials` | |
| 5 | * ships only a *sign-in* provider for Twitter (getAuthUrl/getAccessToken/ | |
| 6 | * getUserByToken, no `publish`), so — like the Mastodon driver — this is a | |
| 7 | * complete local implementation rather than a subclass. | |
| 8 | * | |
| 9 | * Auth is OAuth 2.0 with PKCE (X's user-context flow). Posting is `POST | |
| 10 | * /2/tweets`; images go through `POST /2/media/upload` first and attach by | |
| 11 | * media id. Threads chain via `reply.in_reply_to_tweet_id`. | |
| 12 | * | |
| 13 | * NOTE: posting on X requires a paid API tier — this is exercised only against | |
| 14 | * mocked endpoints in tests; the request shapes follow X's documented v2 API. | |
| 15 | */ | |
| 16 | ||
| 17 | export class TwitterApiError extends Error { | |
| 18 | constructor( | |
| 19 | message: string, | |
| 20 | public status: number, | |
| 21 | public body: string, | |
| 22 | ) { | |
| 23 | super(message) | |
| 24 | this.name = 'TwitterApiError' | |
| 25 | } | |
| 26 | ||
| 27 | get isAuthError(): boolean { | |
| 28 | return this.status === 401 || this.status === 403 | |
| 29 | } | |
| 30 | } | |
| 31 | ||
| 32 | export interface TwitterDriverOptions { | |
| 33 | apiBase?: string | |
| 34 | authorizeBase?: string | |
| 35 | } | |
| 36 | ||
| 37 | export interface TwitterAuthUrlInput { | |
| 38 | clientId: string | |
| 39 | redirectUrl: string | |
| 40 | scopes: string[] | |
| 41 | state: string | |
| 42 | } | |
| 43 | ||
| 44 | export interface TwitterTokenExchangeInput { | |
| 45 | clientId: string | |
| 46 | clientSecret?: string | |
| 47 | redirectUrl: string | |
| 48 | code: string | |
| 49 | codeVerifier: string | |
| 50 | } | |
| 51 | ||
| 52 | export interface TwitterRefreshInput { | |
| 53 | clientId: string | |
| 54 | clientSecret?: string | |
| 55 | refreshToken: string | |
| 56 | } | |
| 57 | ||
| 58 | export interface TwitterToken { | |
| 59 | accessToken: string | |
| 60 | refreshToken?: string | |
| 61 | expiresIn?: number | |
| 62 | scope?: string | |
| 63 | } | |
| 64 | ||
| 65 | export interface TwitterProfile { | |
| 66 | id: string | |
| 67 | username: string | |
| 68 | name?: string | |
| 69 | } | |
| 70 | ||
| 71 | /** base64url with padding stripped — the encoding OAuth2/PKCE expects. */ | |
| 72 | function base64Url(bytes: Uint8Array): string { | |
| 73 | let binary = '' | |
| 74 | for (const byte of bytes) binary += String.fromCharCode(byte) | |
| 75 | return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') | |
| 76 | } | |
| 77 | ||
| 78 | export class TwitterPublishingDriver { | |
| 79 | readonly provider: 'twitter' = 'twitter' | |
| 80 | characterLimit = 280 | |
| 81 | ||
| 82 | protected apiBase: string | |
| 83 | protected authorizeBase: string | |
| 84 | ||
| 85 | constructor(options: TwitterDriverOptions = {}) { | |
| 86 | this.apiBase = options.apiBase || 'https://api.twitter.com' | |
| 87 | this.authorizeBase = options.authorizeBase || 'https://twitter.com' | |
| 88 | } | |
| 89 | ||
| 90 | /** | |
| 91 | * Build the OAuth 2.0 consent URL with a PKCE challenge, returning both the | |
| 92 | * URL and the `code_verifier` the caller must stash for the token exchange. | |
| 93 | */ | |
| 94 | async createAuthorization(input: TwitterAuthUrlInput): Promise<{ url: string, codeVerifier: string }> { | |
| 95 | const codeVerifier = base64Url(crypto.getRandomValues(new Uint8Array(32))) | |
| 96 | const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier)) | |
| 97 | const codeChallenge = base64Url(new Uint8Array(digest)) | |
| 98 | ||
| 99 | const query = new URLSearchParams({ | |
| 100 | response_type: 'code', | |
| 101 | client_id: input.clientId, | |
| 102 | redirect_uri: input.redirectUrl, | |
| 103 | scope: input.scopes.join(' '), | |
| 104 | state: input.state, | |
| 105 | code_challenge: codeChallenge, | |
| 106 | code_challenge_method: 'S256', | |
| 107 | }) | |
| 108 | ||
| 109 | return { url: `${this.authorizeBase}/i/oauth2/authorize?${query.toString()}`, codeVerifier } | |
| 110 | } | |
| 111 | ||
| 112 | /** Exchange an authorization code (+ PKCE verifier) for user tokens. */ | |
| 113 | async exchangeCode(input: TwitterTokenExchangeInput): Promise<TwitterToken> { | |
| 114 | return this.tokenRequest(new URLSearchParams({ | |
| 115 | grant_type: 'authorization_code', | |
| 116 | code: input.code, | |
| 117 | redirect_uri: input.redirectUrl, | |
| 118 | code_verifier: input.codeVerifier, | |
| 119 | client_id: input.clientId, | |
| 120 | }), input.clientId, input.clientSecret) | |
| 121 | } | |
| 122 | ||
| 123 | /** Mint a fresh access token from a stored refresh token. */ | |
| 124 | async refreshAccessToken(input: TwitterRefreshInput): Promise<TwitterToken> { | |
| 125 | return this.tokenRequest(new URLSearchParams({ | |
| 126 | grant_type: 'refresh_token', | |
| 127 | refresh_token: input.refreshToken, | |
| 128 | client_id: input.clientId, | |
| 129 | }), input.clientId, input.clientSecret) | |
| 130 | } | |
| 131 | ||
| 132 | /** Resolve the authenticated account (id + handle). */ | |
| 133 | async getProfile(accessToken: string): Promise<TwitterProfile> { | |
| 134 | const payload = await this.request<{ data?: { id: string, username: string, name?: string } }>( | |
| 135 | `${this.apiBase}/2/users/me?user.fields=username,name`, | |
| 136 | { headers: { authorization: `Bearer ${accessToken}` } }, | |
| 137 | ) | |
| 138 | if (!payload.data?.id || !payload.data.username) { | |
| 139 | throw new TwitterApiError('Twitter did not return the authenticated user.', 400, JSON.stringify(payload)) | |
| 140 | } | |
| 141 | return { id: payload.data.id, username: payload.data.username, name: payload.data.name } | |
| 142 | } | |
| 143 | ||
| 144 | /** Upload one image and return its media id for attachment. */ | |
| 145 | async uploadMedia(accessToken: string, bytes: Uint8Array, mimeType: string): Promise<string> { | |
| 146 | const form = new FormData() | |
| 147 | form.set('media', new Blob([bytes as unknown as BlobPart], { type: mimeType || 'image/jpeg' })) | |
| 148 | form.set('media_category', 'tweet_image') | |
| 149 | ||
| 150 | const payload = await this.request<{ data?: { id?: string }, media_id_string?: string, id?: string }>( | |
| 151 | `${this.apiBase}/2/media/upload`, | |
| 152 | { method: 'POST', headers: { authorization: `Bearer ${accessToken}` }, body: form }, | |
| 153 | ) | |
| 154 | ||
| 155 | const mediaId = payload.data?.id || payload.media_id_string || payload.id | |
| 156 | if (!mediaId) { | |
| 157 | throw new TwitterApiError('Twitter did not return a media id.', 400, JSON.stringify(payload)) | |
| 158 | } | |
| 159 | return mediaId | |
| 160 | } | |
| 161 | ||
| 162 | async publish(identity: SocialIdentityCredentials, post: PublishPostInput): Promise<PublishedPost> { | |
| 163 | if (!identity.accessToken) throw new Error('Twitter access token is missing for this identity.') | |
| 164 | if (post.text.length > this.characterLimit) { | |
| 165 | throw new Error(`Twitter posts must be ${this.characterLimit} characters or fewer.`) | |
| 166 | } | |
| 167 | ||
| 168 | // Resolve an attached image to bytes (uploaded files arrive as bytes; a bare | |
| 169 | // URL is fetched first) and upload it for its media id. | |
| 170 | const mediaIds: string[] = [] | |
| 171 | const media = post.media?.[0] | |
| 172 | if (media) { | |
| 173 | let bytes = media.bytes | |
| 174 | let mimeType = media.mimeType | |
| 175 | if (!bytes?.length && media.url) { | |
| 176 | const response = await fetch(media.url) | |
| 177 | if (response.ok) { | |
| 178 | bytes = new Uint8Array(await response.arrayBuffer()) | |
| 179 | mimeType = mimeType || response.headers.get('content-type') || 'image/jpeg' | |
| 180 | } | |
| 181 | } | |
| 182 | if (bytes?.length) mediaIds.push(await this.uploadMedia(identity.accessToken, bytes, mimeType || 'image/jpeg')) | |
| 183 | } | |
| 184 | ||
| 185 | const body: Record<string, unknown> = { text: post.text } | |
| 186 | if (mediaIds.length) body.media = { media_ids: mediaIds } | |
| 187 | // Threads chain through the parent tweet id, carried in reply.parent.uri. | |
| 188 | if (post.reply?.parent?.uri) body.reply = { in_reply_to_tweet_id: post.reply.parent.uri } | |
| 189 | ||
| 190 | const payload = await this.request<{ data?: { id?: string } }>( | |
| 191 | `${this.apiBase}/2/tweets`, | |
| 192 | { | |
| 193 | method: 'POST', | |
| 194 | headers: { 'authorization': `Bearer ${identity.accessToken}`, 'content-type': 'application/json' }, | |
| 195 | body: JSON.stringify(body), | |
| 196 | }, | |
| 197 | ) | |
| 198 | ||
| 199 | const id = payload.data?.id | |
| 200 | if (!id) throw new TwitterApiError('Twitter did not return a tweet id.', 400, JSON.stringify(payload)) | |
| 201 | ||
| 202 | return { | |
| 203 | provider: this.provider, | |
| 204 | // Expose the tweet id as both uri and cid so the crosspost thread-chaining | |
| 205 | // logic (which needs a cid) can reply-chain subsequent segments. | |
| 206 | uri: id, | |
| 207 | cid: id, | |
| 208 | url: identity.handle | |
| 209 | ? `https://x.com/${identity.handle}/status/${id}` | |
| 210 | : `https://x.com/i/web/status/${id}`, | |
| 211 | } | |
| 212 | } | |
| 213 | ||
| 214 | // X's home timeline needs elevated access we don't assume here. | |
| 215 | async timeline(): Promise<{ items: [] }> { | |
| 216 | return { items: [] } | |
| 217 | } | |
| 218 | ||
| 219 | protected async tokenRequest(body: URLSearchParams, clientId: string, clientSecret?: string): Promise<TwitterToken> { | |
| 220 | const headers: Record<string, string> = { 'content-type': 'application/x-www-form-urlencoded' } | |
| 221 | // Confidential clients authenticate the token endpoint with HTTP Basic; | |
| 222 | // public (PKCE-only) clients send just the client_id in the body. | |
| 223 | if (clientSecret) headers.authorization = `Basic ${btoa(`${clientId}:${clientSecret}`)}` | |
| 224 | ||
| 225 | const payload = await this.request<{ | |
| 226 | access_token?: string | |
| 227 | refresh_token?: string | |
| 228 | expires_in?: number | |
| 229 | scope?: string | |
| 230 | }>(`${this.apiBase}/2/oauth2/token`, { method: 'POST', headers, body: body.toString() }) | |
| 231 | ||
| 232 | if (!payload.access_token) { | |
| 233 | throw new TwitterApiError('Twitter did not return an access token.', 400, JSON.stringify(payload)) | |
| 234 | } | |
| 235 | ||
| 236 | return { | |
| 237 | accessToken: payload.access_token, | |
| 238 | refreshToken: payload.refresh_token, | |
| 239 | expiresIn: payload.expires_in, | |
| 240 | scope: payload.scope, | |
| 241 | } | |
| 242 | } | |
| 243 | ||
| 244 | protected async request<T>(url: string, init: RequestInit): Promise<T> { | |
| 245 | const response = await fetch(url, init) | |
| 246 | const text = await response.text() | |
| 247 | ||
| 248 | if (!response.ok) { | |
| 249 | throw new TwitterApiError( | |
| 250 | `Twitter API failed (${response.status}): ${text || response.statusText}`, | |
| 251 | response.status, | |
| 252 | text, | |
| 253 | ) | |
| 254 | } | |
| 255 | ||
| 256 | return text ? JSON.parse(text) as T : {} as T | |
| 257 | } | |
| 258 | } | |
| 259 | ||
| 260 | // Consumers import this as `TwitterDriver`, matching the sibling drivers. | |
| 261 | export { TwitterPublishingDriver as TwitterDriver } | |