Elffuss BraidHub

kikocis/continue public

feat: auto-select scope for org api keys in cn (p2)
Changeset8f2687024467de1bdec551cf032f31ef977a5bc0a22b399a87f1f15b37d6c997
AuthorNate <sestinj@gmail.com> · 2025-09-14 11:48 -07:00
CommitterNate <sestinj@gmail.com> · 2025-09-14 11:48 -07:00
Parents09dcac3b6da9

Browse the files at this changeset

1 file changed

modified extensions/cli/src/auth/workos.ts +54 −2
@@ -540,8 +540,10 @@
540540 );
541541 }
542542 } else if (isEnvironmentAuthConfig(authConfig)) {
543- // No CLI organization slug (or "personal" was specified) - return as-is
544- return authConfig;
543+ // No CLI organization slug (or "personal" was specified)
544+ // If using API key auth, attempt to resolve its organization scope once
545+ const resolved = await resolveOrgScopeForApiKey(authConfig);
546+ return resolved;
545547 }
546548
547549 // If not authenticated, return as-is
@@ -577,6 +579,56 @@
577579 return autoSelectOrganization(authenticatedConfig);
578580 }
579581
582+/**
583+ * Attempts to resolve the organization scope for API key auth (environment-based auth).
584+ * Calls a lightweight backend endpoint to determine if the API key is an org-scoped key.
585+ * If successful, returns a new EnvironmentAuthConfig with organizationId set; otherwise returns the original config.
586+ */
587+async function resolveOrgScopeForApiKey(
588+ envConfig: EnvironmentAuthConfig,
589+): Promise<EnvironmentAuthConfig> {
590+ // If already set (including explicit null), return as-is
591+ if (envConfig.organizationId !== null) {
592+ return envConfig;
593+ }
594+
595+ const accessToken = envConfig.accessToken;
596+ if (!accessToken) return envConfig;
597+
598+ try {
599+ // Prefer a dedicated endpoint for scope discovery. This should return JSON like:
600+ // { organizationId: string | null } (aka orgScopeId)
601+ const url = new URL("auth/scope", env.apiBase);
602+ const resp = await fetch(url, {
603+ method: "GET",
604+ headers: {
605+ Authorization: `Bearer ${accessToken}`,
606+ "Content-Type": "application/json",
607+ },
608+ });
609+
610+ if (!resp.ok) {
611+ // Gracefully ignore if the endpoint isn't available yet (e.g., 404) or other non-2xx errors
612+ return envConfig;
613+ }
614+
615+ const data: any = await resp.json().catch(() => ({}));
616+ const orgId =
617+ data?.organizationId ?? data?.orgScopeId ?? data?.organization?.id ?? null;
618+
619+ if (orgId && typeof orgId === "string") {
620+ return {
621+ ...envConfig,
622+ organizationId: orgId,
623+ };
624+ }
625+ } catch {
626+ // Network or parsing issues: leave config unchanged
627+ }
628+
629+ return envConfig;
630+}
631+
580632 /**
581633 * Gets the list of available organizations for the user
582634 */