|
| 1 | +/** |
| 2 | + * Ramp service implementation (browser / AI agent-key pathway, production only). |
| 3 | + * |
| 4 | + * `latchkey auth browser ramp` runs the OAuth 2.0 authorization-code + PKCE flow |
| 5 | + * against Ramp's public client (a fixed client ID, no secret). The hosted consent |
| 6 | + * screen (auth_level=auto) mints an "AI agent key"; latchkey catches the loopback |
| 7 | + * callback, exchanges the code for a bearer + refresh token at |
| 8 | + * `.../developer/v1/token/pkce`, and stores them as OAuthCredentials (auto-refreshed). |
| 9 | + * |
| 10 | + * Agent keys use the agent-tools endpoints -- POST https://api.ramp.com/developer/v1/ |
| 11 | + * agent-tools/<tool> with a {"rationale": ...} body (they are auth-level barred from |
| 12 | + * the standard REST endpoints). Spec: https://api.ramp.com/v1/public/agent-tools/spec/. |
| 13 | + */ |
| 14 | + |
| 15 | +import { randomUUID } from 'node:crypto'; |
| 16 | +import type { Browser, BrowserContext, Response } from 'playwright'; |
| 17 | +import { ApiCredentials, OAuthCredentials } from '../apiCredentials/base.js'; |
| 18 | +import { |
| 19 | + exchangeCodeForTokens, |
| 20 | + generateCodeChallenge, |
| 21 | + generateCodeVerifier, |
| 22 | + refreshAccessToken, |
| 23 | + startOAuthCallbackServer, |
| 24 | +} from '../oauthUtils.js'; |
| 25 | +import { isBrowserClosedError, LoginCancelledError, Service, ServiceSession } from './core/base.js'; |
| 26 | + |
| 27 | +/** Ramp's public OAuth client (PKCE, no secret), from ramp-cli. */ |
| 28 | +const RAMP_OAUTH_CLIENT_ID = 'ramp_id_6pKvd0IR3d8Kuzp82SV6YgpVCZOlz68Px6s3wVsr'; |
| 29 | + |
| 30 | +/** Hosted authorize endpoint (where the user signs in / approves the agent key). */ |
| 31 | +const RAMP_AUTHORIZE_URL = 'https://app.ramp.com/v1/authorize'; |
| 32 | + |
| 33 | +/** PKCE token endpoint (code exchange + refresh). */ |
| 34 | +const RAMP_PKCE_TOKEN_ENDPOINT = 'https://api.ramp.com/developer/v1/token/pkce'; |
| 35 | + |
| 36 | +/** Loopback callback path; matches ramp-cli's `/callback`. */ |
| 37 | +const RAMP_OAUTH_CALLBACK_PATH = '/callback'; |
| 38 | + |
| 39 | +/** Time to wait for the user to finish the hosted login + agent-key approval. */ |
| 40 | +const RAMP_LOGIN_TIMEOUT_MS = 300_000; |
| 41 | + |
| 42 | +/** |
| 43 | + * Scopes requested on the authorize URL: exactly the scopes Ramp's agent-tools |
| 44 | + * OpenAPI declares (no regular-REST-only scopes -- agent keys can't use the standard |
| 45 | + * REST API anyway). Ramp grants only the subset the signed-in user is entitled to |
| 46 | + * (returned in the token's `scope`), so over-requesting is harmless, but omitting a |
| 47 | + * scope an endpoint needs fails at call time with DEVELOPER_7100. |
| 48 | + */ |
| 49 | +const RAMP_OAUTH_SCOPES = [ |
| 50 | + 'accounting:read', |
| 51 | + 'ai_spend:read', |
| 52 | + 'approvals:write', |
| 53 | + 'bills:read', |
| 54 | + 'cards:read_agentic', |
| 55 | + 'cards:write', |
| 56 | + 'comments:write', |
| 57 | + 'funds:write', |
| 58 | + 'limits:read', |
| 59 | + 'limits:write', |
| 60 | + 'memos:read', |
| 61 | + 'purchase_orders:read', |
| 62 | + 'receipts:write', |
| 63 | + 'reimbursements:read', |
| 64 | + 'reimbursements:write', |
| 65 | + 'tasks:read', |
| 66 | + 'transactions:read', |
| 67 | + 'transactions:write', |
| 68 | + 'treasury:read', |
| 69 | + 'trips:read', |
| 70 | + 'trips:write', |
| 71 | + 'unified_requests:read', |
| 72 | + 'users:read', |
| 73 | + 'vendors:read', |
| 74 | + 'vendors:write', |
| 75 | + 'x402:write', |
| 76 | +].join(' '); |
| 77 | + |
| 78 | +/** |
| 79 | + * Browser login session: runs the OAuth authorization-code + PKCE flow in a |
| 80 | + * Playwright browser and returns OAuthCredentials. login() is overridden wholesale |
| 81 | + * (the base template's static loginUrl + response-watching model doesn't fit a |
| 82 | + * per-session authorize URL with a localhost callback), mirroring NotionMcpSession. |
| 83 | + */ |
| 84 | +class RampOAuthServiceSession extends ServiceSession { |
| 85 | + onResponse(_response: Response): void { |
| 86 | + // Not used -- login completion is signalled by the OAuth callback, not by |
| 87 | + // inspecting page responses. |
| 88 | + } |
| 89 | + |
| 90 | + protected isLoginComplete(): boolean { |
| 91 | + // Not used -- login() is overridden entirely. |
| 92 | + return false; |
| 93 | + } |
| 94 | + |
| 95 | + protected finalizeCredentials( |
| 96 | + _browser: Browser, |
| 97 | + _context: BrowserContext, |
| 98 | + _oldCredentials?: ApiCredentials |
| 99 | + ): Promise<ApiCredentials | null> { |
| 100 | + // Not used -- login() is overridden entirely. |
| 101 | + return Promise.resolve(null); |
| 102 | + } |
| 103 | + |
| 104 | + override async login( |
| 105 | + encryptedStorage: import('../encryptedStorage.js').EncryptedStorage, |
| 106 | + launchOptions: import('../playwrightUtils.js').BrowserLaunchOptions = {}, |
| 107 | + _oldCredentials?: ApiCredentials |
| 108 | + ): Promise<ApiCredentials> { |
| 109 | + const { withTempBrowserContext } = await import('../playwrightUtils.js'); |
| 110 | + const clientId = RAMP_OAUTH_CLIENT_ID; |
| 111 | + |
| 112 | + return withTempBrowserContext(encryptedStorage, launchOptions, async ({ context }) => { |
| 113 | + const page = await context.newPage(); |
| 114 | + |
| 115 | + const abortController = new AbortController(); |
| 116 | + const closeHandler = () => { |
| 117 | + abortController.abort(); |
| 118 | + }; |
| 119 | + page.on('close', closeHandler); |
| 120 | + context.on('close', closeHandler); |
| 121 | + |
| 122 | + try { |
| 123 | + // 1. Stand up the localhost callback server (random port; Ramp's public |
| 124 | + // client allows arbitrary loopback ports per RFC 8252). |
| 125 | + const { port, codePromise } = await startOAuthCallbackServer( |
| 126 | + RAMP_LOGIN_TIMEOUT_MS, |
| 127 | + abortController.signal, |
| 128 | + RAMP_OAUTH_CALLBACK_PATH |
| 129 | + ); |
| 130 | + const redirectUri = `http://localhost:${port.toString()}${RAMP_OAUTH_CALLBACK_PATH}`; |
| 131 | + |
| 132 | + // 2. PKCE verifier/challenge. |
| 133 | + const codeVerifier = generateCodeVerifier(); |
| 134 | + const codeChallenge = generateCodeChallenge(codeVerifier); |
| 135 | + |
| 136 | + // 3. Open Ramp's hosted authorize screen. auth_level=auto triggers the |
| 137 | + // "create/approve an AI agent key" prompt. |
| 138 | + const authUrl = new URL(RAMP_AUTHORIZE_URL); |
| 139 | + authUrl.searchParams.set('response_type', 'code'); |
| 140 | + authUrl.searchParams.set('client_id', clientId); |
| 141 | + authUrl.searchParams.set('redirect_uri', redirectUri); |
| 142 | + authUrl.searchParams.set('scope', RAMP_OAUTH_SCOPES); |
| 143 | + authUrl.searchParams.set('state', randomUUID()); |
| 144 | + authUrl.searchParams.set('code_challenge', codeChallenge); |
| 145 | + authUrl.searchParams.set('code_challenge_method', 'S256'); |
| 146 | + authUrl.searchParams.set('auth_level', 'auto'); |
| 147 | + |
| 148 | + await page.goto(authUrl.toString()); |
| 149 | + |
| 150 | + // 4. Wait for the user to finish and the callback to deliver the code. |
| 151 | + const code = await codePromise; |
| 152 | + |
| 153 | + // 5. Exchange the code for tokens (public client: no secret). |
| 154 | + const tokens = exchangeCodeForTokens( |
| 155 | + RAMP_PKCE_TOKEN_ENDPOINT, |
| 156 | + code, |
| 157 | + clientId, |
| 158 | + '', |
| 159 | + redirectUri, |
| 160 | + codeVerifier |
| 161 | + ); |
| 162 | + const accessTokenExpiresAt = new Date(Date.now() + tokens.expires_in * 1000).toISOString(); |
| 163 | + |
| 164 | + await page.close(); |
| 165 | + |
| 166 | + // Public client: clientSecret is stored as '' so refresh sends client_id only. |
| 167 | + return new OAuthCredentials( |
| 168 | + clientId, |
| 169 | + '', |
| 170 | + tokens.access_token, |
| 171 | + tokens.refresh_token, |
| 172 | + accessTokenExpiresAt |
| 173 | + ); |
| 174 | + } catch (error: unknown) { |
| 175 | + if (error instanceof Error && isBrowserClosedError(error)) { |
| 176 | + throw new LoginCancelledError(); |
| 177 | + } |
| 178 | + throw error; |
| 179 | + } finally { |
| 180 | + page.off('close', closeHandler); |
| 181 | + context.off('close', closeHandler); |
| 182 | + } |
| 183 | + }); |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +export class Ramp extends Service { |
| 188 | + readonly name = 'ramp'; |
| 189 | + readonly displayName = 'Ramp'; |
| 190 | + readonly baseApiUrls = ['https://api.ramp.com/'] as const; |
| 191 | + readonly loginUrl = 'https://app.ramp.com/'; |
| 192 | + readonly info = |
| 193 | + 'Ramp agent-tools API; the REST API is not supported. ' + |
| 194 | + 'Docs: https://api.ramp.com/v1/public/agent-tools/spec/.'; |
| 195 | + |
| 196 | + // Validate credentials against `search-help-center-snippets`: the one agent-tools |
| 197 | + // endpoint that requires only a valid token and no specific scope (`security: |
| 198 | + // [{oauth2: []}]` in the spec), so the check works regardless of which scopes the |
| 199 | + // signed-in user's agent key was granted. It's a POST taking a required |
| 200 | + // {query, rationale} body; a bad token returns a non-200 (404 DEVELOPER_7002). |
| 201 | + readonly credentialCheckCurlArguments = [ |
| 202 | + '-X', |
| 203 | + 'POST', |
| 204 | + '-H', |
| 205 | + 'Content-Type: application/json', |
| 206 | + '-d', |
| 207 | + '{"query":"ping","rationale":"latchkey credential check"}', |
| 208 | + 'https://api.ramp.com/developer/v1/agent-tools/search-help-center-snippets', |
| 209 | + ] as const; |
| 210 | + |
| 211 | + setCredentialsExample(serviceName: string): string { |
| 212 | + return `latchkey auth browser ${serviceName}`; |
| 213 | + } |
| 214 | + |
| 215 | + /** |
| 216 | + * Browser login: run the OAuth authorization-code + PKCE flow and store the |
| 217 | + * resulting bearer + refresh token. |
| 218 | + */ |
| 219 | + override getSession(appNamePrefix: string): RampOAuthServiceSession { |
| 220 | + return new RampOAuthServiceSession(this, appNamePrefix); |
| 221 | + } |
| 222 | + |
| 223 | + override refreshCredentials(apiCredentials: ApiCredentials): Promise<ApiCredentials | null> { |
| 224 | + // Refresh the PKCE access token with the (rotating) refresh token against the |
| 225 | + // `/token/pkce` endpoint, mirroring ramp-cli. |
| 226 | + if (!(apiCredentials instanceof OAuthCredentials)) { |
| 227 | + return Promise.resolve(null); |
| 228 | + } |
| 229 | + if (apiCredentials.refreshToken === undefined || apiCredentials.refreshToken === '') { |
| 230 | + return Promise.resolve(null); |
| 231 | + } |
| 232 | + const tokens = refreshAccessToken( |
| 233 | + RAMP_PKCE_TOKEN_ENDPOINT, |
| 234 | + apiCredentials.refreshToken, |
| 235 | + apiCredentials.clientId, |
| 236 | + apiCredentials.clientSecret |
| 237 | + ); |
| 238 | + if (tokens === null) { |
| 239 | + return Promise.resolve(null); |
| 240 | + } |
| 241 | + const accessTokenExpiresAt = new Date(Date.now() + tokens.expires_in * 1000).toISOString(); |
| 242 | + // Ramp rotates refresh tokens; keep the old one only if none came back. |
| 243 | + return Promise.resolve( |
| 244 | + new OAuthCredentials( |
| 245 | + apiCredentials.clientId, |
| 246 | + apiCredentials.clientSecret, |
| 247 | + tokens.access_token, |
| 248 | + tokens.refresh_token ?? apiCredentials.refreshToken, |
| 249 | + accessTokenExpiresAt, |
| 250 | + apiCredentials.refreshTokenExpiresAt |
| 251 | + ) |
| 252 | + ); |
| 253 | + } |
| 254 | +} |
| 255 | + |
| 256 | +export const RAMP = new Ramp(); |
0 commit comments