Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 19 additions & 43 deletions apps/desktop/electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ import {
tokenNeedsRefresh
} from './native-oauth'
import { runNativeLogin } from './native-oauth-login'
import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store'
import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { createKeepAwake } from './power-save'
import { FirstRunSetupResetError, runPrimaryBackendStartup } from './primary-backend-startup'
Expand Down Expand Up @@ -6189,35 +6190,24 @@ function _nativeTokenStorePath() {
return path.join(app.getPath('userData'), 'native-oauth-tokens.json')
}

function _readNativeTokenStore(): Record<string, any> {
try {
const raw = fs.readFileSync(_nativeTokenStorePath(), 'utf8')
const parsed = JSON.parse(raw)

return parsed && typeof parsed === 'object' ? parsed : {}
} catch {
return {}
// The electron-coupled half of the token store: safeStorage encryption plus the
// userData file. native-token-store.ts owns the serialization/parse round trip
// so it can be tested without an Electron runtime.
function _nativeTokenStoreIo(): NativeTokenStoreIo {
return {
encrypt: encryptDesktopSecret,
decrypt: decryptDesktopSecret,
readStoreText: () => fs.readFileSync(_nativeTokenStorePath(), 'utf8'),
writeStoreText: (text: string) => {
fs.mkdirSync(path.dirname(_nativeTokenStorePath()), { recursive: true })
fs.writeFileSync(_nativeTokenStorePath(), text, { mode: 0o600 })
},
rememberLog
}
}

function _persistNativeTokens(baseUrl: string, tokens: NativeTokenSet | null) {
const store = _readNativeTokenStore()

if (tokens) {
// Encrypt the whole token set as one blob so the refresh token never
// lands in plaintext on disk. Reuse the hardened encrypt helper.
const secret = encryptDesktopSecret(JSON.stringify(tokens))
store[baseUrl] = secret
} else {
delete store[baseUrl]
}

try {
fs.mkdirSync(path.dirname(_nativeTokenStorePath()), { recursive: true })
fs.writeFileSync(_nativeTokenStorePath(), JSON.stringify(store), { mode: 0o600 })
} catch (error) {
rememberLog(`[native-oauth] failed to persist tokens: ${(error as Error).message}`)
}
persistNativeTokenSet(baseUrl, tokens, _nativeTokenStoreIo())
}

function _loadNativeTokens(baseUrl: string): NativeTokenSet | null {
Expand All @@ -6227,27 +6217,13 @@ function _loadNativeTokens(baseUrl: string): NativeTokenSet | null {
return cached
}

const store = _readNativeTokenStore()
const secret = store[baseUrl]

if (!secret) {
return null
}

try {
const plaintext = decryptDesktopSecret(secret)

if (!plaintext) {
return null
}
const tokens = loadNativeTokenSet(baseUrl, _nativeTokenStoreIo())

const tokens = parseTokenResponse(JSON.parse(plaintext))
if (tokens) {
_nativeTokens.set(baseUrl, tokens)

return tokens
} catch {
return null
}

return tokens
}

function _storeNativeTokens(baseUrl: string, tokens: NativeTokenSet) {
Expand Down
37 changes: 37 additions & 0 deletions apps/desktop/electron/native-oauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
nativeRefreshUrl,
nativeTokenUrl,
parseLoopbackCallback,
parseStoredTokenSet,
parseTokenResponse,
resolveLoginStrategy,
statusSupportsNativeFlow,
Expand Down Expand Up @@ -176,6 +177,42 @@ test('parseTokenResponse tolerates an absent refresh token / expiry', () => {
assert.equal(t.expiresAt, 0)
})

test('parseStoredTokenSet maps the encrypted on-disk camelCase shape', () => {
const t = parseStoredTokenSet({
accessToken: 'AT-stored',
refreshToken: 'RT-stored',
expiresAt: 1893456000,
provider: 'self-hosted',
userId: 'u-stored'
})

assert.equal(t.accessToken, 'AT-stored')
assert.equal(t.refreshToken, 'RT-stored')
assert.equal(t.expiresAt, 1893456000)
assert.equal(t.provider, 'self-hosted')
assert.equal(t.userId, 'u-stored')
})

test('parseTokenResponse cannot read a persisted set (the reload bug #73271)', () => {
// Guards against regressing to the wrong parser on the reload path: a
// persisted camelCase set has no snake_case access_token, so the raw-response
// parser throws — which is exactly why the stored path must use
// parseStoredTokenSet instead.
const persisted = JSON.parse(
JSON.stringify({ accessToken: 'AT', refreshToken: 'RT', expiresAt: 1, provider: 'nous', userId: 'u' })
)

assert.throws(() => parseTokenResponse(persisted), /missing access_token/i)
assert.equal(parseStoredTokenSet(persisted).accessToken, 'AT')
})

test('parseStoredTokenSet rejects a non-normalized server response', () => {
assert.throws(
() => parseStoredTokenSet({ access_token: 'AT-server' }),
/missing accessToken/i
)
})

// --- refresh timing ---

test('tokenNeedsRefresh respects the skew window', () => {
Expand Down
25 changes: 25 additions & 0 deletions apps/desktop/electron/native-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,31 @@ export function parseTokenResponse(body: any): NativeTokenSet {
}
}

/**
* Validate a token set loaded from the encrypted local store.
*
* The stored representation is already normalized as NativeTokenSet and
* therefore uses camelCase. Gateway token responses use snake_case and
* remain handled separately by parseTokenResponse().
*/
export function parseStoredTokenSet(body: any): NativeTokenSet {
const accessToken = String(body?.accessToken || '')

if (!accessToken) {
throw new Error('Stored token set missing accessToken')
}

const expiresAt = Number(body?.expiresAt)

return {
accessToken,
refreshToken: String(body?.refreshToken || ''),
expiresAt: Number.isFinite(expiresAt) ? expiresAt : 0,
provider: String(body?.provider || ''),
userId: String(body?.userId || '')
}
}

/**
* True when a stored token set is at/near expiry and should be refreshed
* before use. `skewSeconds` refreshes slightly early to avoid a race where
Expand Down
Loading
Loading