Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(device): register, list and revoke tunnel links from the server (#19881)

Arvin Xue146cd150970
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 8226cd434b1..90d237803f5 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -23,9 +23,10 @@ import { DeviceModel, WorkspaceDevicePrivateConflictError } from '@/database/mod
import { UserModel } from '@/database/models/user';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { signWorkspaceDeviceToken } from '@/libs/trpc/utils/internalJwt';
+import { signTunnelAccessToken, signWorkspaceDeviceToken } from '@/libs/trpc/utils/internalJwt';
import { type DeviceAttachment, deviceGateway } from '@/server/services/deviceGateway';
import { filterAuthorizedDevicePresence } from '@/server/services/deviceGateway/scopedDevicePresence';
+import { deviceTunnels, TUNNEL_MAX_TTL_SECONDS } from '@/server/services/deviceGateway/tunnels';
import { preserveWorkspaceCache } from './deviceWorkingDirs';
import {
@@ -60,6 +61,44 @@ const SCAN_TIMEOUT_MS = 10_000;
* Members can therefore self-serve their own machines without touching anyone
* else's enrollment, while shared cleanup remains an owner action.
*/
+/**
+ * Exposing a port is at least as sensitive as reading the filesystem, so a
+ * workspace device is gated the same way `browseDirectory` gates new paths:
+ * only the enrolling member or a workspace owner.
+ */
+const assertTunnelDeviceWritable = async (
+ ctx: {
+ deviceModel: DeviceModel;
+ userId: string;
+ workspaceId?: string;
+ workspaceRole?: WorkspaceRole;
+ },
+ deviceId: string,
+) => {
+ if (!ctx.workspaceId) return;
+
+ const row = await ctx.deviceModel.findWorkspaceDeviceById(deviceId);
+ if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });
+ if (!canEditWorkspaceDevice(ctx.workspaceRole, ctx.userId, row.userId)) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the enrolling member or a workspace owner can expose a port on this device.',
+ });
+ }
+};
+
+/** Append a freshly minted access token to a tunnel URL. */
+const buildTunnelOpenUrl = async (
+ url: string,
+ ctx: { userId: string; workspaceId?: string },
+): Promise<string> => {
+ const token = await signTunnelAccessToken({
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ return `${url}?token=${encodeURIComponent(token)}`;
+};
+
const canEditWorkspaceDevice = (
role: WorkspaceRole | undefined,
actorUserId: string,
@@ -1198,6 +1237,86 @@ export const deviceRouter = router({
]);
}),
+ // ─── Tunnel links ───
+ //
+ // A tunnel makes one loopback port on a device reachable at
+ // `https://<port>--<slug>.lobe.sh/`. Creating one is gated exactly like
+ // browsing the device's filesystem: on a workspace device, only the
+ // enrolling member or an owner may expose a port.
+
+ /** Open a link to `port` on a device. */
+ createTunnel: deviceProcedure
+ .input(
+ z.object({
+ deviceId: z.string(),
+ port: z.number().int().min(1).max(65_535),
+ ttlSeconds: z.number().int().positive().max(TUNNEL_MAX_TTL_SECONDS).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ await assertTunnelDeviceWritable(ctx, input.deviceId);
+
+ const link = await deviceTunnels.create({
+ deviceId: input.deviceId,
+ port: input.port,
+ ttlSeconds: input.ttlSeconds,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ if (!link) {
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'Device gateway is not configured on this deployment.',
+ });
+ }
+
+ return { ...link, openUrl: await buildTunnelOpenUrl(link.url, ctx) };
+ }),
+
+ /** Live tunnel links the caller can reach, newest first. */
+ listTunnels: deviceProcedure
+ .input(z.object({ deviceId: z.string().optional() }).optional())
+ .query(async ({ ctx, input }) =>
+ deviceTunnels.list({
+ deviceId: input?.deviceId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ }),
+ ),
+
+ /**
+ * Mint the one-shot token that opens an existing link. Tokens are minted per
+ * click rather than stored with the link: the gateway swaps the token for a
+ * session cookie on first use, so the URL in hand stays clean.
+ */
+ openTunnel: deviceProcedure
+ .input(z.object({ slug: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const links = await deviceTunnels.list({ userId: ctx.userId, workspaceId: ctx.workspaceId });
+ const link = links.find((candidate) => candidate.slug === input.slug);
+ if (!link) throw new TRPCError({ code: 'NOT_FOUND', message: 'Tunnel not found.' });
+
+ return { openUrl: await buildTunnelOpenUrl(link.url, ctx), url: link.url };
+ }),
+
+ /** Revoke a link. Its session cookies stop resolving immediately. */
+ revokeTunnel: deviceProcedure
+ .input(z.object({ slug: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const outcome = await deviceTunnels.revoke({
+ slug: input.slug,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ if (outcome === 'forbidden') {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'This tunnel belongs to someone else.' });
+ }
+ if (outcome === 'not-found') {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Tunnel not found.' });
+ }
+ return { success: true };
+ }),
+
/**
* Mint a short-lived connect token for enrolling a WORKSPACE-owned device.
* Workspace members (and owners) can call β€” enrolling a machine into the
diff --git a/apps/server/src/services/deviceGateway/tunnels.test.ts b/apps/server/src/services/deviceGateway/tunnels.test.ts
new file mode 100644
index 00000000000..3da38d1fb7f
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/tunnels.test.ts
@@ -0,0 +1,143 @@
+import type * as DeviceGatewayClient from '@lobechat/device-gateway-client';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ createTunnel: vi.fn(),
+ listTunnels: vi.fn(),
+ resolveTunnel: vi.fn(),
+ revokeTunnel: vi.fn(),
+}));
+
+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({
+ ...(await importOriginal<typeof DeviceGatewayClient>()),
+ GatewayHttpClient: vi.fn().mockImplementation(function () {
+ return mocks;
+ }),
+}));
+
+vi.mock('@/envs/gateway', () => ({
+ gatewayEnv: {
+ DEVICE_GATEWAY_SERVICE_TOKEN: 'service-token',
+ DEVICE_GATEWAY_URL: 'https://gateway.test',
+ },
+}));
+
+const { DeviceTunnelRegistry } = await import('./tunnels');
+
+const registration = (overrides: Record<string, unknown> = {}) => ({
+ createdAt: 1_000,
+ createdBy: 'user-1',
+ deviceId: 'device-1',
+ hostname: '3000--abcdefgh.lobe.sh',
+ port: 3000,
+ principal: 'user:user-1',
+ slug: 'abcdefgh',
+ ...overrides,
+});
+
+let registry: InstanceType<typeof DeviceTunnelRegistry>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ registry = new DeviceTunnelRegistry();
+});
+
+describe('DeviceTunnelRegistry', () => {
+ describe('create', () => {
+ it('registers against the caller personal principal and returns the link', async () => {
+ mocks.createTunnel.mockResolvedValue(registration());
+
+ const link = await registry.create({ deviceId: 'device-1', port: 3000, userId: 'user-1' });
+
+ expect(mocks.createTunnel).toHaveBeenCalledWith({
+ createdBy: 'user-1',
+ deviceId: 'device-1',
+ port: 3000,
+ principal: 'user:user-1',
+ ttlSeconds: undefined,
+ });
+ expect(link).toMatchObject({ slug: 'abcdefgh', url: 'https://3000--abcdefgh.lobe.sh/' });
+ });
+
+ it('registers a workspace tunnel against the workspace principal', async () => {
+ mocks.createTunnel.mockResolvedValue(registration({ principal: 'workspace:ws-1' }));
+
+ await registry.create({
+ deviceId: 'device-1',
+ port: 5173,
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+
+ // Workspace tunnels are reachable by every member, so they must not be
+ // filed under the creator's personal principal.
+ expect(mocks.createTunnel).toHaveBeenCalledWith(
+ expect.objectContaining({ createdBy: 'user-1', principal: 'workspace:ws-1' }),
+ );
+ });
+ });
+
+ describe('list', () => {
+ it('returns newest first and can narrow to one device', async () => {
+ mocks.listTunnels.mockResolvedValue([
+ registration({ createdAt: 1, deviceId: 'device-1', slug: 'aaaaaaaa' }),
+ registration({ createdAt: 3, deviceId: 'device-2', slug: 'bbbbbbbb' }),
+ registration({ createdAt: 2, deviceId: 'device-1', slug: 'cccccccc' }),
+ ]);
+
+ const all = await registry.list({ userId: 'user-1' });
+ expect(all.map((link) => link.slug)).toEqual(['bbbbbbbb', 'cccccccc', 'aaaaaaaa']);
+
+ const scoped = await registry.list({ deviceId: 'device-1', userId: 'user-1' });
+ expect(scoped.map((link) => link.slug)).toEqual(['cccccccc', 'aaaaaaaa']);
+ });
+ });
+
+ describe('revoke', () => {
+ it('revokes a tunnel the caller owns', async () => {
+ mocks.resolveTunnel.mockResolvedValue(registration());
+ mocks.revokeTunnel.mockResolvedValue(true);
+
+ expect(await registry.revoke({ slug: 'abcdefgh', userId: 'user-1' })).toBe('revoked');
+ expect(mocks.revokeTunnel).toHaveBeenCalledWith('abcdefgh');
+ });
+
+ it('refuses to delete another principal tunnel', async () => {
+ mocks.resolveTunnel.mockResolvedValue(registration({ principal: 'user:someone-else' }));
+
+ // The gateway admin API deletes any slug it is handed, so ownership has
+ // to be proven here or one user could revoke another user's tunnel.
+ expect(await registry.revoke({ slug: 'abcdefgh', userId: 'user-1' })).toBe('forbidden');
+ expect(mocks.revokeTunnel).not.toHaveBeenCalled();
+ });
+
+ it('refuses a workspace tunnel when the caller is out of that workspace', async () => {
+ mocks.resolveTunnel.mockResolvedValue(registration({ principal: 'workspace:ws-1' }));
+
+ expect(await registry.revoke({ slug: 'abcdefgh', userId: 'user-1' })).toBe('forbidden');
+ expect(
+ await registry.revoke({ slug: 'abcdefgh', userId: 'user-1', workspaceId: 'ws-1' }),
+ ).not.toBe('forbidden');
+ });
+
+ it('reports an unknown slug instead of throwing', async () => {
+ mocks.resolveTunnel.mockResolvedValue(undefined);
+
+ expect(await registry.revoke({ slug: 'zzzzzzzz', userId: 'user-1' })).toBe('not-found');
+ expect(mocks.revokeTunnel).not.toHaveBeenCalled();
+ });
+ });
+});
+
+describe('DeviceTunnelRegistry without a configured gateway', () => {
+ it('degrades instead of failing', async () => {
+ vi.resetModules();
+ vi.doMock('@/envs/gateway', () => ({ gatewayEnv: {} }));
+ const { DeviceTunnelRegistry: Unconfigured } = await import('./tunnels');
+ const unconfigured = new Unconfigured();
+
+ expect(await unconfigured.create({ deviceId: 'd', port: 3000, userId: 'u' })).toBeUndefined();
+ expect(await unconfigured.list({ userId: 'u' })).toEqual([]);
+ expect(await unconfigured.revoke({ slug: 'abcdefgh', userId: 'u' })).toBe('not-found');
+ });
+});
diff --git a/apps/server/src/services/deviceGateway/tunnels.ts b/apps/server/src/services/deviceGateway/tunnels.ts
new file mode 100644
index 00000000000..770621a5c6d
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/tunnels.ts
@@ -0,0 +1,129 @@
+import { devicePrincipal, GatewayHttpClient } from '@lobechat/device-gateway-client';
+import debug from 'debug';
+
+import { gatewayEnv } from '@/envs/gateway';
+
+const log = debug('lobe-server:device-tunnels');
+
+/**
+ * Tunnel links: an opaque slug that makes one loopback port on one device
+ * reachable at `https://<port>--<slug>.lobe.sh/`.
+ *
+ * Separate from {@link DeviceGateway} because nothing here talks to a device β€”
+ * these calls manage the gateway's own registry. Ownership is enforced on this
+ * side: the gateway's admin API trusts the service token and will delete any
+ * slug it is handed.
+ */
+
+/** Default lifetime of a link, matching the gateway's own default. */
+export const TUNNEL_DEFAULT_TTL_SECONDS = 7 * 24 * 3600;
+export const TUNNEL_MAX_TTL_SECONDS = 30 * 24 * 3600;
+
+export interface TunnelLink {
+ createdAt: number;
+ deviceId: string;
+ expiresAt?: number;
+ /** `<port>--<slug>.lobe.sh` */
+ hostname: string;
+ port: number;
+ slug: string;
+ /** The link to open, without the one-shot access token. */
+ url: string;
+}
+
+export type TunnelRevokeOutcome = 'forbidden' | 'not-found' | 'revoked';
+
+const toLink = (registration: {
+ createdAt: number;
+ deviceId: string;
+ expiresAt?: number;
+ hostname?: string;
+ port: number;
+ slug: string;
+}): TunnelLink => {
+ const hostname = registration.hostname ?? '';
+ return {
+ createdAt: registration.createdAt,
+ deviceId: registration.deviceId,
+ expiresAt: registration.expiresAt,
+ hostname,
+ port: registration.port,
+ slug: registration.slug,
+ url: `https://${hostname}/`,
+ };
+};
+
+export class DeviceTunnelRegistry {
+ private client: GatewayHttpClient | null = null;
+
+ /** Open a link to `port` on `deviceId`. Returns undefined when unconfigured. */
+ async create(params: {
+ deviceId: string;
+ port: number;
+ ttlSeconds?: number;
+ userId: string;
+ workspaceId?: string;
+ }): Promise<TunnelLink | undefined> {
+ const client = this.getClient();
+ if (!client) return undefined;
+
+ const registration = await client.createTunnel({
+ createdBy: params.userId,
+ deviceId: params.deviceId,
+ port: params.port,
+ principal: devicePrincipal(params),
+ ttlSeconds: params.ttlSeconds,
+ });
+ log('created tunnel %s for device %s:%d', registration.slug, params.deviceId, params.port);
+ return toLink(registration);
+ }
+
+ /** Every live link the caller can reach, newest first. */
+ async list(params: {
+ deviceId?: string;
+ userId: string;
+ workspaceId?: string;
+ }): Promise<TunnelLink[]> {
+ const client = this.getClient();
+ if (!client) return [];
+
+ const tunnels = await client.listTunnels(devicePrincipal(params));
+ return tunnels
+ .filter((tunnel) => !params.deviceId || tunnel.deviceId === params.deviceId)
+ .map((tunnel) => toLink(tunnel))
+ .sort((a, b) => b.createdAt - a.createdAt);
+ }
+
+ /**
+ * Revoke a link. The slug is resolved first so a caller can only delete a
+ * registration owned by their own principal.
+ */
+ async revoke(params: {
+ slug: string;
+ userId: string;
+ workspaceId?: string;
+ }): Promise<TunnelRevokeOutcome> {
+ const client = this.getClient();
+ if (!client) return 'not-found';
+
+ const registration = await client.resolveTunnel(params.slug);
+ if (!registration) return 'not-found';
+ if (registration.principal !== devicePrincipal(params)) return 'forbidden';
+
+ const revoked = await client.revokeTunnel(params.slug);
+ return revoked ? 'revoked' : 'not-found';
+ }
+
+ private getClient(): GatewayHttpClient | null {
+ const url = gatewayEnv.DEVICE_GATEWAY_URL;
+ const token = gatewayEnv.DEVICE_GATEWAY_SERVICE_TOKEN;
+ if (!url || !token) return null;
+
+ if (!this.client) {
+ this.client = new GatewayHttpClient({ gatewayUrl: url, serviceToken: token });
+ }
+ return this.client;
+ }
+}
+
+export const deviceTunnels = new DeviceTunnelRegistry();
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 13a557c8e7e..ac81cb7713b 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -839,4 +839,87 @@ describe('GatewayHttpClient', () => {
expect(result.success).toBe(false);
});
});
+
+ describe('tunnel registry', () => {
+ it('creates a tunnel and folds the hostname into the registration', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({
+ hostname: '3000--abcdefgh.lobe.sh',
+ registration: {
+ createdAt: 1,
+ createdBy: 'user-1',
+ deviceId: 'device-1',
+ port: 3000,
+ principal: 'user:user-1',
+ slug: 'abcdefgh',
+ },
+ }),
+ ok: true,
+ });
+
+ const result = await client.createTunnel({
+ createdBy: 'user-1',
+ deviceId: 'device-1',
+ port: 3000,
+ principal: 'user:user-1',
+ });
+
+ expect(result).toMatchObject({ hostname: '3000--abcdefgh.lobe.sh', slug: 'abcdefgh' });
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://gateway.test.com/api/admin/tunnels',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+
+ it('surfaces a rejected creation instead of returning a broken link', async () => {
+ mockFetch({ ok: false, status: 400, text: vi.fn().mockResolvedValue('INVALID_PORT') });
+
+ await expect(
+ client.createTunnel({
+ createdBy: 'user-1',
+ deviceId: 'device-1',
+ port: 3000,
+ principal: 'user:user-1',
+ }),
+ ).rejects.toThrow('INVALID_PORT');
+ });
+
+ it('lists tunnels for one principal', async () => {
+ mockFetch({ json: vi.fn().mockResolvedValue({ tunnels: [{ slug: 'abcdefgh' }] }), ok: true });
+
+ const result = await client.listTunnels('workspace:ws-1');
+
+ expect(result).toEqual([{ slug: 'abcdefgh' }]);
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://gateway.test.com/api/admin/tunnels?principal=workspace%3Aws-1',
+ expect.objectContaining({
+ headers: { Authorization: 'Bearer test-service-token' },
+ method: 'GET',
+ }),
+ );
+ });
+
+ it('treats an unknown slug as absent, not as an error', async () => {
+ mockFetch({ ok: false, status: 404 });
+ expect(await client.resolveTunnel('zzzzzzzz')).toBeUndefined();
+
+ mockFetch({ ok: false, status: 404 });
+ expect(await client.revokeTunnel('zzzzzzzz')).toBe(false);
+ });
+
+ it('revokes a tunnel', async () => {
+ mockFetch({ json: vi.fn().mockResolvedValue({ success: true }), ok: true });
+
+ expect(await client.revokeTunnel('abcdefgh')).toBe(true);
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://gateway.test.com/api/admin/tunnels/abcdefgh',
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ });
+
+ it('raises a gateway failure rather than reporting an empty list', async () => {
+ mockFetch({ ok: false, status: 500 });
+ await expect(client.listTunnels('user:user-1')).rejects.toThrow('responded 500');
+ });
+ });
});
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 50197717081..2b6a953d1f0 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -9,6 +9,7 @@ import type {
GatewayDevice,
GatewayMcpParams,
GatewayToolCallType,
+ GatewayTunnelRegistration,
} from './types';
const DEFAULT_GATEWAY_TOOL_CALL_TIMEOUT_MS = 30_000;
@@ -371,6 +372,69 @@ export class GatewayHttpClient {
};
}
+ // ─── Tunnel registry (gateway admin API) ───
+ //
+ // These do NOT reach the device: they manage the slug β†’ { device, port }
+ // mapping that gives a tunnel its public hostname. Ownership is enforced
+ // here, on the server β€” the gateway's admin API trusts the service token.
+
+ /** Register a tunnel and return it with its public hostname. */
+ async createTunnel(params: {
+ createdBy: string;
+ deviceId: string;
+ port: number;
+ principal: string;
+ ttlSeconds?: number;
+ }): Promise<GatewayTunnelRegistration> {
+ const res = await this.post('/api/admin/tunnels', params, {
+ timeout: DEVICE_QUERY_TIMEOUT_MS,
+ });
+ if (!res.ok) {
+ const detail = await res.text().catch(() => '');
+ throw new Error(`Device gateway /api/admin/tunnels responded ${res.status} ${detail}`.trim());
+ }
+
+ const data = (await res.json()) as {
+ hostname: string;
+ registration: GatewayTunnelRegistration;
+ };
+ return { ...data.registration, hostname: data.hostname };
+ }
+
+ /** Every live tunnel owned by one principal. */
+ async listTunnels(principal: string): Promise<GatewayTunnelRegistration[]> {
+ const res = await this.request(
+ `/api/admin/tunnels?principal=${encodeURIComponent(principal)}`,
+ 'GET',
+ );
+ if (!res.ok) {
+ throw new Error(`Device gateway /api/admin/tunnels responded ${res.status}`);
+ }
+
+ const data = (await res.json()) as { tunnels?: GatewayTunnelRegistration[] };
+ return data.tunnels ?? [];
+ }
+
+ /** The registration behind a slug, or undefined when it is unknown or expired. */
+ async resolveTunnel(slug: string): Promise<GatewayTunnelRegistration | undefined> {
+ const res = await this.request(`/api/admin/tunnels/resolve/${encodeURIComponent(slug)}`, 'GET');
+ if (res.status === 404) return undefined;
+ if (!res.ok) {
+ throw new Error(`Device gateway /api/admin/tunnels/resolve responded ${res.status}`);
+ }
+ return (await res.json()) as GatewayTunnelRegistration;
+ }
+
+ /** Revoke a tunnel. Returns false when the slug was already gone. */
+ async revokeTunnel(slug: string): Promise<boolean> {
+ const res = await this.request(`/api/admin/tunnels/${encodeURIComponent(slug)}`, 'DELETE');
+ if (res.status === 404) return false;
+ if (!res.ok) {
+ throw new Error(`Device gateway /api/admin/tunnels responded ${res.status}`);
+ }
+ return true;
+ }
+
private post(path: string, body: unknown, options?: { timeout?: number }): Promise<Response> {
return fetch(`${this.gatewayUrl}${path}`, {
body: JSON.stringify(body),
@@ -382,4 +446,13 @@ export class GatewayHttpClient {
...(options?.timeout ? { signal: AbortSignal.timeout(options.timeout) } : {}),
});
}
+
+ /** Bodyless service-authenticated call, for the registry's GET/DELETE routes. */
+ private request(path: string, method: 'DELETE' | 'GET'): Promise<Response> {
+ return fetch(`${this.gatewayUrl}${path}`, {
+ headers: { Authorization: `Bearer ${this.serviceToken}` },
+ method,
+ signal: AbortSignal.timeout(DEVICE_QUERY_TIMEOUT_MS),
+ });
+ }
}
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 3ed5879610a..aa026c71421 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -283,6 +283,33 @@ export interface AgentRunRequestMessage {
workspaceId?: string;
}
+// ─── Tunnel registry ───
+//
+// A registration maps an opaque slug to one device + port, and gives the tunnel
+// its public hostname `<port>--<slug>.lobe.sh`. The registry lives in the
+// gateway; the server creates, lists and revokes entries through the admin API.
+
+export interface GatewayTunnelRegistration {
+ createdAt: number;
+ /** userId of whoever opened the tunnel. */
+ createdBy: string;
+ deviceId: string;
+ expiresAt?: number;
+ /** Public hostname, e.g. `3000--x7k2p9q8.lobe.sh`. */
+ hostname?: string;
+ port: number;
+ /** Owning principal β€” the gateway routing key (`user:<id>` / `workspace:<id>`). */
+ principal: string;
+ slug: string;
+}
+
+/**
+ * Gateway routing key for a caller. A workspace tunnel is reachable by every
+ * member of that workspace; a personal one only by its owner.
+ */
+export const devicePrincipal = (params: { userId: string; workspaceId?: string }): string =>
+ params.workspaceId ? `workspace:${params.workspaceId}` : `user:${params.userId}`;
+
// ─── HTTP Tunnel Frames ───
//
// A tunnel relays one browser HTTP request to a TCP port on this device as a
diff --git a/packages/trpc/src/utils/internalJwt.ts b/packages/trpc/src/utils/internalJwt.ts
index b9dda6a9ec7..8efb1493321 100644
--- a/packages/trpc/src/utils/internalJwt.ts
+++ b/packages/trpc/src/utils/internalJwt.ts
@@ -246,6 +246,33 @@ export const signWorkspaceDeviceToken = async (workspaceId: string): Promise<str
);
};
+/**
+ * Sign the one-shot token that opens a tunnel link.
+ *
+ * The device gateway verifies the signature and reads `sub` (plus an optional
+ * `workspace_id`) to decide whether the caller owns the tunnel. The token is
+ * only the *entry ticket*: the gateway immediately exchanges it for a session
+ * cookie scoped to that tunnel hostname, so it is minted at click time and
+ * expires quickly. A tunnel link is not a public share link β€” opening it from
+ * elsewhere requires an authenticated LobeHub session to mint a fresh token.
+ */
+export const signTunnelAccessToken = async (params: {
+ userId: string;
+ workspaceId?: string;
+}): Promise<string> => {
+ const { key, kid } = await getSigningKey();
+
+ return new SignJWT({
+ purpose: 'tunnel-access',
+ ...(params.workspaceId ? { workspace_id: params.workspaceId } : {}),
+ })
+ .setProtectedHeader({ alg: 'RS256', kid })
+ .setSubject(params.userId)
+ .setIssuedAt()
+ .setExpirationTime('10m')
+ .sign(key);
+};
+
/**
* Long-lived operation token for an agent run dispatched to a WORKSPACE device.
* Mirrors {@link signOperationJwt} but carries `workspace_id` so the device's