|
| 1 | +// Seeds the OAuth clients only local Syntax Auth has (src/lib/server/local_oauth_clients.ts) into |
| 2 | +// the local D1, after `pnpm d1:migrate:local` in `pnpm dev` and in the Docker image. It writes the |
| 3 | +// row itself because Better Auth's `adminCreateOAuthClient` always generates a random client ID. |
| 4 | +// An upsert on the client ID, so it can run on every start and later changes reach existing local |
| 5 | +// databases. |
| 6 | +import { drizzle } from 'drizzle-orm/d1'; |
| 7 | +import { getPlatformProxy } from 'wrangler'; |
| 8 | + |
| 9 | +import { oauthClient } from '../src/lib/server/db/schema'; |
| 10 | +import { get_auth_environment } from '../src/lib/server/env'; |
| 11 | +import { LOCAL_SYNTAX_LAB_MCP_CLIENT } from '../src/lib/server/local_oauth_clients'; |
| 12 | + |
| 13 | +// Only the `local` env, never remote bindings: this script must never write a deployed database. |
| 14 | +const platform = await getPlatformProxy<App.Platform['env']>({ |
| 15 | + configPath: 'wrangler.jsonc', |
| 16 | + environment: 'local', |
| 17 | + persist: true, |
| 18 | + remoteBindings: false |
| 19 | +}); |
| 20 | + |
| 21 | +try { |
| 22 | + const env = get_auth_environment(platform.env); |
| 23 | + if (!env.is_local_development) { |
| 24 | + throw new Error( |
| 25 | + `Local OAuth clients are seeded only into local Syntax Auth, not ${env.BETTER_AUTH_URL}.` |
| 26 | + ); |
| 27 | + } |
| 28 | + |
| 29 | + const client = LOCAL_SYNTAX_LAB_MCP_CLIENT; |
| 30 | + const now = new Date(); |
| 31 | + const client_fields = { |
| 32 | + name: client.client_name, |
| 33 | + redirectUris: [...client.redirect_uris], |
| 34 | + scopes: [...client.scopes], |
| 35 | + tokenEndpointAuthMethod: client.token_endpoint_auth_method, |
| 36 | + type: client.type, |
| 37 | + public: true, |
| 38 | + grantTypes: [...client.grant_types], |
| 39 | + responseTypes: [...client.response_types], |
| 40 | + requirePKCE: client.require_pkce, |
| 41 | + skipConsent: client.skip_consent, |
| 42 | + enableEndSession: client.enable_end_session, |
| 43 | + disabled: false, |
| 44 | + updatedAt: now |
| 45 | + }; |
| 46 | + |
| 47 | + await drizzle(env.DB) |
| 48 | + .insert(oauthClient) |
| 49 | + .values({ id: client.client_id, clientId: client.client_id, createdAt: now, ...client_fields }) |
| 50 | + .onConflictDoUpdate({ target: oauthClient.clientId, set: client_fields }); |
| 51 | + |
| 52 | + console.log(`Seeded the local OAuth client ${client.client_id}`); |
| 53 | +} catch (seed_error) { |
| 54 | + console.error('Seeding local OAuth clients failed', seed_error); |
| 55 | + process.exitCode = 1; |
| 56 | +} finally { |
| 57 | + await platform.dispose(); |
| 58 | +} |
0 commit comments