Skip to content

An AI-powered task-management system you can drop into Cursor, Lovable, Windsurf, Roo, and others.

fix(auth): enforce org selection post-login and remove duplicate success messages

Eyal Toledano985b6e16facc
diff --git a/apps/cli/src/commands/auth.command.ts b/apps/cli/src/commands/auth.command.ts
index 440d35ba..0aa37879 100644
--- a/apps/cli/src/commands/auth.command.ts
+++ b/apps/cli/src/commands/auth.command.ts
@@ -427,7 +427,7 @@ Examples:
// Direct browser authentication - no menu needed
const credentials = await this.authenticateWithBrowser();
- ui.displaySuccess('Authentication successful!');
+ // Display user info (auth success message is already shown by authenticateWithBrowserMFA)
console.log(
chalk.gray(` Logged in as: ${credentials.email || credentials.userId}`)
);
@@ -569,7 +569,7 @@ Examples:
// Authenticate with the token
const credentials = await this.authenticateWithToken(token);
- ui.displaySuccess('Authentication successful!');
+ // Display user info (auth success message is already shown by authenticateWithToken spinner)
console.log(
chalk.gray(` Logged in as: ${credentials.email || credentials.userId}`)
);
diff --git a/apps/cli/src/commands/export.command.ts b/apps/cli/src/commands/export.command.ts
index eda2772c..913e5d5c 100644
--- a/apps/cli/src/commands/export.command.ts
+++ b/apps/cli/src/commands/export.command.ts
@@ -100,7 +100,7 @@ export class ExportCommand extends Command {
// Default action
this.action(async (options?: any) => {
- await this.executeExport(options);
+ return await this.executeExport(options);
});
}
diff --git a/apps/cli/src/utils/auth-guard.ts b/apps/cli/src/utils/auth-guard.ts
index a4028993..b326f9e7 100644
--- a/apps/cli/src/utils/auth-guard.ts
+++ b/apps/cli/src/utils/auth-guard.ts
@@ -5,12 +5,15 @@
*
* Uses the shared authenticateWithBrowserMFA utility for consistent
* login UX across all commands (auth login, parse-prd, export, etc.)
+ *
+ * After successful authentication, ensures org selection is completed.
*/
-import { type AuthCredentials, AuthDomain } from '@tm/core';
+import { type AuthCredentials, AuthDomain, AuthManager } from '@tm/core';
import chalk from 'chalk';
import inquirer from 'inquirer';
import { authenticateWithBrowserMFA } from './auth-ui.js';
+import { ensureOrgSelected } from './org-selection.js';
/**
* Options for the auth guard
@@ -71,6 +74,28 @@ export async function ensureAuthenticated(
// Check if already authenticated
const hasSession = await authDomain.hasValidSession();
if (hasSession) {
+ // Only get AuthManager when we need to check org selection
+ const authManager = AuthManager.getInstance();
+
+ // Check if org is already selected (quick check before any API calls)
+ const context = authManager.getContext();
+ if (context?.orgId) {
+ // Org already selected, return immediately without further API calls
+ return { authenticated: true };
+ }
+
+ // Org not selected, need to prompt
+ const orgResult = await ensureOrgSelected(authManager, {
+ promptMessage: 'Select an organization to continue:'
+ });
+
+ if (!orgResult.success) {
+ return {
+ authenticated: true,
+ error: orgResult.message || 'Organization selection required'
+ };
+ }
+
return { authenticated: true };
}
@@ -105,6 +130,28 @@ export async function ensureAuthenticated(
// Trigger OAuth flow using shared browser auth with MFA support
try {
const credentials = await authenticateWithBrowserMFA(authDomain);
+
+ // Display user info (auth success message is already shown by authenticateWithBrowserMFA)
+ if (credentials.email) {
+ console.log(chalk.gray(` Logged in as: ${credentials.email}`));
+ }
+ console.log('');
+
+ // After successful authentication, ensure org is selected
+ // This is REQUIRED for all Hamster operations
+ const authManager = AuthManager.getInstance();
+ const orgResult = await ensureOrgSelected(authManager, {
+ promptMessage: 'Select an organization to continue:'
+ });
+
+ if (!orgResult.success) {
+ return {
+ authenticated: true, // Auth succeeded, but org selection failed
+ credentials,
+ error: orgResult.message || 'Organization selection required'
+ };
+ }
+
return {
authenticated: true,
credentials
diff --git a/apps/cli/src/utils/index.ts b/apps/cli/src/utils/index.ts
index bb8681a5..39c81bc1 100644
--- a/apps/cli/src/utils/index.ts
+++ b/apps/cli/src/utils/index.ts
@@ -20,6 +20,12 @@ export {
type AuthGuardResult
} from './auth-guard.js';
+// Shared browser authentication with MFA support
+export { authenticateWithBrowserMFA } from './auth-ui.js';
+
+// Organization selection utility
+export { ensureOrgSelected, type OrgSelectionResult } from './org-selection.js';
+
// Command guard for local-only commands
export {
checkAndBlockIfAuthenticated,
diff --git a/packages/tm-core/src/modules/integration/services/export.service.ts b/packages/tm-core/src/modules/integration/services/export.service.ts
index 0eaea7c7..b5b3f1f9 100644
--- a/packages/tm-core/src/modules/integration/services/export.service.ts
+++ b/packages/tm-core/src/modules/integration/services/export.service.ts
@@ -1589,7 +1589,11 @@ export class ExportService {
const resultInvitations = Array.isArray(invitations)
? (invitations as Array<{
email: string;
- status: 'sent' | 'already_member' | 'already_invited' | 'failed';
+ status:
+ | 'sent'
+ | 'already_member'
+ | 'already_invited'
+ | 'failed';
}>)
: emails.map((email) => ({
email,
diff --git a/scripts/init.js b/scripts/init.js
index b8a9cf43..d2e5ff21 100755
--- a/scripts/init.js
+++ b/scripts/init.js
@@ -17,8 +17,8 @@ import { randomUUID } from 'crypto';
import fs from 'fs';
import path from 'path';
import readline from 'readline';
-import { ui } from '@tm/cli';
-import { AUTH_TIMEOUT_MS, AuthManager } from '@tm/core';
+import { authenticateWithBrowserMFA, ensureOrgSelected, ui } from '@tm/cli';
+import { AuthManager } from '@tm/core';
import boxen from 'boxen';
import chalk from 'chalk';
import figlet from 'figlet';
@@ -419,7 +419,8 @@ async function initializeProject(options = {}) {
log('success', 'Already authenticated with Hamster');
authCredentials = existingCredentials;
} else {
- // Trigger OAuth flow
+ // Use shared browser auth with MFA support
+ // This is the SAME auth flow used by 'tm auth login' and 'tm parse-prd'
log('info', 'Starting authentication flow...');
console.log(chalk.blue('\n🔐 Authentication Required\n'));
console.log(
@@ -430,94 +431,23 @@ async function initializeProject(options = {}) {
console.log(
chalk.gray(' This enables sync across devices with Hamster.\n')
);
- let countdownInterval = null;
- let authSpinner = null;
-
- const startCountdown = (totalMs) => {
- const startTime = Date.now();
- const endTime = startTime + totalMs;
-
- const updateCountdown = () => {
- const remaining = Math.max(0, endTime - Date.now());
- const mins = Math.floor(remaining / 60000);
- const secs = Math.floor((remaining % 60000) / 1000);
- const timeStr = `${mins}:${secs.toString().padStart(2, '0')}`;
-
- if (authSpinner) {
- authSpinner.text = `Waiting for authentication... ${chalk.cyan(timeStr)} remaining`;
- }
-
- if (remaining <= 0 && countdownInterval) {
- clearInterval(countdownInterval);
- }
- };
-
- authSpinner = ora({
- text: `Waiting for authentication... ${chalk.cyan('10:00')} remaining`,
- spinner: 'dots'
- }).start();
-
- countdownInterval = setInterval(updateCountdown, 1000);
- };
-
- const stopCountdown = (success) => {
- if (countdownInterval) {
- clearInterval(countdownInterval);
- countdownInterval = null;
- }
- if (authSpinner) {
- if (success) {
- authSpinner.succeed('Authentication successful!');
- } else {
- authSpinner.fail('Authentication failed');
- }
- authSpinner = null;
- }
- };
-
- authCredentials = await authManager.authenticateWithOAuth({
- openBrowser: async (authUrl) => {
- await open(authUrl);
- },
- timeout: AUTH_TIMEOUT_MS,
- onAuthUrl: (authUrl) => {
- console.log(
- chalk.blue.bold('\n[auth] Browser Authentication\n')
- );
- console.log(
- chalk.white(' Opening your browser to authenticate...')
- );
- console.log(
- chalk.gray(" If the browser doesn't open, visit:")
- );
- console.log(chalk.cyan.underline(` ${authUrl}\n`));
- },
- onWaitingForAuth: () => {
- console.log(
- chalk.dim(
- ' If you signed up, check your email to confirm your account.'
- )
- );
- console.log(
- chalk.dim(
- ' The CLI will automatically detect when you log in.\n'
- )
- );
- startCountdown(AUTH_TIMEOUT_MS);
- },
- onSuccess: () => {
- stopCountdown(true);
- },
- onError: (error) => {
- stopCountdown(false);
- log('error', `Authentication failed: ${error.message}`);
- }
- });
+
+ // Use shared auth utility - handles MFA automatically
+ authCredentials = await authenticateWithBrowserMFA(authManager);
// Track auth_completed event
- // TODO: Send to Segment telemetry when implemented
log('debug', `Auth completed - taskmaster_id: ${taskmasterId}`);
}
+
+ // Ensure org is selected (required for all Hamster operations)
+ // This runs for both new auth AND existing auth
+ // Uses shared utility from @tm/cli
+ const orgResult = await ensureOrgSelected(authManager, {
+ promptMessage: 'Select an organization to continue:'
+ });
+ if (!orgResult.success) {
+ log('warn', orgResult.message || 'Organization selection required');
+ }
} catch (authError) {
log(
'error',
@@ -721,6 +651,9 @@ async function initializeProject(options = {}) {
authCredentials
);
rl.close();
+ // Exit cleanly after command completes
+ // Required because Supabase client keeps connections alive
+ process.exit(0);
} catch (error) {
if (rl) {
rl.close();
diff --git a/scripts/modules/commands.js b/scripts/modules/commands.js
index e1c3961f..00de374e 100644
--- a/scripts/modules/commands.js
+++ b/scripts/modules/commands.js
@@ -63,7 +63,7 @@ import {
validateDependenciesCommand
} from './dependency-manager.js';
-import { checkAndBlockIfAuthenticated } from '@tm/cli';
+import { checkAndBlockIfAuthenticated, ensureOrgSelected } from '@tm/cli';
import { LOCAL_ONLY_COMMANDS } from '@tm/core';
import {
@@ -383,6 +383,19 @@ async function handleParsePrdToHamster(prdPath) {
const authManager = AuthManager.getInstance();
+ // Ensure an organization is selected before proceeding
+ const orgResult = await ensureOrgSelected(authManager, {
+ promptMessage: 'Select an organization to create the brief in:'
+ });
+ if (!orgResult.success) {
+ console.error(
+ chalk.red(
+ `\n ${orgResult.message || 'Organization selection cancelled.'}\n`
+ )
+ );
+ return;
+ }
+
// Read PRD file content
const prdContent = fs.readFileSync(prdPath, 'utf-8');
if (!prdContent.trim()) {