Skip to content

Commit fe9894f

Browse files
fix(cloud): return compatible worker tokens for remote connect (anomalyco#640)
1 parent 41850bf commit fe9894f

2 files changed

Lines changed: 49 additions & 30 deletions

File tree

‎packages/web/components/cloud-control.tsx‎

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,7 @@ export function CloudControlPanel() {
499499

500500
const [events, setEvents] = useState<LaunchEvent[]>([]);
501501
const [copiedField, setCopiedField] = useState<string | null>(null);
502+
const [tokenFetchedForWorkerId, setTokenFetchedForWorkerId] = useState<string | null>(null);
502503

503504
const selectedWorker = workers.find((item) => item.workerId === workerLookupId) ?? null;
504505

@@ -715,7 +716,7 @@ export function CloudControlPanel() {
715716

716717
setWorker(restored);
717718
setWorkerLookupId(restored.workerId);
718-
setLaunchStatus(`Recovered worker ${restored.workerName}. Generate a new API key if needed.`);
719+
setLaunchStatus(`Recovered worker ${restored.workerName}. Get an access token if needed.`);
719720
appendEvent("info", "Recovered worker context", `Worker ID ${restored.workerId}`);
720721
} catch {
721722
return;
@@ -750,6 +751,24 @@ export function CloudControlPanel() {
750751
setStep(1);
751752
}, [worker, user, checkoutUrl, paymentReturned]);
752753

754+
useEffect(() => {
755+
if (!user || !worker) {
756+
return;
757+
}
758+
if (worker.clientToken) {
759+
return;
760+
}
761+
if (actionBusy !== null || launchBusy) {
762+
return;
763+
}
764+
if (tokenFetchedForWorkerId === worker.workerId) {
765+
return;
766+
}
767+
768+
setTokenFetchedForWorkerId(worker.workerId);
769+
void handleGenerateKey();
770+
}, [actionBusy, launchBusy, tokenFetchedForWorkerId, user, worker]);
771+
753772
async function handleAuthSubmit(event: FormEvent<HTMLFormElement>) {
754773
event.preventDefault();
755774

@@ -959,13 +978,13 @@ export function CloudControlPanel() {
959978

960979
async function handleGenerateKey() {
961980
if (!user) {
962-
setLaunchError("Sign in before generating a worker API key.");
981+
setLaunchError("Sign in before fetching a worker access token.");
963982
return;
964983
}
965984

966985
const id = workerLookupId.trim() || worker?.workerId || workers[0]?.workerId || "";
967986
if (!id) {
968-
setLaunchError("No worker selected yet. Launch one first, then generate a key.");
987+
setLaunchError("No worker selected yet. Launch one first, then fetch a token.");
969988
return;
970989
}
971990

@@ -982,16 +1001,16 @@ export function CloudControlPanel() {
9821001
});
9831002

9841003
if (!response.ok) {
985-
const message = getErrorMessage(payload, `Key generation failed with ${response.status}.`);
1004+
const message = getErrorMessage(payload, `Token fetch failed with ${response.status}.`);
9861005
setLaunchError(message);
987-
appendEvent("error", "Key generation failed", message);
1006+
appendEvent("error", "Token fetch failed", message);
9881007
return;
9891008
}
9901009

9911010
const tokens = getWorkerTokens(payload);
9921011
if (!tokens) {
993-
setLaunchError("Key generation returned no token values.");
994-
appendEvent("error", "Key generation failed", "Missing token payload");
1012+
setLaunchError("Token response returned no token values.");
1013+
appendEvent("error", "Token fetch failed", "Missing token payload");
9951014
return;
9961015
}
9971016

@@ -1017,13 +1036,13 @@ export function CloudControlPanel() {
10171036
const resolvedWorker = await withResolvedOpenworkCredentials(nextWorker, { quiet: true });
10181037
setWorker(resolvedWorker);
10191038

1020-
setLaunchStatus("Generated a fresh access token.");
1021-
appendEvent("success", "Generated new access token", `Worker ID ${id}`);
1039+
setLaunchStatus("Access token is ready for this worker.");
1040+
appendEvent("success", "Access token ready", `Worker ID ${id}`);
10221041
void refreshWorkers({ keepSelection: true });
10231042
} catch (error) {
10241043
const message = error instanceof Error ? error.message : "Unknown network error";
10251044
setLaunchError(message);
1026-
appendEvent("error", "Key generation failed", message);
1045+
appendEvent("error", "Token fetch failed", message);
10271046
} finally {
10281047
setActionBusy(null);
10291048
}
@@ -1243,7 +1262,7 @@ export function CloudControlPanel() {
12431262
onClick={handleGenerateKey}
12441263
disabled={actionBusy !== null || !selectedWorker}
12451264
>
1246-
{actionBusy === "token" ? "Generating..." : "New access token"}
1265+
{actionBusy === "token" ? "Fetching..." : "Get access token"}
12471266
</button>
12481267
</div>
12491268
</div>
@@ -1287,7 +1306,7 @@ export function CloudControlPanel() {
12871306
<CredentialRow
12881307
label="Access token"
12891308
value={worker?.clientToken ?? null}
1290-
placeholder="Click New access token to generate credentials."
1309+
placeholder="Click Get access token to retrieve credentials."
12911310
canCopy={Boolean(worker?.clientToken)}
12921311
copied={copiedField === "access-token"}
12931312
onCopy={() => void copyToClipboard("access-token", worker?.clientToken ?? null)}
@@ -1327,7 +1346,7 @@ export function CloudControlPanel() {
13271346
{actionBusy === "status" ? "Checking..." : "Check status"}
13281347
</button>
13291348
<button type="button" className="ow-btn-secondary" onClick={handleGenerateKey} disabled={actionBusy !== null}>
1330-
{actionBusy === "token" ? "Generating..." : "New access token"}
1349+
{actionBusy === "token" ? "Fetching..." : "Get access token"}
13311350
</button>
13321351
<button
13331352
type="button"

‎services/den/src/http/workers.ts‎

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { randomBytes, randomUUID } from "crypto"
22
import express from "express"
33
import { fromNodeHeaders } from "better-auth/node"
4-
import { and, desc, eq } from "drizzle-orm"
4+
import { and, asc, desc, eq, isNull } from "drizzle-orm"
55
import { z } from "zod"
66
import { auth } from "../auth.js"
77
import { requireCloudWorkerAccess } from "../billing/polar.js"
@@ -318,22 +318,22 @@ workersRouter.post("/:id/tokens", async (req, res) => {
318318
return
319319
}
320320

321-
const hostToken = token()
322-
const clientToken = token()
323-
await db.insert(WorkerTokenTable).values([
324-
{
325-
id: randomUUID(),
326-
worker_id: rows[0].id,
327-
scope: "host",
328-
token: hostToken,
329-
},
330-
{
331-
id: randomUUID(),
332-
worker_id: rows[0].id,
333-
scope: "client",
334-
token: clientToken,
335-
},
336-
])
321+
const tokenRows = await db
322+
.select()
323+
.from(WorkerTokenTable)
324+
.where(and(eq(WorkerTokenTable.worker_id, rows[0].id), isNull(WorkerTokenTable.revoked_at)))
325+
.orderBy(asc(WorkerTokenTable.created_at))
326+
327+
const hostToken = tokenRows.find((entry) => entry.scope === "host")?.token ?? null
328+
const clientToken = tokenRows.find((entry) => entry.scope === "client")?.token ?? null
329+
330+
if (!hostToken || !clientToken) {
331+
res.status(409).json({
332+
error: "worker_tokens_unavailable",
333+
message: "Worker tokens are missing for this worker. Launch a new worker and try again.",
334+
})
335+
return
336+
}
337337

338338
res.json({
339339
tokens: {

0 commit comments

Comments
 (0)