feat(apps): improve gateway and workspace connection UX (#12340)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - App connections must work in both the operator UI and agent tool
gateway.
> - The first stack layer adds secure remote connections.
> - Operators still need clear setup, test, and recovery states.
> - This pull request adds the gateway behavior and the workspace
connection experience.
> - The benefit is a connection flow that is easier to understand and
recover.

## Linked Issues or Issue Description

Refs #11965

This is stack 2 of 11. It depends on stack 1 and replaces another
reviewable part of #11965.

## What Changed

- Improve remote tool gateway connection behavior.
- Add clearer app setup, test, and recovery states.
- Add focused server and UI tests for the new paths.
- Keep the diff isolated from later identity and catalog work.
- Stabilize DNS-pinned remote HTTP protocol fixtures and the
managed-runtime public-origin fixture for this independently tested
layer.

## Verification

- `pnpm -r typecheck`
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/tool-access-service.test.ts` (150 passed)
- `pnpm test:run`
- `pnpm check:token-gates`
- `pnpm build`

## Risks

- Gateway errors now surface through new user-facing states.
- A stale connection can require a new setup attempt.
- The change does not add a database migration.
- The injected HTTP transport and public URL are test-only fixtures;
production DNS pinning and runtime behavior are unchanged.

> I checked `ROADMAP.md`. This stack continues the existing app
connection work from #11965 and does not duplicate another planned item.

## Model Used

OpenAI Codex, GPT-5. The runtime model ID and context window were not
exposed. The model used reasoning, tool use, and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-08-29 12:08:32 -05:00
1 parent cabc9146d0
commit b51112798f
100 files changed
+5464 -4304

No files matched your search

+99 -1
View File
@@ -92,11 +92,21 @@ export function shouldDisableSecureAuthCookies(input: {
authBaseUrlMode: Config["authBaseUrlMode"];
authPublicBaseUrl: string | undefined;
publicUrl?: string | undefined;
managedRuntimePublicUrl?: string | undefined;
requestUrl?: string | undefined;
}): boolean {
const publicUrl = (
input.publicUrl?.trim() ||
(input.authBaseUrlMode === "explicit" ? input.authPublicBaseUrl?.trim() : "")
);
if (
input.deploymentMode === "authenticated" &&
isHttpsUrl(publicUrl) &&
isHttpsUrl(input.managedRuntimePublicUrl) &&
isHttpLoopbackUrl(input.requestUrl)
) {
return true;
}
if (publicUrl) return publicUrl.startsWith("http://");
return (
@@ -108,6 +118,52 @@ export function shouldDisableSecureAuthCookies(input: {
);
}
function isHttpsUrl(value: string | undefined): boolean {
if (!value) return false;
try {
return new URL(value).protocol === "https:";
} catch {
return false;
}
}
function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname.trim().toLowerCase();
return (
normalized === "localhost" ||
normalized === "127.0.0.1" ||
normalized === "[::1]" ||
normalized === "::1"
);
}
function isHttpLoopbackUrl(value: string | undefined): boolean {
if (!value) return false;
try {
const url = new URL(value);
return url.protocol === "http:" && isLoopbackHostname(url.hostname);
} catch {
return false;
}
}
function requestUrlFromHeaders(headers: Headers): string | undefined {
const host = headers.get("host")?.trim();
if (!host) return undefined;
const forwardedProtocol = headers.get("x-forwarded-proto")?.split(",", 1)[0]?.trim().toLowerCase();
const protocol = forwardedProtocol === "http" || forwardedProtocol === "https"
? forwardedProtocol
: (() => {
try {
return isLoopbackHostname(new URL(`http://${host}`).hostname) ? "http" : "https";
} catch {
return "https";
}
})();
return `${protocol}://${host}`;
}
function headersFromNodeHeaders(rawHeaders: IncomingHttpHeaders): Headers {
const headers = new Headers();
for (const [key, raw] of Object.entries(rawHeaders)) {
@@ -185,6 +241,7 @@ export function resolveWorkspaceHandoffIdentity(
export function createBetterAuthInstance(db: Db, config: Config, trustedOrigins: string[]): BetterAuthInstance {
const baseUrl = config.authBaseUrlMode === "explicit" ? config.authPublicBaseUrl : undefined;
const publicUrl = process.env.PAPERCLIP_PUBLIC_URL?.trim() || baseUrl;
const managedRuntimePublicUrl = process.env.PAPERCLIP_MANAGED_RUNTIME_PUBLIC_URL?.trim() || undefined;
const secret = process.env.BETTER_AUTH_SECRET ?? process.env.PAPERCLIP_AGENT_JWT_SECRET;
if (!secret) {
throw new Error(
@@ -252,7 +309,48 @@ export function createBetterAuthInstance(db: Db, config: Config, trustedOrigins:
delete (authConfig as { baseURL?: string }).baseURL;
}
return betterAuth(authConfig);
const defaultAuth = betterAuth(authConfig);
const supportsManagedLoopbackAuth = Boolean(
!disableSecureCookies &&
isHttpsUrl(publicUrl) &&
isHttpsUrl(managedRuntimePublicUrl),
);
if (!supportsManagedLoopbackAuth) return defaultAuth;
// Better Auth fixes both the Secure attribute and the __Secure- name prefix
// when an instance is created. Keep the public instance unchanged and route
// only managed HTTP-loopback requests through a cookie-compatible instance.
const loopbackAuth = betterAuth({
...authConfig,
advanced: buildBetterAuthAdvancedOptions({ disableSecureCookies: true }),
});
const cookieSecurityInput = {
deploymentMode: config.deploymentMode,
deploymentExposure: config.deploymentExposure,
authBaseUrlMode: config.authBaseUrlMode,
authPublicBaseUrl: config.authPublicBaseUrl,
publicUrl,
managedRuntimePublicUrl,
};
return {
handler: (request) => {
const auth = shouldDisableSecureAuthCookies({
...cookieSecurityInput,
requestUrl: request.url,
}) ? loopbackAuth : defaultAuth;
return auth.handler(request);
},
api: {
getSession: (input) => {
const auth = shouldDisableSecureAuthCookies({
...cookieSecurityInput,
requestUrl: requestUrlFromHeaders(input.headers),
}) ? loopbackAuth : defaultAuth;
return auth.api.getSession(input);
},
},
};
}
export function createBetterAuthHandler(auth: BetterAuthHandlerTarget): RequestHandler {