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
23 changes: 17 additions & 6 deletions src/main/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,15 @@ export interface CloudAuth {
accountKey: string
}

function cloudAuthFromStored(tokens: StoredTokens): CloudAuth {
const apiUrl = normalizeCloudApiUrl(tokens.apiUrl)
return {
accessToken: tokens.accessToken,
apiUrl,
accountKey: deriveCloudAuthAccountKey(apiUrl, tokens.accessToken, tokens.user)
}
}

function normalizeCloudApiUrl(url: string | undefined): string {
return (url || getApiUrl()).trim().replace(/\/+$/, '')
}
Expand Down Expand Up @@ -623,12 +632,7 @@ export async function resolveCloudAuth(): Promise<CloudAuth | null> {
? (await refreshStoredTokens(pearAuth)) ?? (loadTokens() ?? null)
: pearAuth
if (usable) {
const apiUrl = normalizeCloudApiUrl(usable.apiUrl)
return {
accessToken: usable.accessToken,
apiUrl,
accountKey: deriveCloudAuthAccountKey(apiUrl, usable.accessToken, usable.user)
}
return cloudAuthFromStored(usable)
}
}

Expand All @@ -645,6 +649,13 @@ export async function resolveCloudAuth(): Promise<CloudAuth | null> {
return null
}

export async function refreshCloudAuth(): Promise<CloudAuth | null> {
const pearAuth = loadTokens()
if (!pearAuth) return null
const refreshed = await refreshStoredTokens(pearAuth)
return refreshed ? cloudAuthFromStored(refreshed) : null
}
Comment on lines +652 to +657

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: refreshCloudAuth only tries to refresh Pear-stored tokens and immediately returns null when those tokens are absent, even though resolveCloudAuth also supports Cloud SDK credentials. This makes the new Unauthorized retry path fail for SDK-authenticated setups (env/file auth), because refresh is never attempted from that source. Make refreshCloudAuth fall back to re-resolving Cloud SDK auth so both auth sources are handled consistently. [incomplete implementation]

Severity Level: Major ⚠️
- ❌ Local integration mounts fail to recover after Unauthorized.
- ❌ Integration event subscriptions fail retry under SDK-only auth.
- ⚠️ Env/file-provisioned auth behaves worse than in-app login.
Steps of Reproduction ✅
1. Configure Pear to use only Cloud SDK auth so `loadTokens()` returns null and
`readCloudSdkAuth()` returns valid unexpired credentials (see `loadTokens` at
`src/main/auth.ts:226-235` and `resolveCloudAuth` at `src/main/auth.ts:102-121`).

2. Trigger integration mount reconciliation so
`IntegrationManager.syncLocalIntegrationMount` calls
`integrationMountManager.ensureMounted(...)` (see `src/main/integrations.ts:1718-1725`),
which in turn calls the private `mount()` method and obtains `auth` via
`resolveCloudAuth()` (see `src/main/integration-mounts.ts:224-231`).

3. During `mount()`, `setup.mountWorkspace(...)` is invoked for each mount (see
`startMount` in `src/main/integration-mounts.ts:53-70`); if the Cloud SDK access token is
rejected with 401/403, the error reaches the `catch` block where
`isUnauthorizedError(error)` returns true (see `isUnauthorizedError` at
`src/main/integration-mounts.ts:32-39`).

4. The Unauthorized retry path then calls `refreshCloudAuth()` (see
`src/main/integration-mounts.ts:75-80`), which immediately returns `null` when no
Pear-stored tokens exist (implementation at `src/main/auth.ts:134-139`), causing the code
to rethrow the original error instead of retrying with refreshed or re-resolved Cloud SDK
credentials; the same pattern exists for integration event subscriptions in
`getWorkspaceHandle()` (`src/main/integration-event-bridge.ts:24-67`), so
SDK-authenticated setups never benefit from the new Unauthorized retry behavior.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/main/auth.ts
**Line:** 652:657
**Comment:**
	*Incomplete Implementation: `refreshCloudAuth` only tries to refresh Pear-stored tokens and immediately returns `null` when those tokens are absent, even though `resolveCloudAuth` also supports Cloud SDK credentials. This makes the new Unauthorized retry path fail for SDK-authenticated setups (env/file auth), because refresh is never attempted from that source. Make `refreshCloudAuth` fall back to re-resolving Cloud SDK auth so both auth sources are handled consistently.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎


export async function ensureAuthenticated(apiUrl?: string): Promise<AuthStatus> {
const stored = loadTokens()
if (stored && !isTokenExpired(stored)) {
Expand Down
48 changes: 35 additions & 13 deletions src/main/integration-event-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,15 @@ function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}

function isUnauthorizedError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
(error as { httpStatus?: unknown; status?: unknown }).status
if (status === 401 || status === 403) return true
const message = (error as { message?: unknown }).message
return typeof message === 'string' && /\b(401|403|unauthor|forbidden)\b/i.test(message)
}
Comment on lines +104 to +111

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The regular expression /\b(401|403|unauthor|forbidden)\b/i will fail to match the word "unauthorized" because of the trailing word boundary \b. Since "unauthorized" continues with "ized", there is no word boundary after "unauthor", causing the match to fail. Changing "unauthor" to "unauthorized" ensures that the full word is matched correctly. Additionally, handling cases where the error is thrown directly as a string makes this utility more robust.

Suggested change
function isUnauthorizedError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
(error as { httpStatus?: unknown; status?: unknown }).status
if (status === 401 || status === 403) return true
const message = (error as { message?: unknown }).message
return typeof message === 'string' && /\b(401|403|unauthor|forbidden)\b/i.test(message)
}
function isUnauthorizedError(error: unknown): boolean {
if (!error) return false;
if (typeof error === 'string') {
return /\b(401|403|unauthorized|forbidden)\b/i.test(error);
}
if (typeof error !== 'object') return false;
const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
(error as { httpStatus?: unknown; status?: unknown }).status;
if (status === 401 || status === 403) return true;
const message = (error as { message?: unknown }).message;
return typeof message === 'string' && /\b(401|403|unauthorized|forbidden)\b/i.test(message);
}


function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}
Expand Down Expand Up @@ -933,8 +942,8 @@ export class IntegrationEventBridge {

private async getWorkspaceHandle(): Promise<RelayfileWorkspaceHandle> {
if (this.deps.getWorkspaceHandle) return this.deps.getWorkspaceHandle()
const { accountWorkspaceReadyRetryOptions, getAccountWorkspaceId, resolveCloudAuth } = await import('./auth.ts')
const auth = await resolveCloudAuth()
const { accountWorkspaceReadyRetryOptions, getAccountWorkspaceId, refreshCloudAuth, resolveCloudAuth } = await import('./auth.ts')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The dynamic import uses ./auth.ts while the rest of the code imports the same module via ./auth. In packaged/runtime builds this can break chunk/module resolution or create inconsistent module identity behavior for the same dependency. Use the same module specifier style as the rest of the codebase for this import. [api mismatch]

Severity Level: Critical 🚨
- ❌ Integration event bridge fails to initialize workspace handle.
- ❌ Event subscriptions for integrations never establish in packaged app.
- ⚠️ Inconsistent auth module identity complicates debugging and testing.
Steps of Reproduction ✅
1. Build and run the packaged Electron main process using `npm run build`, which compiles
`src/main/*.ts` (including `auth.ts` and `integration-event-bridge.ts`) to JavaScript
while static imports reference `./auth` without an extension (see usages in
`src/main/proactive-agent.ts:8`, `src/main/integrations.ts:5`,
`src/main/cloud-agent.ts:17`, `src/main/relay-workspace.ts:3`, and
`src/main/ipc-handlers.ts:21`).

2. In the running app, trigger integration event subscription reconciliation so
`IntegrationsManager.syncEventSubscriptions` calls `integrationEventBridge.reconcile(...)`
(see `src/main/integrations.ts:1652-1657`), which internally needs a Relay workspace
handle and calls the private `getWorkspaceHandle()` method (see
`src/main/integration-event-bridge.ts:24-88`).

3. `getWorkspaceHandle()` performs a dynamic import using the specifier `await
import('./auth.ts')` (see `src/main/integration-event-bridge.ts:24-27`), which in the
compiled JavaScript will try to load a module literally named `./auth.ts` even though the
built file is `auth.js` and all other imports target `./auth` without an extension.

4. This dynamic import rejects at runtime due to a failed module resolution or yields a
distinct module identity from the `./auth` import graph, causing `getWorkspaceHandle()` to
throw before resolving credentials, so `syncEventSubscriptions()` logs `[integrations]
Failed to reconcile integration event subscriptions` and returns false (see
`src/main/integrations.ts:13-22`), leaving integration events unsubscribed.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/main/integration-event-bridge.ts
**Line:** 945:945
**Comment:**
	*Api Mismatch: The dynamic import uses `./auth.ts` while the rest of the code imports the same module via `./auth`. In packaged/runtime builds this can break chunk/module resolution or create inconsistent module identity behavior for the same dependency. Use the same module specifier style as the rest of the codebase for this import.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

let auth = await resolveCloudAuth()
if (!auth) {
accountIntegrationEventHandle = null
throw new Error('cloud-auth-required')
Expand All @@ -950,18 +959,31 @@ export class IntegrationEventBridge {
return accountIntegrationEventHandle.handle
}

const tokenProvider = async (): Promise<string | undefined> => {
const fresh = await resolveCloudAuth()
return fresh?.accessToken ?? auth.accessToken
const joinWorkspace = async () => {
const tokenProvider = async (): Promise<string | undefined> => {
const fresh = await resolveCloudAuth()
return fresh?.accessToken ?? auth?.accessToken
}
const setup = new RelayfileSetup({
cloudApiUrl: auth.apiUrl,
accessToken: tokenProvider
})
return setup.joinWorkspace(accountWorkspaceId, {
agentName: INTEGRATION_EVENT_AGENT_NAME,
scopes: INTEGRATION_EVENT_SCOPES
})
}

let joined: Awaited<ReturnType<typeof joinWorkspace>>
try {
joined = await joinWorkspace()
} catch (error) {
if (!isUnauthorizedError(error)) throw error
const refreshed = await refreshCloudAuth()
if (!refreshed) throw error
auth = refreshed
joined = await joinWorkspace()
}
const setup = new RelayfileSetup({
cloudApiUrl: auth.apiUrl,
accessToken: tokenProvider
})
const joined = await setup.joinWorkspace(accountWorkspaceId, {
agentName: INTEGRATION_EVENT_AGENT_NAME,
scopes: INTEGRATION_EVENT_SCOPES
})
const relayWorkspaceId = joined.workspaceId
const workspaceTokenProvider = async (): Promise<string> => {
await joined.refreshToken()
Expand Down
43 changes: 34 additions & 9 deletions src/main/integration-mounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
RelayfileSetup,
type MountedWorkspaceHandle
} from '@relayfile/sdk'
import { accountWorkspaceReadyRetryOptions, getAccountWorkspaceId, resolveCloudAuth } from './auth'
import { accountWorkspaceReadyRetryOptions, getAccountWorkspaceId, refreshCloudAuth, resolveCloudAuth } from './auth'
import { createPearMountLauncher } from './relayfile-mount-launcher'

const MOUNT_READY_TIMEOUT_MS = 60_000
Expand All @@ -29,6 +29,15 @@ function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}

function isUnauthorizedError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
(error as { httpStatus?: unknown; status?: unknown }).status
if (status === 401 || status === 403) return true
const message = (error as { message?: unknown }).message
return typeof message === 'string' && /\b(401|403|unauthor|forbidden)\b/i.test(message)
}
Comment on lines +32 to +39

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The regular expression /\b(401|403|unauthor|forbidden)\b/i will fail to match the word "unauthorized" because of the trailing word boundary \b. Since "unauthorized" continues with "ized", there is no word boundary after "unauthor", causing the match to fail. Changing "unauthor" to "unauthorized" ensures that the full word is matched correctly. Additionally, handling cases where the error is thrown directly as a string makes this utility more robust.

function isUnauthorizedError(error: unknown): boolean {
  if (!error) return false;
  if (typeof error === 'string') {
    return /\b(401|403|unauthorized|forbidden)\b/i.test(error);
  }
  if (typeof error !== 'object') return false;
  const status = (error as { httpStatus?: unknown; status?: unknown }).httpStatus ??
    (error as { httpStatus?: unknown; status?: unknown }).status;
  if (status === 401 || status === 403) return true;
  const message = (error as { message?: unknown }).message;
  return typeof message === 'string' && /\b(401|403|unauthorized|forbidden)\b/i.test(message);
}


function sanitizePathSegment(value: string): string {
return value
.trim()
Expand Down Expand Up @@ -238,13 +247,8 @@ export class IntegrationMountManager {
await ensureProtectedDirectory(integrationMountWorkspaceRoot(workspaceId))
await ensureProtectedDirectory(mountRoot)

const setup = new RelayfileSetup({
cloudApiUrl: auth.apiUrl,
accessToken: async () => {
const fresh = await resolveCloudAuth()
return fresh?.accessToken ?? auth.accessToken
}
})
let activeAuth = auth
let setup = this.createSetup(activeAuth)

const mountSpecs = this.mountSpecsFor(mountPaths, mountRoot)
const expectedRemotePaths = mountSpecs.map((spec) => spec.remotePath)
Expand All @@ -269,7 +273,7 @@ export class IntegrationMountManager {

await ensureProtectedDirectory(spec.localDir)
try {
const handle = await setup.mountWorkspace({
const startMount = async (): Promise<MountedWorkspaceHandle> => setup.mountWorkspace({
workspaceId,
localDir: spec.localDir,
remotePath: spec.remotePath,
Expand All @@ -287,6 +291,17 @@ export class IntegrationMountManager {
}),
readyTimeoutMs: MOUNT_READY_TIMEOUT_MS
})
let handle: MountedWorkspaceHandle
try {
handle = await startMount()
} catch (error) {
if (!isUnauthorizedError(error)) throw error
const refreshed = await refreshCloudAuth()
if (!refreshed) throw error
activeAuth = refreshed
setup = this.createSetup(activeAuth)
handle = await startMount()
}
this.handles.set(spec.remotePath, handle)
this.scheduleRefresh(spec.remotePath, handle)
} catch (error) {
Expand All @@ -300,6 +315,16 @@ export class IntegrationMountManager {
await this.removeLegacyIntegrationMountRoot(mountRoot)
}

private createSetup(auth: { apiUrl: string; accessToken: string }): RelayfileSetup {
return new RelayfileSetup({
cloudApiUrl: auth.apiUrl,
accessToken: async () => {
const fresh = await resolveCloudAuth()
return fresh?.accessToken ?? auth.accessToken
}
})
}

private mountSpecsFor(mountPaths: string[], mountRoot: string): IntegrationMountSpec[] {
const specs: IntegrationMountSpec[] = mountPaths.map((mountPath) => {
const providerSegment = remotePathSegments(mountPath)[0] || 'integration'
Expand Down
Loading