File size: 10,290 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | /**
* `claude mcp xaa` β manage the XAA (SEP-990) IdP connection.
*
* The IdP connection is user-level: configure once, all XAA-enabled MCP
* servers reuse it. Lives in settings.xaaIdp (non-secret) + a keychain slot
* keyed by issuer (secret). Separate trust domain from per-server AS secrets.
*/
import type { Command } from '@commander-js/extra-typings'
import { cliError, cliOk } from '../../cli/exit.js'
import {
acquireIdpIdToken,
clearIdpClientSecret,
clearIdpIdToken,
getCachedIdpIdToken,
getIdpClientSecret,
getXaaIdpSettings,
issuerKey,
saveIdpClientSecret,
saveIdpIdTokenFromJwt,
} from '../../services/mcp/xaaIdpLogin.js'
import { errorMessage } from '../../utils/errors.js'
import { updateSettingsForSource } from '../../utils/settings/settings.js'
export function registerMcpXaaIdpCommand(mcp: Command): void {
const xaaIdp = mcp
.command('xaa')
.description('Manage the XAA (SEP-990) IdP connection')
xaaIdp
.command('setup')
.description(
'Configure the IdP connection (one-time setup for all XAA-enabled servers)',
)
.requiredOption('--issuer <url>', 'IdP issuer URL (OIDC discovery)')
.requiredOption('--client-id <id>', "Claude Code's client_id at the IdP")
.option(
'--client-secret',
'Read IdP client secret from MCP_XAA_IDP_CLIENT_SECRET env var',
)
.option(
'--callback-port <port>',
'Fixed loopback callback port (only if IdP does not honor RFC 8252 port-any matching)',
)
.action(options => {
// Validate everything BEFORE any writes. An exit(1) mid-write leaves
// settings configured but keychain missing β confusing state.
// updateSettingsForSource doesn't schema-check on write; a non-URL
// issuer lands on disk and then poisons the whole userSettings source
// on next launch (SettingsSchema .url() fails β parseSettingsFile
// returns { settings: null }, dropping everything, not just xaaIdp).
let issuerUrl: URL
try {
issuerUrl = new URL(options.issuer)
} catch {
return cliError(
`Error: --issuer must be a valid URL (got "${options.issuer}")`,
)
}
// OIDC discovery + token exchange run against this host. Allow http://
// only for loopback (conformance harness mock IdP); anything else leaks
// the client secret and authorization code over plaintext.
if (
issuerUrl.protocol !== 'https:' &&
!(
issuerUrl.protocol === 'http:' &&
(issuerUrl.hostname === 'localhost' ||
issuerUrl.hostname === '127.0.0.1' ||
issuerUrl.hostname === '[::1]')
)
) {
return cliError(
`Error: --issuer must use https:// (got "${issuerUrl.protocol}//${issuerUrl.host}")`,
)
}
const callbackPort = options.callbackPort
? parseInt(options.callbackPort, 10)
: undefined
// callbackPort <= 0 fails Zod's .positive() on next launch β same
// settings-poisoning failure mode as the issuer check above.
if (
callbackPort !== undefined &&
(!Number.isInteger(callbackPort) || callbackPort <= 0)
) {
return cliError('Error: --callback-port must be a positive integer')
}
const secret = options.clientSecret
? process.env.MCP_XAA_IDP_CLIENT_SECRET
: undefined
if (options.clientSecret && !secret) {
return cliError(
'Error: --client-secret requires MCP_XAA_IDP_CLIENT_SECRET env var',
)
}
// Read old config now (before settings overwrite) so we can clear stale
// keychain slots after a successful write. `clear` can't do this after
// the fact β it reads the *current* settings.xaaIdp, which by then is
// the new one.
const old = getXaaIdpSettings()
const oldIssuer = old?.issuer
const oldClientId = old?.clientId
// callbackPort MUST be present (even as undefined) β mergeWith deep-merges
// and only deletes on explicit `undefined`, not on absent key. A conditional
// spread would leak a prior fixed port into a new IdP's config.
const { error } = updateSettingsForSource('userSettings', {
xaaIdp: {
issuer: options.issuer,
clientId: options.clientId,
callbackPort,
},
})
if (error) {
return cliError(`Error writing settings: ${error.message}`)
}
// Clear stale keychain slots only after settings write succeeded β
// otherwise a write failure leaves settings pointing at oldIssuer with
// its secret already gone. Compare via issuerKey(): trailing-slash or
// host-case differences normalize to the same keychain slot.
if (oldIssuer) {
if (issuerKey(oldIssuer) !== issuerKey(options.issuer)) {
clearIdpIdToken(oldIssuer)
clearIdpClientSecret(oldIssuer)
} else if (oldClientId !== options.clientId) {
// Same issuer slot but different OAuth client registration β the
// cached id_token's aud claim and the stored secret are both for the
// old client. `xaa login` would send {new clientId, old secret} and
// fail with opaque `invalid_client`; downstream SEP-990 exchange
// would fail aud validation. Keep both when clientId is unchanged:
// re-setup without --client-secret means "tweak port, keep secret".
clearIdpIdToken(oldIssuer)
clearIdpClientSecret(oldIssuer)
}
}
if (secret) {
const { success, warning } = saveIdpClientSecret(options.issuer, secret)
if (!success) {
return cliError(
`Error: settings written but keychain save failed${warning ? ` β ${warning}` : ''}. ` +
`Re-run with --client-secret once keychain is available.`,
)
}
}
cliOk(`XAA IdP connection configured for ${options.issuer}`)
})
xaaIdp
.command('login')
.description(
'Cache an IdP id_token so XAA-enabled MCP servers authenticate ' +
'silently. Default: run the OIDC browser login. With --id-token: ' +
'write a pre-obtained JWT directly (used by conformance/e2e tests ' +
'where the mock IdP does not serve /authorize).',
)
.option(
'--force',
'Ignore any cached id_token and re-login (useful after IdP-side revocation)',
)
// TODO(paulc): read the JWT from stdin instead of argv to keep it out of
// shell history. Fine for conformance (docker exec uses argv directly,
// no shell parser), but a real user would want `echo $TOKEN | ... --stdin`.
.option(
'--id-token <jwt>',
'Write this pre-obtained id_token directly to cache, skipping the OIDC browser login',
)
.action(async options => {
const idp = getXaaIdpSettings()
if (!idp) {
return cliError(
"Error: no XAA IdP connection. Run 'claude mcp xaa setup' first.",
)
}
// Direct-inject path: skip cache check, skip OIDC. Writing IS the
// operation. Issuer comes from settings (single source of truth), not
// a separate flag β one less thing to desync.
if (options.idToken) {
const expiresAt = saveIdpIdTokenFromJwt(idp.issuer, options.idToken)
return cliOk(
`id_token cached for ${idp.issuer} (expires ${new Date(expiresAt).toISOString()})`,
)
}
if (options.force) {
clearIdpIdToken(idp.issuer)
}
const wasCached = getCachedIdpIdToken(idp.issuer) !== undefined
if (wasCached) {
return cliOk(
`Already logged in to ${idp.issuer} (cached id_token still valid). Use --force to re-login.`,
)
}
process.stdout.write(`Opening browser for IdP login at ${idp.issuer}β¦\n`)
try {
await acquireIdpIdToken({
idpIssuer: idp.issuer,
idpClientId: idp.clientId,
idpClientSecret: getIdpClientSecret(idp.issuer),
callbackPort: idp.callbackPort,
onAuthorizationUrl: url => {
process.stdout.write(
`If the browser did not open, visit:\n ${url}\n`,
)
},
})
cliOk(
`Logged in. MCP servers with --xaa will now authenticate silently.`,
)
} catch (e) {
cliError(`IdP login failed: ${errorMessage(e)}`)
}
})
xaaIdp
.command('show')
.description('Show the current IdP connection config')
.action(() => {
const idp = getXaaIdpSettings()
if (!idp) {
return cliOk('No XAA IdP connection configured.')
}
const hasSecret = getIdpClientSecret(idp.issuer) !== undefined
const hasIdToken = getCachedIdpIdToken(idp.issuer) !== undefined
process.stdout.write(`Issuer: ${idp.issuer}\n`)
process.stdout.write(`Client ID: ${idp.clientId}\n`)
if (idp.callbackPort !== undefined) {
process.stdout.write(`Callback port: ${idp.callbackPort}\n`)
}
process.stdout.write(
`Client secret: ${hasSecret ? '(stored in keychain)' : '(not set β PKCE-only)'}\n`,
)
process.stdout.write(
`Logged in: ${hasIdToken ? 'yes (id_token cached)' : "no β run 'claude mcp xaa login'"}\n`,
)
cliOk()
})
xaaIdp
.command('clear')
.description('Clear the IdP connection config and cached id_token')
.action(() => {
// Read issuer first so we can clear the right keychain slots.
const idp = getXaaIdpSettings()
// updateSettingsForSource uses mergeWith: set to undefined (not delete)
// to signal key removal.
const { error } = updateSettingsForSource('userSettings', {
xaaIdp: undefined,
})
if (error) {
return cliError(`Error writing settings: ${error.message}`)
}
// Clear keychain only after settings write succeeded β otherwise a
// write failure leaves settings pointing at the IdP with its secrets
// already gone (same pattern as `setup`'s old-issuer cleanup).
if (idp) {
clearIdpIdToken(idp.issuer)
clearIdpClientSecret(idp.issuer)
}
cliOk('XAA IdP connection cleared')
})
}
|