Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
999b2a8
CLI: Implement `auth login` command
fredrikekelund Nov 5, 2025
8650b02
Fix lint and tests
fredrikekelund Nov 6, 2025
fc661e0
Add tests, tweak command
fredrikekelund Nov 6, 2025
c8b228c
Consider expiration time
fredrikekelund Nov 6, 2025
9fcc45f
Move logic around
fredrikekelund Nov 6, 2025
36e6059
Unwrap
fredrikekelund Nov 6, 2025
a228ae9
Fix type error
fredrikekelund Nov 6, 2025
b838c0c
CLI: Implement `auth logout` command
fredrikekelund Nov 6, 2025
4634320
CLI: Implement `auth status` command
fredrikekelund Nov 6, 2025
c1799fe
Address review comments
fredrikekelund Nov 6, 2025
23aa26c
Reject unsupported platforms
fredrikekelund Nov 6, 2025
ed4f216
Merge branch 'f26d/cli-auth-login-command' into f26d/cli-auth-logout-…
fredrikekelund Nov 6, 2025
a68c998
Merge branch 'f26d/cli-auth-logout-command' into f26d/cli-auth-status…
fredrikekelund Nov 6, 2025
49966e3
Merge branch 'trunk' into f26d/cli-auth-login-command
fredrikekelund Nov 7, 2025
e13fd34
Address review feedback
fredrikekelund Nov 7, 2025
c72a70d
Fix test
fredrikekelund Nov 7, 2025
edb407f
Merge branch 'f26d/cli-auth-login-command' into f26d/cli-auth-logout-…
fredrikekelund Nov 7, 2025
6ba6a05
Fix
fredrikekelund Nov 7, 2025
6946324
Merge branch 'f26d/cli-auth-logout-command' into f26d/cli-auth-status…
fredrikekelund Nov 7, 2025
2908170
Merge branch 'trunk' into f26d/cli-auth-login-command
fredrikekelund Nov 17, 2025
fc816bf
docs: Update CLI documentation for auth login command
github-actions[bot] Nov 17, 2025
5748109
Restore package-lock.json
fredrikekelund Nov 17, 2025
7b1c743
Install inquirer dependency again
fredrikekelund Nov 17, 2025
d8feb6b
Tweak
fredrikekelund Nov 17, 2025
20c7566
Merge branch 'f26d/cli-auth-login-command' into f26d/cli-auth-logout-…
fredrikekelund Nov 17, 2025
fdb06df
Merge branch 'f26d/cli-auth-logout-command' into f26d/cli-auth-status…
fredrikekelund Nov 17, 2025
1cc1fe0
docs: Update CLI documentation for auth commands
github-actions[bot] Nov 17, 2025
9df3824
Merge branch 'trunk' into f26d/cli-auth-status-command
fredrikekelund Nov 17, 2025
3233720
docs: Add CLI documentation for auth status command
github-actions[bot] Nov 17, 2025
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions cli/commands/auth/status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { __, sprintf } from '@wordpress/i18n';
import { AuthCommandLoggerAction as LoggerAction } from 'common/logger-actions';
import { getUserInfo } from 'cli/lib/api';
import { getAuthToken } from 'cli/lib/appdata';
import { Logger, LoggerError } from 'cli/logger';
import { StudioArgv } from 'cli/types';

export async function runCommand(): Promise< void > {
const logger = new Logger< LoggerAction >();

logger.reportStart( LoggerAction.STATUS_CHECK, __( 'Checking authentication status…' ) );
let token: Awaited< ReturnType< typeof getAuthToken > >;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Style - The type annotation Awaited< ReturnType< typeof getAuthToken > > is correct but creates an unused variable declaration since token is reassigned in the try block. Consider simplifying:

logger.reportStart( LoggerAction.STATUS_CHECK, __( 'Checking authentication status…' ) );

try {
	const token = await getAuthToken();
	const userData = await getUserInfo( token.accessToken );
	logger.reportSuccess(
		sprintf( __( 'Successfully authenticated with WordPress.com as `%s`' ), userData.username )
	);
} catch ( error ) {
	// Handle getAuthToken errors
	if ( error instanceof LoggerError && error.message.includes( 'Authentication required' ) ) {
		logger.reportError( new LoggerError( __( 'Authentication token is invalid or expired' ) ) );
		return;
	}
	// Handle getUserInfo errors
	// ...
}

This would eliminate the uninitialized variable and flatten the nesting slightly. However, the current approach with two separate try-catch blocks does make the error handling more explicit, so this is a minor style preference.


try {
token = await getAuthToken();
} catch ( error ) {
logger.reportError( new LoggerError( __( 'Authentication token is invalid or expired' ) ) );
return;
}

try {
const userData = await getUserInfo( token.accessToken );
logger.reportSuccess(
sprintf( __( 'Successfully authenticated with WordPress.com as `%s`' ), userData.username )
);
} catch ( error ) {
if ( error instanceof LoggerError ) {
logger.reportError( error );
} else {
logger.reportError( new LoggerError( __( 'Failed to check authentication status' ), error ) );
}
}
}

export const registerCommand = ( yargs: StudioArgv ) => {
return yargs.command( {
command: 'status',
describe: __( 'Check authentication status' ),
handler: async () => {
await runCommand();
},
} );
};
87 changes: 87 additions & 0 deletions cli/commands/auth/tests/status.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { getUserInfo } from 'cli/lib/api';
import { getAuthToken } from 'cli/lib/appdata';
import { Logger, LoggerError } from 'cli/logger';

jest.mock( 'cli/lib/api' );
jest.mock( 'cli/lib/appdata' );
jest.mock( 'cli/logger' );

describe( 'Auth Status Command', () => {
const mockToken = {
accessToken: 'existing-token',
id: 999,
email: 'existing@example.com',
displayName: 'Existing User',
expiresIn: 1209600,
expirationTime: Date.now() + 1209600000,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing - Edge Case Coverage - Great test coverage overall! Consider adding one more test case for better completeness:

it( 'should report error when token is expired (past expirationTime)', async () => {
	const expiredToken = {
		...mockToken,
		expirationTime: Date.now() - 1000, // Expired 1 second ago
	};
	( getAuthToken as jest.Mock ).mockRejectedValue( new Error( 'Token expired' ) );

	const { runCommand } = await import( '../status' );
	await runCommand();

	expect( mockLogger.reportError ).toHaveBeenCalledWith( expect.any( LoggerError ) );
	expect( getUserInfo ).not.toHaveBeenCalled();
} );

This explicitly tests the expiration time check logic that's in getAuthToken at cli/lib/appdata.ts:152.

};
const mockUserData = {
username: 'testuser',
};

let mockLogger: {
reportStart: jest.Mock;
reportSuccess: jest.Mock;
reportError: jest.Mock;
};

beforeEach( () => {
jest.clearAllMocks();

mockLogger = {
reportStart: jest.fn(),
reportSuccess: jest.fn(),
reportError: jest.fn(),
};

( Logger as unknown as jest.Mock ).mockReturnValue( mockLogger );
( getAuthToken as jest.Mock ).mockResolvedValue( mockToken );
( getUserInfo as jest.Mock ).mockResolvedValue( mockUserData );
} );

afterEach( () => {
jest.restoreAllMocks();
} );

it( 'should report success when authenticated', async () => {
const { runCommand } = await import( '../status' );
await runCommand();

expect( mockLogger.reportStart ).toHaveBeenCalled();
expect( getAuthToken ).toHaveBeenCalled();
expect( getUserInfo ).toHaveBeenCalledWith( mockToken.accessToken );
expect( mockLogger.reportSuccess ).toHaveBeenCalledWith(
expect.stringContaining( 'Successfully authenticated with WordPress.com as `testuser`' )
);
} );

it( 'should report error when token is invalid', async () => {
( getAuthToken as jest.Mock ).mockRejectedValue( new Error( 'Token error' ) );

const { runCommand } = await import( '../status' );
await runCommand();

expect( mockLogger.reportError ).toHaveBeenCalled();
expect( mockLogger.reportError ).toHaveBeenCalledWith( expect.any( LoggerError ) );
expect( getUserInfo ).not.toHaveBeenCalled();
} );

it( 'should forward LoggerError from getUserInfo', async () => {
const apiError = new LoggerError( 'API error' );
( getUserInfo as jest.Mock ).mockRejectedValue( apiError );

const { runCommand } = await import( '../status' );
await runCommand();

expect( mockLogger.reportError ).toHaveBeenCalledWith( apiError );
} );

it( 'should wrap unknown error when getUserInfo fails', async () => {
( getUserInfo as jest.Mock ).mockRejectedValue( new Error( 'Unknown error' ) );

const { runCommand } = await import( '../status' );
await runCommand();

expect( mockLogger.reportError ).toHaveBeenCalledWith( expect.any( LoggerError ) );
} );
} );
2 changes: 2 additions & 0 deletions cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { StatsGroup, StatsMetric } from 'common/types/stats';
import yargs from 'yargs';
import { registerCommand as registerAuthLoginCommand } from 'cli/commands/auth/login';
import { registerCommand as registerAuthLogoutCommand } from 'cli/commands/auth/logout';
import { registerCommand as registerAuthStatusCommand } from 'cli/commands/auth/status';
import { registerCommand as registerCreateCommand } from 'cli/commands/preview/create';
import { registerCommand as registerDeleteCommand } from 'cli/commands/preview/delete';
import { registerCommand as registerListCommand } from 'cli/commands/preview/list';
Expand Down Expand Up @@ -50,6 +51,7 @@ async function main() {
.command( 'auth', __( 'Manage authentication' ), ( authYargs ) => {
registerAuthLoginCommand( authYargs );
registerAuthLogoutCommand( authYargs );
registerAuthStatusCommand( authYargs );
authYargs.demandCommand( 1, __( 'You must provide a valid auth command' ) );
} )
.command( 'preview', __( 'Manage preview sites' ), ( previewYargs ) => {
Expand Down
3 changes: 2 additions & 1 deletion cli/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ const userResponseSchema = z.object( {
ID: z.number(),
email: z.string().email(),
display_name: z.string(),
username: z.string(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Reusability & Architecture - I agree with @youknowriad's earlier comment. The getUserInfo, validateAccessToken, and revokeAuthToken functions are generic WordPress.com API operations that would benefit from being in a shared location like src/lib/ or common/lib/.

This would:

  1. Allow the main Electron app to reuse these functions for authentication UI
  2. Follow the DRY principle
  3. Make the API operations testable from both CLI and app contexts
  4. Align with the architecture documented in CLAUDE.md where common code goes in /common

Consider creating common/lib/wpcom-user-api.ts or similar for these user-related API functions.

} );

export async function getUserInfo(
Expand All @@ -157,7 +158,7 @@ export async function getUserInfo(
const wpcom = wpcomFactory( token, wpcomXhrRequest );
try {
const rawResponse = await wpcom.req.get( '/me', {
fields: 'ID,login,email,display_name',
fields: 'ID,username,email,display_name',
} );
return userResponseSchema.parse( rawResponse );
} catch ( error ) {
Expand Down
1 change: 1 addition & 0 deletions common/logger-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
export enum AuthCommandLoggerAction {
LOGIN = 'login',
LOGOUT = 'logout',
STATUS_CHECK = 'status_check',
}

export enum PreviewCommandLoggerAction {
Expand Down
31 changes: 31 additions & 0 deletions docs/ai-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,37 @@ node dist/cli/main.js auth logout
- Logout is shared between the CLI and the Studio desktop app
- The token is revoked on WordPress.com, invalidating all sessions using that token

#### `studio auth status`
Check authentication status and display the current WordPress.com username.

**Usage:**
```bash
node dist/cli/main.js auth status
```

**Description:**
This command checks if you are currently authenticated with WordPress.com by:
1. Reading the authentication token from your local app data
2. Verifying the token's validity by making an API request to WordPress.com
3. Displaying your WordPress.com username if authenticated

**Options:**
- None required

**Example:**
```bash
npm run cli:build
node dist/cli/main.js auth status
# Output when authenticated: ✓ Successfully authenticated with WordPress.com as `username`
# Output when not authenticated: ✗ Authentication token is invalid or expired
```

**Notes:**
- The command will check both token existence and validity
- If the token has expired (older than 2 weeks), you'll need to log in again
- Authentication state is shared between the CLI and the Studio desktop app
- No authentication token will be created; use `auth login` if not authenticated

### Preview Site Commands

See the existing preview site commands (create, list, delete, update) in `cli/commands/preview/`.
Expand Down
Loading