Skip to content

Commit 479dd67

Browse files
author
jpalanco
committed
Merge pull request '[Feature] Client login v1: loopback PKCE + device flow, keychain storage, revoking logout' (#8) from auth-v1-login into main
2 parents 0f1753f + 74d1e30 commit 479dd67

41 files changed

Lines changed: 2275 additions & 588 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/commands/configSet.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import { friendlyError } from '../utils/errors.js'
44
export default async function ConfigSetCommand(key: string, value: string): Promise<void> {
55
try {
66
await setConfigValue(key, value)
7-
const isSensitive = key === 'token'
8-
console.log(`✓ Set ${key} = ${isSensitive ? '***' : value}`)
7+
console.log(`✓ Set ${key} = ${value}`)
98
} catch (err) {
109
console.error(`✗ Failed to set ${key}: ${friendlyError(err, 'Unknown error')}`)
1110
process.exit(1)

‎src/commands/login.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { PlexicusApi } from '../services/plexicusApi.js'
2+
import { saveCredential, envToken } from '../services/auth/credentials.js'
3+
import { interactiveLogin, type LoginMode } from '../services/auth/login.js'
4+
import { CredentialStore } from '../services/auth/keychain.js'
5+
import type { FetchFn, TokenResponse } from '../services/auth/oauthClient.js'
6+
import { canOpenBrowser as defaultCanOpenBrowser } from '../utils/canOpenBrowser.js'
7+
import { openBrowser as defaultOpenBrowser } from '../utils/openBrowser.js'
8+
import { deriveWebUrl } from '../utils/url.js'
9+
import type { Config } from '../services/config.js'
10+
11+
export interface LoginDeps {
12+
store?: CredentialStore
13+
fetch?: FetchFn
14+
canOpenBrowser?: () => boolean
15+
openBrowser?: (url: string) => Promise<boolean>
16+
print?: (line: string) => void
17+
warn?: (line: string) => void
18+
sleep?: (ms: number) => Promise<void>
19+
now?: () => number
20+
loopbackTimeoutMs?: number
21+
env?: NodeJS.ProcessEnv
22+
}
23+
24+
export interface LoginOutcome {
25+
token: string
26+
email: string | null
27+
backend: string
28+
}
29+
30+
/**
31+
* `plexicus login [--device]`: interactive OAuth-style login (loopback + PKCE by default, device
32+
* flow on request or when no browser can be opened). The minted token goes straight to the keychain;
33+
* it is never printed.
34+
*/
35+
export async function runLogin(
36+
config: Pick<Config, 'serverUrl' | 'webUrl'>,
37+
opts: { device?: boolean } = {},
38+
deps: LoginDeps = {},
39+
): Promise<LoginOutcome> {
40+
const print = deps.print ?? ((l: string) => console.log(l))
41+
const warn = deps.warn ?? ((l: string) => console.warn(l))
42+
const mode: LoginMode = opts.device ? 'device' : 'auto'
43+
44+
const tokenResponse: TokenResponse = await interactiveLogin({
45+
apiUrl: config.serverUrl,
46+
webUrl: deriveWebUrl(config),
47+
mode,
48+
canOpenBrowser: (deps.canOpenBrowser ?? defaultCanOpenBrowser)(),
49+
openBrowser: deps.openBrowser ?? defaultOpenBrowser,
50+
print,
51+
fetch: deps.fetch,
52+
loopbackTimeoutMs: deps.loopbackTimeoutMs,
53+
sleep: deps.sleep,
54+
now: deps.now,
55+
})
56+
57+
// Store first: the token was minted with the user's consent and must not be lost to a lookup error.
58+
const saved = await saveCredential(config.serverUrl, tokenResponse.access_token, deps.store)
59+
if (saved.warning) warn(saved.warning)
60+
61+
let email: string | null = null
62+
try {
63+
const user = await new PlexicusApi({ baseUrl: config.serverUrl, token: tokenResponse.access_token }).getSession()
64+
email = user.email
65+
} catch {
66+
// Display only; the token is already stored.
67+
}
68+
if (envToken(deps.env)) {
69+
warn('Note: PLEXICUS_TOKEN is set in your environment and takes precedence over the stored login.')
70+
}
71+
return { token: tokenResponse.access_token, email, backend: saved.backend }
72+
}

‎src/commands/logout.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import { PlexicusApi } from '../services/plexicusApi.js'
2+
import { accountFor, clearCredential, envToken } from '../services/auth/credentials.js'
3+
import { CredentialStore } from '../services/auth/keychain.js'
4+
import { friendlyError, PlexicusAuthError } from '../utils/errors.js'
5+
import type { Config } from '../services/config.js'
6+
7+
export interface LogoutDeps {
8+
store?: CredentialStore
9+
/** Calls DELETE /users/me/api-tokens/self with `token`; injectable for tests. */
10+
revoke?: (serverUrl: string, token: string) => Promise<void>
11+
env?: NodeJS.ProcessEnv
12+
}
13+
14+
export interface LogoutResult {
15+
/** 'none' = nothing was stored; 'revoked' = server confirmed; 'already-invalid' = 401; 'failed' = server call failed. */
16+
server: 'none' | 'revoked' | 'already-invalid' | 'failed'
17+
clearedLocal: boolean
18+
messages: string[]
19+
exitCode: 0
20+
}
21+
22+
const REVOKE_HINT = 'Revoke it in the web app under Settings -> API tokens.'
23+
24+
/**
25+
* Logout per AUTH-API-CONTRACT: revoke the calling API token on the server, then delete the
26+
* keychain item and the file fallback. A server failure never blocks the local cleanup.
27+
*/
28+
export async function runLogout(config: Pick<Config, 'serverUrl'>, deps: LogoutDeps = {}): Promise<LogoutResult> {
29+
const store = deps.store ?? new CredentialStore()
30+
const account = accountFor(config.serverUrl)
31+
const stored = await store.get(account)
32+
const messages: string[] = []
33+
34+
if (!stored) {
35+
messages.push('Not logged in (no stored token).')
36+
if (envToken(deps.env)) {
37+
messages.push('PLEXICUS_TOKEN is set in your environment; unset it to stop using that token. It is not stored by plexicus.')
38+
}
39+
return { server: 'none', clearedLocal: false, messages, exitCode: 0 }
40+
}
41+
42+
const revoke =
43+
deps.revoke ??
44+
(async (serverUrl: string, token: string) => {
45+
await new PlexicusApi({ baseUrl: serverUrl, token }).logout()
46+
})
47+
48+
let server: LogoutResult['server'] = 'revoked'
49+
try {
50+
await revoke(config.serverUrl, stored.token)
51+
} catch (err) {
52+
if (err instanceof PlexicusAuthError) {
53+
server = 'already-invalid'
54+
} else {
55+
server = 'failed'
56+
messages.push(`Could not revoke the token on the server (${friendlyError(err, 'request failed')}).`)
57+
}
58+
}
59+
60+
await clearCredential(config.serverUrl, store)
61+
62+
if (server === 'failed') {
63+
messages.push(`The token was removed from this machine but may still be valid. ${REVOKE_HINT}`)
64+
} else if (server === 'already-invalid') {
65+
messages.push('Logged out. The token was already invalid on the server; it was removed from this machine.')
66+
} else {
67+
messages.push('Logged out. The token was revoked on the server and removed from this machine.')
68+
}
69+
if (envToken(deps.env)) {
70+
messages.push('PLEXICUS_TOKEN is still set in your environment; unset it to stop using that token.')
71+
}
72+
return { server, clearedLocal: true, messages, exitCode: 0 }
73+
}

‎src/components/App.tsx‎

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@ import { ReposPanel } from './ReposPanel.js'
88
import { FindingDetailScreen } from './FindingDetailScreen.js'
99
import { FilterModal } from './FilterModal.js'
1010
import { StatusModal } from './StatusModal.js'
11-
import { LoginForm } from './LoginForm.js'
1211
import { FirstRunWizard } from './FirstRunWizard.js'
1312
import { findCommand } from '../commands.js'
1413
import { useWebSocket } from '../hooks/useWebSocket.js'
1514
import { filterCommands } from '../utils/replCommands.js'
1615
import { friendlyError } from '../utils/errors.js'
1716
import { createApiClient } from '../services/apiClient.js'
17+
import { PlexicusApi } from '../services/plexicusApi.js'
18+
import { PlexicusAuthError } from '../utils/errors.js'
1819
import type { Config } from '../services/config.js'
1920

2021
interface AppProps {
@@ -24,6 +25,8 @@ interface AppProps {
2425
config?: Config
2526
}
2627

28+
// The token comes from the credential store (or PLEXICUS_TOKEN) resolved in main.tsx; the TUI never
29+
// asks for a password. A rejected token ends the session with a pointer to `plexicus login`.
2730
function AuthGate({
2831
token,
2932
config,
@@ -33,17 +36,60 @@ function AuthGate({
3336
config?: Config
3437
children: React.ReactNode
3538
}) {
36-
const { state } = useAppState()
39+
const { state, dispatch } = useAppState()
40+
const { exit } = useApp()
3741
const [needsFirstRun, setNeedsFirstRun] = useState(
3842
!config?.serverUrl || config.serverUrl === '',
3943
)
44+
const [failure, setFailure] = useState<string | null>(null)
45+
46+
useEffect(() => {
47+
if (needsFirstRun || state.isAuthenticated) return
48+
if (!token) {
49+
setFailure('Not logged in. Run `plexicus login`.')
50+
return
51+
}
52+
let cancelled = false
53+
new PlexicusApi({ baseUrl: config?.serverUrl ?? 'https://api.app.plexicus.ai', token })
54+
.getSession()
55+
.then(user => {
56+
if (!cancelled) dispatch({ type: 'auth/set', payload: { user, token } })
57+
})
58+
.catch(err => {
59+
if (cancelled) return
60+
setFailure(
61+
err instanceof PlexicusAuthError
62+
? 'Your token is invalid, expired or was revoked. Run `plexicus login`.'
63+
: friendlyError(err, 'Could not verify your session'),
64+
)
65+
})
66+
return () => { cancelled = true }
67+
}, [needsFirstRun, state.isAuthenticated, token])
68+
69+
useEffect(() => {
70+
if (!failure) return
71+
const t = setTimeout(() => exit(), 100)
72+
return () => clearTimeout(t)
73+
}, [failure])
4074

4175
if (needsFirstRun) {
4276
return <FirstRunWizard onComplete={() => setNeedsFirstRun(false)} />
4377
}
4478

79+
if (failure) {
80+
return (
81+
<Box padding={1}>
82+
<Text color="red">{failure}</Text>
83+
</Box>
84+
)
85+
}
86+
4587
if (!state.isAuthenticated) {
46-
return <LoginForm prefilledToken={token ?? process.env.PLEXICUS_TOKEN} />
88+
return (
89+
<Box padding={1}>
90+
<Text color="yellow">Verifying your session...</Text>
91+
</Box>
92+
)
4793
}
4894

4995
return <>{children}</>

0 commit comments

Comments
 (0)