Skip to content

Commit aff81b5

Browse files
Upgrade WorkOS to v8, fix public auth handler socket reuse (#134)
- Upgrade @workos-inc/node to v8 and switch to the worker subpath import (`@workos-inc/node/worker`). The v8 worker build ships with a clean `iron-webcrypto` dependency, so the `require('buffer/index.js')` patch is no longer needed and gets deleted. - Fix "Cannot perform I/O on behalf of a different request" on the second login after logout. `HttpApiBuilder.toWebHandler` was called once at module load for the public auth handler, which memoized `DbService.Live`'s `Layer.scoped` — the `sql` connection was created in the module scope and reused across requests. workerd tears down TCP sockets at request boundaries, so the second request hit a dead socket. Build the public handler per-request and dispose it after. - Scrub internal details from tagged error response payloads. The `UserStoreError`/`WorkOSError` schemas had a `cause: Schema.Unknown` field which encoded the full drizzle/workos error (SQL, params, stack) into 500 response bodies. Drop the field, set a 500 status annotation, and log the real cause server-side via `console.error` so we can see it in logs without leaking it to clients. - Add a `memberships` table to the cloud schema as the foundation for multi-workspace support (one account → many orgs) per notes/auth.md. Migration regenerated since prod was wiped and reseeded. - Rename `APP_URL` → `VITE_PUBLIC_SITE_URL` for consistency with the public site URL naming used elsewhere. Used in the auth login handler to compute the redirect origin instead of trusting the request's Host header (which points at the internal proxy target in dev). - Tighten `secure: true` on session cookies unconditionally. - Kill the `POST /auth/organization` standalone endpoint. The only place orgs are created is the auth callback, which auto-provisions a default workspace on first login. The v8 upgrade, per-request handler, VITE_PUBLIC_SITE_URL rename, and `secure: true` changes are cherry-picks / adaptations from PR #133. Co-authored-by: Saatvik Arya <aryasaatvik@gmail.com>
1 parent 67b0dd1 commit aff81b5

15 files changed

Lines changed: 339 additions & 216 deletions

apps/cloud/drizzle/0000_gigantic_terrax.sql renamed to apps/cloud/drizzle/0000_redundant_night_nurse.sql

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@ CREATE TABLE "accounts" (
33
"created_at" timestamp with time zone DEFAULT now() NOT NULL
44
);
55
--> statement-breakpoint
6+
CREATE TABLE "memberships" (
7+
"account_id" text NOT NULL,
8+
"organization_id" text NOT NULL,
9+
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
10+
CONSTRAINT "memberships_account_id_organization_id_pk" PRIMARY KEY("account_id","organization_id")
11+
);
12+
--> statement-breakpoint
613
CREATE TABLE "organizations" (
714
"id" text PRIMARY KEY NOT NULL,
815
"name" text NOT NULL,
@@ -70,3 +77,6 @@ CREATE TABLE "tools" (
7077
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
7178
CONSTRAINT "tools_id_organization_id_pk" PRIMARY KEY("id","organization_id")
7279
);
80+
--> statement-breakpoint
81+
ALTER TABLE "memberships" ADD CONSTRAINT "memberships_account_id_accounts_id_fk" FOREIGN KEY ("account_id") REFERENCES "public"."accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
82+
ALTER TABLE "memberships" ADD CONSTRAINT "memberships_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;

‎apps/cloud/drizzle/meta/0000_snapshot.json‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"id": "54fdb041-bab4-45f5-bb24-5d1c61489dea",
2+
"id": "1a3473eb-f8df-44f3-aaa4-16b1574e4a65",
33
"prevId": "00000000-0000-0000-0000-000000000000",
44
"version": "7",
55
"dialect": "postgresql",
@@ -30,6 +30,73 @@
3030
"checkConstraints": {},
3131
"isRLSEnabled": false
3232
},
33+
"public.memberships": {
34+
"name": "memberships",
35+
"schema": "",
36+
"columns": {
37+
"account_id": {
38+
"name": "account_id",
39+
"type": "text",
40+
"primaryKey": false,
41+
"notNull": true
42+
},
43+
"organization_id": {
44+
"name": "organization_id",
45+
"type": "text",
46+
"primaryKey": false,
47+
"notNull": true
48+
},
49+
"created_at": {
50+
"name": "created_at",
51+
"type": "timestamp with time zone",
52+
"primaryKey": false,
53+
"notNull": true,
54+
"default": "now()"
55+
}
56+
},
57+
"indexes": {},
58+
"foreignKeys": {
59+
"memberships_account_id_accounts_id_fk": {
60+
"name": "memberships_account_id_accounts_id_fk",
61+
"tableFrom": "memberships",
62+
"tableTo": "accounts",
63+
"columnsFrom": [
64+
"account_id"
65+
],
66+
"columnsTo": [
67+
"id"
68+
],
69+
"onDelete": "cascade",
70+
"onUpdate": "no action"
71+
},
72+
"memberships_organization_id_organizations_id_fk": {
73+
"name": "memberships_organization_id_organizations_id_fk",
74+
"tableFrom": "memberships",
75+
"tableTo": "organizations",
76+
"columnsFrom": [
77+
"organization_id"
78+
],
79+
"columnsTo": [
80+
"id"
81+
],
82+
"onDelete": "cascade",
83+
"onUpdate": "no action"
84+
}
85+
},
86+
"compositePrimaryKeys": {
87+
"memberships_account_id_organization_id_pk": {
88+
"name": "memberships_account_id_organization_id_pk",
89+
"columns": [
90+
"account_id",
91+
"organization_id"
92+
]
93+
}
94+
},
95+
"uniqueConstraints": {},
96+
"policies": {},
97+
"checkConstraints": {},
98+
"isRLSEnabled": false
99+
},
33100
"public.organizations": {
34101
"name": "organizations",
35102
"schema": "",

‎apps/cloud/drizzle/meta/_journal.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
{
66
"idx": 0,
77
"version": "7",
8-
"when": 1775718432762,
9-
"tag": "0000_gigantic_terrax",
8+
"when": 1775764846378,
9+
"tag": "0000_redundant_night_nurse",
1010
"breakpoints": true
1111
}
1212
]

‎apps/cloud/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
"@modelcontextprotocol/sdk": "^1.29.0",
2424
"@tanstack/react-router": "catalog:",
2525
"@tanstack/react-start": "catalog:",
26-
"@workos-inc/node": "^7.0.0",
26+
"@workos-inc/node": "^8.11.1",
2727
"agents": "^0.10.0",
2828
"drizzle-orm": "catalog:",
2929
"effect": "catalog:",

‎apps/cloud/src/api.ts‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -100,18 +100,30 @@ const NonProtectedApiLive = HttpApiBuilder.api(NonProtectedApi).pipe(
100100
);
101101

102102
// ---------------------------------------------------------------------------
103-
// Static web handlers — built once at module load
103+
// Public auth web handler
104+
// ---------------------------------------------------------------------------
105+
//
106+
// Build per-request, not once at module load. `toWebHandler` creates a
107+
// single long-lived `Layer.MemoMap` that memoizes `DbService.Live`'s
108+
// `Layer.scoped` acquire — the resulting `sql` connection is created in
109+
// the module scope, not the request scope. Workerd tears down TCP sockets
110+
// at request boundaries, so the second request on a cached handler fails
111+
// with "Cannot perform I/O on behalf of a different request". Building a
112+
// fresh handler per request gives each request its own layer scope and a
113+
// fresh socket. Auth endpoints (login/callback/me/logout) are infrequent
114+
// so the overhead is negligible.
104115
// ---------------------------------------------------------------------------
105116

106117
const RouterConfig = HttpRouter.setRouterConfig({ maxParamLength: 1000 });
107118

108-
const nonProtectedHandler = HttpApiBuilder.toWebHandler(
109-
NonProtectedApiLive.pipe(
110-
Layer.provideMerge(SharedServices),
111-
Layer.provideMerge(RouterConfig),
112-
),
113-
{ middleware: HttpMiddleware.logger },
114-
);
119+
const createNonProtectedHandler = () =>
120+
HttpApiBuilder.toWebHandler(
121+
NonProtectedApiLive.pipe(
122+
Layer.provideMerge(SharedServices),
123+
Layer.provideMerge(RouterConfig),
124+
),
125+
{ middleware: HttpMiddleware.logger },
126+
);
115127

116128
// ---------------------------------------------------------------------------
117129
// Protected handler — must be built per-request because the executor varies
@@ -178,7 +190,12 @@ export const handleApiRequest = async (request: Request): Promise<Response> => {
178190
const pathname = new URL(request.url).pathname;
179191

180192
if (isAuthPath(pathname)) {
181-
return nonProtectedHandler.handler(request);
193+
const handler = createNonProtectedHandler();
194+
try {
195+
return await handler.handler(request);
196+
} finally {
197+
await handler.dispose();
198+
}
182199
}
183200

184201
// Protected path — build the executor lazily for the request's org.

‎apps/cloud/src/auth/api.ts‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,6 @@ const AuthCallbackSearch = Schema.Struct({
2424
code: Schema.String,
2525
});
2626

27-
const CreateOrganizationRequest = Schema.Struct({
28-
name: Schema.String,
29-
});
30-
3127
export const AUTH_PATHS = {
3228
login: "/api/auth/login",
3329
logout: "/api/auth/logout",
@@ -56,11 +52,5 @@ export class CloudAuthApi extends HttpApiGroup.make("cloudAuth")
5652
.add(
5753
HttpApiEndpoint.post("logout")`/auth/logout`,
5854
)
59-
.add(
60-
HttpApiEndpoint.post("createOrganization")`/auth/organization`
61-
.setPayload(CreateOrganizationRequest)
62-
.addError(UserStoreError)
63-
.addError(WorkOSError),
64-
)
6555
.middleware(SessionAuth)
6656
{}

‎apps/cloud/src/auth/context.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,17 @@ const makeService = (store: RawStore) => {
1616
const use = <A>(fn: (s: RawStore) => Promise<A>) =>
1717
Effect.tryPromise({
1818
try: () => fn(store),
19-
catch: (cause) => new UserStoreError({ cause }),
20-
}).pipe(Effect.withSpan("user_store"));
19+
catch: (cause) => cause,
20+
}).pipe(
21+
Effect.tapError((cause) =>
22+
Effect.sync(() => {
23+
// eslint-disable-next-line no-console
24+
console.error("[user_store] query failed:", cause);
25+
}),
26+
),
27+
Effect.mapError(() => new UserStoreError()),
28+
Effect.withSpan("user_store"),
29+
);
2130

2231
return { use };
2332
};

‎apps/cloud/src/auth/errors.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
1+
import { HttpApiSchema } from "@effect/platform";
12
import { Schema } from "effect";
23

4+
// Tagged errors returned to HTTP clients. The response payload must NEVER
5+
// include internal details (SQL, stack traces, WorkOS error bodies) — those
6+
// can leak schema + secrets. Keep the schema empty and log the `cause`
7+
// server-side via Effect's logger when the error is constructed.
38
export class UserStoreError extends Schema.TaggedError<UserStoreError>()(
49
"UserStoreError",
5-
{ cause: Schema.Unknown },
10+
{},
11+
HttpApiSchema.annotations({ status: 500 }),
612
) {}
713

814
export class WorkOSError extends Schema.TaggedError<WorkOSError>()(
915
"WorkOSError",
10-
{ cause: Schema.Unknown },
16+
{},
17+
HttpApiSchema.annotations({ status: 500 }),
1118
) {}

‎apps/cloud/src/auth/handlers.ts‎

Lines changed: 8 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { HttpApi, HttpApiBuilder, HttpServerRequest, HttpServerResponse } from "@effect/platform";
1+
import { HttpApi, HttpApiBuilder, HttpServerResponse } from "@effect/platform";
22
import { Effect } from "effect";
3-
import { setCookie, deleteCookie, getCookie } from "@tanstack/react-start/server";
3+
import { setCookie, deleteCookie } from "@tanstack/react-start/server";
44

55
import { AUTH_PATHS, CloudAuthApi, CloudAuthPublicApi } from "./api";
66
import { SessionContext } from "./middleware";
@@ -13,12 +13,12 @@ const COOKIE_OPTIONS = {
1313
httpOnly: true,
1414
sameSite: "lax" as const,
1515
maxAge: 60 * 60 * 24 * 7,
16-
secure: server.NODE_ENV === "production",
16+
secure: true,
1717
};
1818

1919
// ---------------------------------------------------------------------------
2020
// Single non-protected API surface — public (login/callback) + session
21-
// (me/logout/createOrganization). The session group has SessionAuth on it.
21+
// (me/logout). The session group has SessionAuth on it.
2222
// ---------------------------------------------------------------------------
2323

2424
export const NonProtectedApi = HttpApi.make("cloudWeb")
@@ -37,13 +37,10 @@ export const CloudAuthPublicHandlers = HttpApiBuilder.group(
3737
.handleRaw("login", () =>
3838
Effect.gen(function* () {
3939
const workos = yield* WorkOSAuth;
40-
const req = yield* HttpServerRequest.HttpServerRequest;
41-
// Prefer APP_URL (set explicitly in dev/prod config) since the
42-
// request's Host header is the internal proxy target in dev, not
43-
// the public URL WorkOS needs to redirect back to.
44-
const origin = server.APP_URL
45-
? server.APP_URL
46-
: new URL(req.url, `${req.headers["x-forwarded-proto"] ?? "https"}://${req.headers["host"]}`).origin;
40+
// Use the explicit public site URL — in dev, the request's Host
41+
// header points at the internal proxy target, not the public URL
42+
// WorkOS needs to redirect back to.
43+
const origin = server.VITE_PUBLIC_SITE_URL;
4744
const url = workos.getAuthorizationUrl(`${origin}${AUTH_PATHS.callback}`);
4845
return HttpServerResponse.redirect(url, { status: 302 });
4946
}),
@@ -132,32 +129,5 @@ export const CloudSessionAuthHandlers = HttpApiBuilder.group(
132129
deleteCookie("wos-session", { path: "/" });
133130
return HttpServerResponse.redirect("/", { status: 302 });
134131
}),
135-
)
136-
.handle("createOrganization", ({ payload }) =>
137-
Effect.gen(function* () {
138-
const session = yield* SessionContext;
139-
const workos = yield* WorkOSAuth;
140-
const users = yield* UserStoreService;
141-
142-
// Create the org in WorkOS
143-
const org = yield* workos.createOrganization(payload.name);
144-
145-
// Add the current user as a member
146-
yield* workos.createMembership(org.id, session.accountId);
147-
148-
// Mirror locally
149-
yield* users.use((s) =>
150-
s.upsertOrganization({ id: org.id, name: org.name }),
151-
);
152-
153-
// Refresh the session with the new org context
154-
const currentSession = getCookie("wos-session") ?? null;
155-
if (currentSession) {
156-
const newSession = yield* workos.refreshSession(currentSession, org.id);
157-
if (newSession) {
158-
setCookie("wos-session", newSession, COOKIE_OPTIONS);
159-
}
160-
}
161-
}),
162132
),
163133
);

‎apps/cloud/src/auth/workos.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
// ---------------------------------------------------------------------------
44

55
import { Context, Effect, Layer } from "effect";
6-
import { WorkOS } from "@workos-inc/node";
6+
import { WorkOS } from "@workos-inc/node/worker";
77
import { WorkOSError } from "./errors";
88
import { server } from "../env";
99

@@ -23,13 +23,22 @@ const make = Effect.gen(function* () {
2323
return yield* Effect.die(new Error("WORKOS_COOKIE_PASSWORD must be at least 32 characters"));
2424
}
2525

26-
const workos = new WorkOS(apiKey, { clientId });
26+
const workos = new WorkOS({ apiKey, clientId });
2727

2828
const use = <A>(fn: (wos: WorkOS) => Promise<A>) =>
2929
Effect.tryPromise({
3030
try: () => fn(workos),
31-
catch: (cause) => new WorkOSError({ cause }),
32-
}).pipe(Effect.withSpan("workos"));
31+
catch: (cause) => cause,
32+
}).pipe(
33+
Effect.tapError((cause) =>
34+
Effect.sync(() => {
35+
// eslint-disable-next-line no-console
36+
console.error("[workos] call failed:", cause);
37+
}),
38+
),
39+
Effect.mapError(() => new WorkOSError()),
40+
Effect.withSpan("workos"),
41+
);
3342

3443
const authenticateSealedSession = (sessionData: string) =>
3544
Effect.gen(function* () {

0 commit comments

Comments
 (0)