feat(server-mode): share one session; scope collaborators' pane tokens (sharing phase 3)

A workspace's owner (or an admin) can share ONE session from its right-click
menu (GET/PUT /api/lanes/:id/sessions/:sid/shares, table session_shares,
audited). The user sees the workspace (access: "session") with only that
session, joins the pane holding it, resumes it on their own account in a
free slot, and uses the workspace's git and Files reads and git writes;
everything else of the workspace answers 403 ESESSIONSHARE (scope.js
sessionShareAllows in scopeGuard). Hook/runtime broadcasts stay with full
collaborators.

A collaborator's pane token (readable by the owner's Linux account) now acts
as them inside that workspace only, and never starts or bills a session
(auth.js paneLaneAllows, 403 EPANESCOPE); a Terminal tab the owner or an
admin opens acts as the owner again. Docs say plainly that under S3 a
session share hands over the owner's account inside the terminal.
This commit is contained in:
2026-11-06 11:25:40 +07:00
parent 1a365a45bd
commit 879a6bb02d
24 changed files with 838 additions and 120 deletions
+2 -2
View File
File diff suppressed because one or more lines are too long
@@ -31,6 +31,7 @@ export function SessionMenu({
onArchive,
onUnarchive,
onPin,
onShare,
}: MenuPoint & {
laneId: number;
session: Session | null;
@@ -42,6 +43,8 @@ export function SessionMenu({
onUnarchive?: () => void;
/** Pin or unpin (by `session.pinned_at`), where the list offers it. */
onPin?: () => void;
/** Share this session on its own (server mode, the workspace's owner). */
onShare?: () => void;
}) {
const { t } = useTranslation("lanes");
const navigate = useNavigate();
@@ -81,6 +84,11 @@ export function SessionMenu({
{t(session.pinned_at ? "sessionMenu.unpin" : "sessionMenu.pin")}
</MenuItem>
)}
{onShare && session && (
<MenuItem testId="session-menu-share" onSelect={pick(onShare)}>
{t("sessionMenu.share")}
</MenuItem>
)}
{session && (
<>
<MenuItem onSelect={pick(() => navigate(`/sessions/${session.id}`))}>
@@ -278,10 +278,13 @@ function HomeBody({
// own account and is billed to them (the server answers ENOCOLLABACCOUNT
// when they have none).
const collab = !ownsLane(lane);
// Only a session of it is shared with them (phase 3): no new session here —
// they open that session and send it messages (the server answers ESESSIONSHARE).
const sessionOnly = lane.access === "session";
const start = async () => {
// Enter reaches here past the disabled button: the same guards again.
// A ref, not only the state: two Enters in one tick both read `starting` false.
if (startingRef.current || uploading || !text) return;
if (sessionOnly || startingRef.current || uploading || !text) return;
startingRef.current = true;
setStarting(true);
setError(null);
@@ -537,7 +540,7 @@ function HomeBody({
type="button"
data-testid="workspace-home-start"
onClick={() => void start()}
disabled={starting || uploading || !text}
disabled={sessionOnly || starting || uploading || !text}
aria-label={t("home.start")}
title={t("home.start")}
className="flex h-8 w-8 items-center justify-center rounded-full bg-accent-solid text-white transition-opacity hover:opacity-90 disabled:opacity-40"
@@ -549,7 +552,7 @@ function HomeBody({
</div>
{collab && (
<p data-testid="workspace-home-collab" className="mt-2 text-xs text-fg-muted">
{t("shared.ownAccount")}
{t(sessionOnly ? "shared.sessionOnly" : "shared.ownAccount")}
</p>
)}
{/* The session's quieter choices, under the box like Claude Desktop's. */}
@@ -31,7 +31,7 @@
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { useEffect, useState, type ReactNode } from "react";
import { lazy, Suspense, useEffect, useState, type ReactNode } from "react";
import { endRuns } from "../../lib/stopSession";
import { isSubmitEnter } from "../../lib/keys";
import { Archive, GitBranch, Pin, PinOff, SquareTerminal } from "lucide-react";
@@ -46,6 +46,11 @@ import { useAiTools } from "../../hooks/useAiTools";
import { useThrottledValue } from "../../hooks/useThrottledValue";
import { useContextMenu } from "../ContextMenu";
import { SessionMenu } from "./SessionMenu";
import { usePermissions } from "../AuthGate";
const WorkspaceShareModal = lazy(() =>
import("./WorkspaceShareModal").then((m) => ({ default: m.WorkspaceShareModal }))
);
export const SESSION_LIMIT = 6;
@@ -256,6 +261,9 @@ export function WorkspaceSessionList({
const [busy, setBusy] = useState(false);
const ctx = useContextMenu<RunHandle>();
const sessionCtx = useContextMenu<Session>();
// Share one session (server mode, the workspace's owner or an admin).
const { local, ownsLane } = usePermissions();
const [sharing, setSharing] = useState<Session | null>(null);
// Rows shown; See all raises it to the whole list.
const [limit, setLimit] = useState(SESSION_LIMIT);
@@ -637,8 +645,18 @@ export function WorkspaceSessionList({
onPin={() =>
void patch(sessionCtx.menu!.item, { pinned: !sessionCtx.menu!.item.pinned_at })
}
onShare={!local && ownsLane(lane) ? () => setSharing(sessionCtx.menu!.item) : undefined}
/>
)}
{sharing && (
<Suspense fallback={null}>
<WorkspaceShareModal
lane={lane}
session={{ id: sharing.id, name: sharing.name }}
onClose={() => setSharing(null)}
/>
</Suspense>
)}
</>
);
}
@@ -1,8 +1,9 @@
/**
* @file WorkspaceShareModal — share a workspace with other users (server mode,
* docs/plans/workspace-sharing/ phase 1). Ticks people from
* `GET /api/artifacts/people` (names only) and saves the whole list through
* `PUT /api/lanes/:id/shares`. It says plainly what sharing means on this
* @file WorkspaceShareModal — share a workspace, or one of its sessions
* (`session`), with other users (server mode, docs/plans/workspace-sharing/
* phases 1 and 3). Ticks people from `GET /api/artifacts/people` (names only)
* and saves the whole list through `PUT /api/lanes/:id/shares` or
* `PUT /api/lanes/:id/sessions/:sid/shares`. It says plainly what sharing means on this
* server: the people it is shared with work as the owner's account and can
* read everything in the owner's home. Only the owner or an admin opens it —
* the server refuses anyone else (`ENOTOWNER`).
@@ -21,7 +22,16 @@ import { Checkbox } from "../Checkbox";
type Person = { id: number; username: string; name: string; disabled?: boolean };
export function WorkspaceShareModal({ lane, onClose }: { lane: Lane; onClose: () => void }) {
export function WorkspaceShareModal({
lane,
session,
onClose,
}: {
lane: Lane;
/** Share this one session instead of the whole workspace. */
session?: { id: string; name?: string | null };
onClose: () => void;
}) {
const { t } = useTranslation("lanes");
const panelRef = useRef<HTMLDivElement>(null);
useDialog(true, panelRef, onClose);
@@ -33,7 +43,11 @@ export function WorkspaceShareModal({ lane, onClose }: { lane: Lane; onClose: ()
useEffect(() => {
let alive = true;
Promise.all([api.artifacts.people(), api.lanes.shares(lane.id)])
const sid = session?.id;
Promise.all([
api.artifacts.people(),
sid ? api.lanes.sessionShares(lane.id, sid) : api.lanes.shares(lane.id),
])
.then(([p, s]) => {
if (!alive) return;
// Never the owner: a workspace is not shared with them. Someone it is
@@ -56,7 +70,7 @@ export function WorkspaceShareModal({ lane, onClose }: { lane: Lane; onClose: ()
return () => {
alive = false;
};
}, [lane.id, lane.owner_id]);
}, [lane.id, lane.owner_id, session?.id]);
const shown = useMemo(() => {
const q = query.trim().toLowerCase();
@@ -66,7 +80,7 @@ export function WorkspaceShareModal({ lane, onClose }: { lane: Lane; onClose: ()
}, [people, query]);
const added = [...picked].filter((id) => !initial.has(id));
const changed = added.length > 0 || [...initial].some((id) => !picked.has(id));
const name = lane.title || lane.cwd;
const name = session ? session.name || session.id : lane.title || lane.cwd;
const save = async () => {
if (added.length > 0) {
@@ -80,7 +94,9 @@ export function WorkspaceShareModal({ lane, onClose }: { lane: Lane; onClose: ()
}
setBusy(true);
try {
const r = await api.lanes.setShares(lane.id, [...picked]);
const r = session
? await api.lanes.setSessionShares(lane.id, session.id, [...picked])
: await api.lanes.setShares(lane.id, [...picked]);
toast.success(
r.shares.length ? t("share.saved", { count: r.shares.length }) : t("share.savedNone")
);
@@ -116,7 +132,7 @@ export function WorkspaceShareModal({ lane, onClose }: { lane: Lane; onClose: ()
<div className="flex items-start gap-3 border-b border-border px-5 py-4">
<div className="min-w-0 flex-1">
<h2 id="workspace-share-title" className="text-base font-semibold text-fg-primary">
{t("share.title")}
{t(session ? "share.sessionTitle" : "share.title")}
</h2>
<p className="mt-0.5 truncate text-xs text-fg-muted" title={lane.cwd}>
{name}
@@ -133,7 +149,9 @@ export function WorkspaceShareModal({ lane, onClose }: { lane: Lane; onClose: ()
</div>
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-5 py-4">
<p className="text-xs text-fg-secondary">{t("share.what")}</p>
<p className="text-xs text-fg-secondary">
{t(session ? "share.sessionWhat" : "share.what")}
</p>
<div
data-testid="workspace-share-warning"
className="flex gap-2 rounded-lg border border-status-warning/30 bg-status-warning/10 px-3 py-2 text-xs text-status-warning"
@@ -3,7 +3,8 @@
* on the current list, never offers the owner, warns what sharing means, asks
* once before adding someone and saves the WHOLE list; WorkspaceRowMenu offers
* Share (server mode) and the other owner-only items only to the workspace's
* owner or an admin.
* owner or an admin; given a session, it lists and saves THAT session's
* shares instead.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
@@ -30,11 +31,18 @@ const m = vi.hoisted(() => ({
people: vi.fn(),
shares: vi.fn(),
setShares: vi.fn(),
sessionShares: vi.fn(),
setSessionShares: vi.fn(),
}));
vi.mock("../../../lib/api", () => ({
api: {
artifacts: { people: m.people },
lanes: { shares: m.shares, setShares: m.setShares },
lanes: {
shares: m.shares,
setShares: m.setShares,
sessionShares: m.sessionShares,
setSessionShares: m.setSessionShares,
},
},
}));
@@ -159,3 +167,33 @@ describe("WorkspaceRowMenu on a shared workspace", () => {
expect(screen.getByText("Rename")).toBeInTheDocument();
});
});
describe("WorkspaceShareModal for one session", () => {
it("reads and saves that session's own list, never the workspace's", async () => {
m.shares.mockClear();
m.setShares.mockClear();
m.sessionShares.mockResolvedValue({ shares: [], canManage: true });
m.setSessionShares.mockResolvedValue({
shares: [{ id: 3, username: "carol", name: "Carol", sharedAt: "" }],
});
render(
<WorkspaceShareModal
lane={lane}
session={{ id: "s-1", name: "Fix cart" }}
onClose={() => {}}
/>
);
await settle();
expect(m.sessionShares).toHaveBeenCalledWith(7, "s-1");
expect(m.shares).not.toHaveBeenCalled();
expect(screen.getByText("Share session")).toBeTruthy();
expect(screen.getByText("Fix cart")).toBeTruthy();
fireEvent.click(screen.getByRole("checkbox", { name: /Carol/ }));
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await settle();
await act(async () => settleConfirm(true));
await settle();
expect(m.setSessionShares).toHaveBeenCalledWith(7, "s-1", [3]);
expect(m.setShares).not.toHaveBeenCalled();
});
});
+3 -1
View File
@@ -60,7 +60,9 @@ function onMessage(msg: WSMessage) {
const lane = payload.lane;
if (payload.removed !== undefined || !lane || !lanes) return void load();
const i = lanes.findIndex((l) => l.id === lane.id);
if (i === -1) return void load();
// A broadcast carries no viewer's `access`: a lane seen through a shared
// session re-reads it (its access may have changed too).
if (i === -1 || lanes[i]?.access) return void load();
const next = [...lanes];
next[i] = lane;
publish(next);
+4
View File
@@ -405,6 +405,10 @@
"share.disabled": "(disabled)",
"share.savedNone": "No longer shared with anyone",
"shared.ownAccount": "This workspace is shared with you: a session you start here runs on your own account — a pool account or an AI Proxy of yours — and is billed to you.",
"share.sessionTitle": "Share session",
"share.sessionWhat": "People you share it with see this session and the workspace's changes, join its open tab, type into it, send it messages (on their own account, billed to them) and commit — nothing else of the workspace. Only you share it. On this server they work as YOUR account inside its terminal, so they can still reach the rest of your home from there.",
"sessionMenu.share": "Share…",
"shared.sessionOnly": "Only a session of this workspace is shared with you: open it from the list to work in it.",
"shared.badge": "Shared with you",
"panel.changes": "Changes",
"panel.analyst": "Analyst",
+4
View File
@@ -405,6 +405,10 @@
"share.disabled": "(đã vô hiệu hoá)",
"share.savedNone": "Không còn chia sẻ với ai",
"shared.ownAccount": "Workspace này được chia sẻ với bạn: session bạn mở ở đây chạy bằng tài khoản của chính bạn — tài khoản pool hoặc AI Proxy của bạn — và tính tiền cho bạn.",
"share.sessionTitle": "Chia sẻ session",
"share.sessionWhat": "Người được chia sẻ thấy session này và các thay đổi của workspace, vào tab đang mở, gõ, gửi tin nhắn cho nó (bằng tài khoản của họ, tính tiền cho họ) và commit — không gì khác của workspace. Chỉ bạn chia sẻ được. Trên server này họ làm việc bằng TÀI KHOẢN CỦA BẠN trong terminal của nó, nên từ đó họ vẫn với tới được phần còn lại trong home của bạn.",
"sessionMenu.share": "Chia sẻ…",
"shared.sessionOnly": "Chỉ một session của workspace này được chia sẻ với bạn: mở nó từ danh sách để làm việc.",
"shared.badge": "Được chia sẻ với bạn",
"panel.changes": "Thay đổi",
"panel.analyst": "Analyst",
+11
View File
@@ -5113,6 +5113,17 @@ export const api = {
method: "PUT",
body: JSON.stringify({ userIds }),
}),
/** GET /api/lanes/:id/sessions/:sid/shares — the users one session is shared with. */
sessionShares: (id: number, sid: string) =>
request<{ shares: LaneShare[]; canManage: boolean }>(
`/workspaces/${id}/sessions/${encodeURIComponent(sid)}/shares`
),
/** PUT /api/lanes/:id/sessions/:sid/shares — the WHOLE list (owner or admin). */
setSessionShares: (id: number, sid: string, userIds: number[]) =>
request<{ shares: LaneShare[] }>(
`/workspaces/${id}/sessions/${encodeURIComponent(sid)}/shares`,
{ method: "PUT", body: JSON.stringify({ userIds }) }
),
removeSource: (id: number, sourceId: number) =>
request<LaneSourcesView>(`/workspaces/${id}/sources/${sourceId}`, { method: "DELETE" }),
/** GET /api/lanes/:id/memory — CLAUDE.md/AGENTS.md and Claude's auto memory, read-only. */
+2
View File
@@ -2708,6 +2708,8 @@ export interface Lane {
owner_display_name?: string | null;
/** When the owner's avatar was last set (`users.avatar_at`); null = none. */
owner_avatar_at?: string | null;
/** Server mode: `"session"` when only sessions of it are shared with this viewer. */
access?: "session";
branch: string | null;
kind: "managed" | "adopted";
/** The CLI this lane's runs spawn. Immutable once the lane exists. */
+17 -1
View File
@@ -2121,7 +2121,23 @@ session hours are billed to them (`session_payers`; a Terminal tab's stay the
owner's). A user disabled since stays on the
list (`disabled: true`) and may be kept or removed; only a new one must be enabled. Users taken off
get the WebSocket message `lane_access` `{laneId, userIds}` (sent to them only). See
`docs/SERVER-MODE.md` → Sharing a workspace.
`docs/SERVER-MODE.md` → Sharing a workspace. A collaborator's pane token
answers only that workspace's reads, the workspace list (filtered to it), its
stage / up / down / hook / feature / mcp-sync writes and `/api/health`
(`403 EPANESCOPE` — never a start or resume).
```http
GET /api/lanes/:id/sessions/:sid/shares → { shares, canManage }
PUT /api/lanes/:id/sessions/:sid/shares {"userIds": [3]} → { shares }
```
One session shared on its own (`session_shares`), same rules as the workspace
list (owner or admin, enabled users, audited `share session <id>`, `404
ENOSESSION` for a session of another workspace). The user gets the workspace
in `GET /api/lanes` with `access: "session"`, only that session in its session
lists, the pane holding it, a resume of it (`start {resumeSessionId}` — no
fork, no new session, no shell), and the workspace's git/Files reads and git
writes; any other call on the workspace answers `403 ESESSIONSHARE`.
#### Workspace context: instructions, folders, context files, memory
+35
View File
@@ -301,6 +301,41 @@ enabled. Every share and unshare is audited (`share workspace <id>` /
the next attach re-check. Deleting the workspace, or the user, drops the rows;
giving the workspace to a user it was shared with drops theirs.
**A collaborator's pane token acts as them inside that workspace only.** The
owner's account can read it (it sits in the owner's home), so it answers only
reads of `/api/lanes/<that id>/…` (and `/api/workspaces/<id>/…`), the
workspace list (which then holds that workspace only), `/api/health`, and its
`stage`, `up`, `down`, `hook/<name>`, `features/activate` and `mcp/sync`
writes (`paneLane`, `403 EPANESCOPE` for everything else) — never a start,
resume or any other call that could bill them. The CLI's workspace commands
work from their pane; the MCP server and the statusline's spend line do not.
A pane the owner or an admin opens still acts as the owner.
#### Sharing one session
The owner (or an admin) can also share ONE session: right-click it in the
sidebar → **Share…** (`GET/PUT /api/lanes/:id/sessions/:sid/shares`, table
`session_shares`, audited as `share session <id>`). The user sees the
workspace in their list (`access: "session"`) with only that session in it,
attaches to the pane holding it, sends it messages (a resume, on their own
account and billed to them, as above) and uses the workspace's Changes, git
and Files reads and git writes. Everything else of the workspace — another
session, a new session, a fork, a Terminal tab, `/api/run`, its instructions,
context and settings — answers `403 ESESSIONSHARE` (`sessionShareAllows` in
`scope.js`, checked in `scopeGuard`). Their run lists show only runs that held
that session, and a pane switching to another session closes their terminal
at the next attach re-check. Taking it back, deleting the workspace or the
user drops the rows. A resume names a free slot (`slot: "auto"`, never pane
0) and a session of THAT workspace; the session's name and archive state stay
the owner's (`PATCH /api/sessions/<id>` is `ESESSIONSHARE`), and the
workspace's extra folders (`?source=`), its files list for Artifacts and its
stage history stay out of reach. **These limits hold for the dashboard's API
only.** Under S3 the pane runs as the owner's Linux account: inside it the
user can `/resume` any session of the folder, run shell commands and read the
owner's home — a session share hands over as much as a workspace share
there. The Share dialog says so; share only with people you would hand your
keyboard to.
### AI Proxy profiles
Each user may keep **personal** AI Proxy profiles beside the **shared** ones:
+1 -1
View File
@@ -1,6 +1,6 @@
# Workspace & session sharing — plan
Status: **phases 1–2 built 2026-11-06** (workspace sharing; collaborators run on their own account, billed per payer by hour — `session_payers`; R1 decided as option **(a)** — accept and warn hard). Phases 3–4 not built.
Status: **phases 1–3 built 2026-11-06** (workspace sharing; collaborators run on their own account, billed per payer by hour — `session_payers`; one session can be shared — `session_shares`; R1 decided as option **(a)** — accept and warn hard). Phase 4 not built.
An independent review of phase 1 found and got fixed: a collaborator's Terminal
tab acted as the owner through its pane token (now `dashboard_runs.started_by`),
`POST /api/run {shell:true}` bypassed `ECOLLABSTART`, a disabled collaborator
+72
View File
@@ -20478,6 +20478,78 @@ paths:
description: ENOTOWNER.
'404':
description: ENOLANE — workspace not found.
/api/lanes/{id}/sessions/{sid}/shares:
get:
tags:
- Lanes
summary: The users one session of a workspace is shared with
description: 'Server mode (local mode: `{shares: [], canManage: false}`). `{shares:[{id, username, name, sharedAt}], canManage}` for session `sid` of this workspace (`404 ENOSESSION` otherwise).'
operationId: getSessionShares
parameters:
- name: id
in: path
required: true
schema:
type: integer
- name: sid
in: path
required: true
schema:
type: string
responses:
'200':
description: '`{shares, canManage}`.'
content:
application/json:
schema:
type: object
additionalProperties: true
'404':
description: ENOLANE — workspace not found.
put:
tags:
- Lanes
summary: Set the users one session of a workspace is shared with
description: '`{userIds:[…]}` is the WHOLE list (≤ 200 enabled users, never the workspace''s owner). The owner or an admin only (`403 ENOTOWNER`); same-origin; audited as `share session <id>` / `unshare session <id>`. A user it is shared with sees that session and its workspace (`access: "session"` in the workspace list), joins the pane holding it, resumes it on their own account and uses the workspace''s git — every other call on the workspace answers them `403 ESESSIONSHARE`.'
operationId: setSessionShares
parameters:
- name: id
in: path
required: true
schema:
type: integer
- name: sid
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- userIds
properties:
userIds:
type: array
items:
type: integer
responses:
'200':
description: '`{shares}`.'
content:
application/json:
schema:
type: object
additionalProperties: true
'400':
description: EBADUSER or ELOCALMODE.
'403':
description: ENOTOWNER.
'404':
description: ENOLANE — workspace not found.
/api/lanes/{id}/memory:
get:
tags:
+150
View File
@@ -299,6 +299,35 @@ describe("sharing a workspace", () => {
assert.equal(asUser(tokenFor(`agenthub-lane-${laneA}-1`, null))?.username, "alice");
const bobs = tokenFor(`agenthub-lane-${laneA}-2`, users.bob.id);
assert.equal(asUser(bobs)?.username, "bob");
// …inside this workspace only: the owner's account can read that token.
assert.equal(asUser(bobs)?.paneLane, laneA);
const guard = (p, method = "GET") => {
let out = null;
auth.authGuard(
{
path: p,
method,
headers: { "x-agenthub-pane-token": bobs },
socket: { remoteAddress: "127.0.0.1" },
},
{
status: (code) => ({ json: (body) => (out = { code, body }) }),
},
() => (out = "next")
);
return out;
};
assert.equal(guard(`/lanes/${laneA}`), "next");
assert.equal(guard(`/workspaces/${laneA}/git`), "next");
assert.equal(guard("/sessions").body.error.code, "EPANESCOPE");
assert.equal(guard(`/lanes/${laneA + 1000}`).body.error.code, "EPANESCOPE");
assert.equal(guard("/me").body.error.code, "EPANESCOPE");
// The CLI finds its workspace in the list (which answers that one only)…
assert.equal(guard("/workspaces"), "next");
// …and never starts or bills a session with it.
assert.equal(guard(`/lanes/${laneA}/start`, "POST").body.error.code, "EPANESCOPE");
assert.equal(guard(`/lanes/${laneA}/reset`, "POST").body.error.code, "EPANESCOPE");
assert.equal(guard("/run", "POST").body.error.code, "EPANESCOPE");
// No longer shared with him: his pane's token is nobody.
db.prepare("DELETE FROM lane_shares WHERE lane_id = ? AND user_id = ?").run(
laneA,
@@ -371,3 +400,124 @@ describe("sharing a workspace", () => {
);
});
});
describe("sharing one session", () => {
let laneS;
before(() => {
laneS = Number(
db
.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES ('/w/alice2', 'claude', ?)")
.run(users.alice.id).lastInsertRowid
);
for (const id of ["s1-shared", "s2-private"]) {
db.prepare(
"INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES (?, ?, 'completed', '/w/alice2', ?)"
).run(id, id, laneS);
}
});
const put = (as, userIds, sid = "s1-shared") =>
call("PUT", `/api/lanes/${laneS}/sessions/${sid}/shares`, { as, body: { userIds } });
it("is managed by the workspace's owner only, for a session of that workspace", async () => {
assert.equal((await put("carol", [users.carol.id])).status, 404);
assert.equal((await put("alice", [users.carol.id], "sA")).status, 404, "not this workspace's");
const r = await put("alice", [users.carol.id]);
assert.equal(r.status, 200);
assert.deepEqual(
r.body.shares.map((u) => u.username),
["carol"]
);
assert.equal(
db.prepare("SELECT COUNT(*) AS n FROM audit_log WHERE path = 'share session s1-shared'").get()
.n,
1
);
});
it("shows that session and its workspace — no other session of it", async () => {
const lanes = (await call("GET", "/api/lanes", { as: "carol" })).body.lanes;
const mine = lanes.find((l) => l.id === laneS);
assert.equal(mine?.access, "session");
const list = await call("GET", `/api/sessions?lane=${laneS}`, { as: "carol" });
assert.deepEqual(
list.body.sessions.map((s) => s.id),
["s1-shared"]
);
assert.equal((await call("GET", "/api/sessions/s1-shared", { as: "carol" })).status, 200);
assert.equal((await call("GET", "/api/sessions/s2-private", { as: "carol" })).status, 404);
});
it("allows that session's pane, Changes and a resume of it — nothing else of the workspace", async () => {
const scope = require("../lib/scope");
const req = { user: { id: users.carol.id, role: "developer" }, method: "POST" };
const run = (id, sid) =>
db
.prepare(
`INSERT OR REPLACE INTO dashboard_runs (id, session_id, mode, cwd, status, lane_id, tool)
VALUES (?, ?, 'interactive', '/w/alice2', 'running', ?, 'claude')`
)
.run(id, sid, laneS);
run(`agenthub-lane-${laneS}-1`, "s1-shared");
run(`agenthub-lane-${laneS}-2`, "s2-private");
assert.equal(scope.canSeeRun(req, `agenthub-lane-${laneS}-1`), true);
assert.equal(scope.canSeeRun(req, `agenthub-lane-${laneS}-2`), false);
assert.equal(scope.canSeeRun(req, `agenthub-lane-${laneS}`), false, "no run there");
const refused = async (method, p, body) => {
const r = await call(method, p, { as: "carol", body });
assert.equal(r.status, 403, `${method} ${p} → ${r.status}`);
assert.equal(r.body.error.code, "ESESSIONSHARE");
};
await refused("PATCH", `/api/lanes/${laneS}`, { title: "x" });
await refused("GET", `/api/lanes/${laneS}/sources`);
await refused("PUT", `/api/lanes/${laneS}/instructions`, { instructions: "x" });
await refused("POST", `/api/lanes/${laneS}/start`, { slot: "auto", prompt: "new" });
await refused("POST", `/api/lanes/${laneS}/start`, { shell: true });
await refused("POST", `/api/lanes/${laneS}/start`, {
resumeSessionId: "s1-shared",
forkSession: true,
});
await refused("POST", "/api/run", { laneId: laneS, initialPrompt: "hi" });
await refused("POST", `/api/lanes/${laneS}/start`, { resumeSessionId: "s1-shared", slot: 0 });
await refused("GET", `/api/lanes/${laneS}/git/tree?source=1`);
await refused("GET", `/api/artifacts/candidates?laneId=${laneS}`);
await refused("PATCH", "/api/sessions/s1-shared", { name: "mine now" });
// A shared session resumed only in its own workspace.
const laneT = Number(
db
.prepare("INSERT INTO lanes (cwd, tool, owner_id) VALUES ('/w/alice3', 'claude', ?)")
.run(users.alice.id).lastInsertRowid
);
db.prepare(
"INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('sT-other', 't', 'completed', '/w/alice3', ?)"
).run(laneT);
db.prepare("INSERT INTO session_shares (session_id, user_id) VALUES ('sT-other', ?)").run(
users.carol.id
);
await refused("POST", `/api/lanes/${laneT}/start`, { resumeSessionId: "s1-shared" });
db.prepare("DELETE FROM session_shares WHERE session_id = 'sT-other'").run();
// Another session of it is not even there.
const other = await call("POST", `/api/lanes/${laneS}/start`, {
as: "carol",
body: { resumeSessionId: "s2-private" },
});
assert.equal(other.status, 404);
// A resume of the shared one gets past the scope (and then needs their own account).
const resume = await call("POST", `/api/lanes/${laneS}/start`, {
as: "carol",
body: { resumeSessionId: "s1-shared", prompt: "hi" },
});
assert.ok(![403, 404].includes(resume.status), JSON.stringify(resume.body));
// Reads of the workspace's git and its own row pass.
assert.equal((await call("GET", `/api/lanes/${laneS}`, { as: "carol" })).status, 200);
const git = await call("GET", `/api/lanes/${laneS}/git`, { as: "carol" });
assert.notEqual(git.status, 403);
db.prepare("DELETE FROM dashboard_runs WHERE lane_id = ?").run(laneS);
});
it("ends their access when it is taken back", async () => {
assert.equal((await put("alice", [])).status, 200);
assert.ok(!(await laneIds("carol")).includes(laneS));
assert.equal((await call("GET", "/api/sessions/s1-shared", { as: "carol" })).status, 404);
});
});
+14
View File
@@ -1014,6 +1014,20 @@ db.exec(`
CREATE INDEX IF NOT EXISTS idx_lane_shares_user ON lane_shares(user_id);
`);
// A single session shared with another user (sharing phase 3): they see that
// session and its workspace's Changes, join its pane and resume it — nothing
// else of the workspace. No foreign keys, like lane_shares.
db.exec(`
CREATE TABLE IF NOT EXISTS session_shares (
session_id TEXT NOT NULL,
user_id INTEGER NOT NULL,
granted_by INTEGER,
shared_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
PRIMARY KEY (session_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_session_shares_user ON session_shares(user_id);
`);
// Who pays for a session from which UTC hour on (sharing phase 2,
// server/lib/session-payers.js): written only once someone other than the
// workspace's owner runs it — a session with no row is its owner's. `from_hour`
+62 -6
View File
@@ -258,9 +258,36 @@ function validateProfile(body) {
// Latin look-alikes from other scripts, so "Vĩ" in Cyrillic still collides.
const CONFUSABLE = {
а: "a", в: "b", е: "e", к: "k", м: "m", н: "h", о: "o", р: "p", с: "c", т: "t",
у: "y", х: "x", і: "i", ј: "j", ԁ: "d", ѕ: "s", ӏ: "l", α: "a", β: "b", ε: "e",
η: "n", ι: "i", κ: "k", ν: "v", ο: "o", ρ: "p", τ: "t", υ: "u", χ: "x", "ı": "i",
а: "a",
в: "b",
е: "e",
к: "k",
м: "m",
н: "h",
о: "o",
р: "p",
с: "c",
т: "t",
у: "y",
х: "x",
і: "i",
ј: "j",
ԁ: "d",
ѕ: "s",
ӏ: "l",
α: "a",
β: "b",
ε: "e",
η: "n",
ι: "i",
κ: "k",
ν: "v",
ο: "o",
ρ: "p",
τ: "t",
υ: "u",
χ: "x",
ı: "i",
};
/**
@@ -519,6 +546,7 @@ function deleteUser(username) {
sql("DELETE FROM user_prefs WHERE user_key = ?").run(`u${u.id}`);
// Workspaces other users shared with them (lane_shares has no foreign key).
sql("DELETE FROM lane_shares WHERE user_id = ?").run(u.id);
sql("DELETE FROM session_shares WHERE user_id = ?").run(u.id);
require("./avatars").removeAvatar(u.id);
try {
sql("DELETE FROM push_subscriptions WHERE user_id = ?").run(u.id);
@@ -549,6 +577,9 @@ function assignWorkspace(laneId, username) {
if (r.changes === 0) throw err("ENOLANE", `no workspace ${laneId}`);
// Its new owner no longer needs it shared with them.
sql("DELETE FROM lane_shares WHERE lane_id = ? AND user_id = ?").run(Number(laneId), u.id);
sql(
"DELETE FROM session_shares WHERE user_id = ? AND session_id IN (SELECT id FROM sessions WHERE lane_id = ?)"
).run(u.id, Number(laneId));
}
/** Take a workspace back from the user who owns it: it is left with no owner
@@ -741,7 +772,7 @@ function userFromPaneToken(req) {
if (typeof t !== "string" || !t.startsWith("ahpane_") || t.length > 200) return null;
if (!isLocalRequest(req)) return null;
const row = sql(
`SELECT r.id, r.lane_id, r.started_by, l.owner_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id
`SELECT r.id, r.lane_id, r.session_id, r.started_by, l.owner_id FROM dashboard_runs r JOIN lanes l ON l.id = r.lane_id
WHERE r.pane_token_hash = ? AND r.status IN ('running', 'spawning') AND instr(r.id, '@') = 0`
).get(sha256(t));
if (!row || row.owner_id == null) return null;
@@ -754,11 +785,33 @@ function userFromPaneToken(req) {
if (
uid !== row.owner_id &&
user.role !== "admin" &&
!require("./scope").sharedWith(row.lane_id, uid)
!require("./scope").sharedWith(row.lane_id, uid) &&
!require("./scope").sessionSharedWith(row.session_id, uid)
) {
return null;
}
return publicUser(user) || null;
const pub = publicUser(user);
if (!pub) return null;
// A collaborator's pane runs as the OWNER's Linux account, which can read
// its token: it acts as the collaborator inside this workspace only
// (`paneLane`, authGuard), never across their account.
return uid !== row.owner_id ? { ...pub, paneLane: row.lane_id } : pub;
}
/**
* What a collaborator's pane token may call — the CLI's workspace commands,
* nothing that starts or bills a session (the owner's account can read the
* token): reads of its own workspace (and the workspace list, which answers
* that one only), health, and its stage / stack / hook / feature writes.
*/
function paneLaneAllows(method, lp, laneId) {
const read = method === "GET" || method === "HEAD";
if (lp === "/health") return true;
if (read && /^\/(?:lanes|workspaces)\/?$/i.test(lp)) return true;
const m = /^\/(?:lanes|workspaces)\/(\d+)(\/.*)?$/i.exec(lp);
if (!m || Number(m[1]) !== laneId) return false;
if (read) return true;
return /^\/(stage|up|down|hook\/[^/]+|features\/activate|mcp\/sync)$/i.test(m[2] || "");
}
// ── Gates ───────────────────────────────────────────────────────────────────
@@ -814,6 +867,9 @@ function authGuard(req, res, next) {
const cookieUser = userFromRequest(req);
const user = cookieUser || userFromPaneToken(req);
if (!user) return deny(res, 401, "EAUTH", "log in first");
if (!cookieUser && user.paneLane != null && !paneLaneAllows(req.method, lp, user.paneLane)) {
return deny(res, 403, "EPANESCOPE", "this pane's token acts only inside its own workspace");
}
req.user = user;
// A password an admin gave: the login may only read its own account and
// pick its own password until it has.
+6 -1
View File
@@ -332,7 +332,12 @@ function setProvisioningFacts(id, facts = {}) {
function deleteLane(id) {
const gone = db.prepare("DELETE FROM lanes WHERE id = ?").run(id).changes > 0;
// Who it was shared with goes with it (lane_shares has no foreign key).
if (gone) db.prepare("DELETE FROM lane_shares WHERE lane_id = ?").run(id);
if (gone) {
db.prepare("DELETE FROM lane_shares WHERE lane_id = ?").run(id);
db.prepare(
"DELETE FROM session_shares WHERE session_id IN (SELECT id FROM sessions WHERE lane_id = ?)"
).run(id);
}
// Its `lane_sources` rows cascade; AgentHub's own copies of its uploaded
// context files go with them. A folder source is the user's and stays.
// Lazy: lane-sources.js reads the db directly and must not load at import.
+156 -21
View File
@@ -66,7 +66,14 @@ function ownSessionWhere(req, col = "id", laneCol = "lane_id") {
}
// The workspaces a user owns or that are shared with them (2 params: uid, uid).
const MY_LANES = "SELECT id FROM lanes WHERE owner_id = ? UNION SELECT lane_id FROM lane_shares WHERE user_id = ?";
const MY_LANES =
"SELECT id FROM lanes WHERE owner_id = ? UNION SELECT lane_id FROM lane_shares WHERE user_id = ?";
// The sessions shared with a user one by one (1 param: uid), and the
// workspaces holding them (sharing phase 3: seen, but only that session).
const MY_SESSIONS = "SELECT session_id FROM session_shares WHERE user_id = ?";
const SESSION_LANES = `SELECT lane_id FROM sessions WHERE lane_id IS NOT NULL AND id IN (${MY_SESSIONS})`;
// Every workspace a user may open (3 params: uid ×3).
const SEEN_LANES = `${MY_LANES} UNION ${SESSION_LANES}`;
function ownedSessionWhere(uid, col, laneCol, shared = false) {
if (uid == null) return { where: "1", params: [] };
@@ -77,8 +84,13 @@ function ownedSessionWhere(uid, col, laneCol, shared = false) {
OR ${col} IN (SELECT r.session_id FROM dashboard_runs r
WHERE r.lane_id IN (${lanes}) AND r.session_id IS NOT NULL)
OR ${col} IN (SELECT id FROM sessions WHERE owner_id = ?)
OR ${col} IN (SELECT session_id FROM (${ACCOUNT_OWNED}) WHERE uid = ?))`,
params: [...lp, ...lp, uid, uid],
OR ${col} IN (SELECT session_id FROM (${ACCOUNT_OWNED}) WHERE uid = ?)${
shared
? `
OR ${col} IN (${MY_SESSIONS})`
: ""
})`,
params: [...lp, ...lp, uid, uid, ...(shared ? [uid] : [])],
};
}
@@ -94,7 +106,36 @@ function bySessionWhere(req, col = "session_id") {
function laneWhere(req, col = "id") {
const uid = memberId(req);
if (uid == null) return { where: "1", params: [] };
return { where: `${col} IN (${MY_LANES})`, params: [uid, uid] };
return { where: `${col} IN (${SEEN_LANES})`, params: [uid, uid, uid] };
}
/** Whether session `sessionId` is shared with `userId` on its own (phase 3). */
function sessionSharedWith(sessionId, userId) {
if (!sessionId || userId == null) return false;
return Boolean(
sql("SELECT 1 FROM session_shares WHERE session_id = ? AND user_id = ?").get(
String(sessionId),
userId
)
);
}
/**
* How much of workspace `laneId` this request may use: `all` (local mode, an
* admin or analyst read, its owner, a user it is shared with), `session`
* (only sessions shared with them one by one), or null.
*/
function laneAccess(req, laneId) {
const uid = memberId(req);
if (uid == null) return "all";
const v = typeof laneId === "number" ? laneId : String(laneId);
const row = sql("SELECT id, owner_id FROM lanes WHERE id = ?").get(v);
if (!row) return null;
if (row.owner_id === uid || sharedWith(row.id, uid)) return "all";
const one = sql(
`SELECT 1 FROM sessions WHERE lane_id = ? AND id IN (${MY_SESSIONS}) LIMIT 1`
).get(row.id, uid);
return one ? "session" : null;
}
/** Whether `userId` is one of the users workspace `laneId` is shared with. */
@@ -123,9 +164,7 @@ function canSeeLane(req, laneId) {
// Bound as given, like getLane binds a route param: SQLite's integer
// affinity reads '9002.0' or ' 9002' as 9002 for both, so the row checked
// here is the row the route would load.
const v = typeof laneId === "number" ? laneId : String(laneId);
const row = sql("SELECT id, owner_id FROM lanes WHERE id = ?").get(v);
return Boolean(row) && (row.owner_id === uid || sharedWith(row.id, uid));
return laneAccess(req, laneId) != null;
}
function canSeeSession(req, sessionId) {
@@ -146,7 +185,13 @@ function canSeeAgent(req, agentId) {
function canSeeRun(req, runId) {
if (memberId(req) == null) return true;
const m = /^agenthub-lane-(\d+)(?:-\d+)?(?:@.*)?$/.exec(String(runId || ""));
if (m) return canSeeLane(req, m[1]);
if (m) {
const access = laneAccess(req, m[1]);
if (access !== "session") return access != null;
// A session shared on its own: only the pane holding that session.
const row = sql("SELECT session_id FROM dashboard_runs WHERE id = ?").get(String(runId));
return Boolean(row?.session_id) && sessionSharedWith(row.session_id, memberId(req));
}
const row = sql("SELECT lane_id FROM dashboard_runs WHERE id = ?").get(String(runId));
return Boolean(row && row.lane_id != null) && canSeeLane(req, row.lane_id);
}
@@ -155,9 +200,9 @@ function canSeeRun(req, runId) {
function visibleLaneIds(req) {
const uid = memberId(req);
if (uid == null) return null;
return sql(MY_LANES)
.all(uid, uid)
.map((r) => r.id);
return sql(SEEN_LANES)
.all(uid, uid, uid)
.map((r) => r.lane_id ?? r.id);
}
/** A row of `table` (`id` = `rowId`) whose `session_id` this request may see. */
@@ -170,8 +215,11 @@ function canSeeRowSession(req, table, rowId, idCol = "id") {
/** A `dashboard_runs` row (`/api/run/history/:id`) of one of this request's workspaces. */
function canSeeRunRow(req, id) {
if (memberId(req) == null) return true;
const row = sql("SELECT lane_id FROM dashboard_runs WHERE id = ?").get(String(id));
return Boolean(row && row.lane_id != null) && canSeeLane(req, row.lane_id);
const row = sql("SELECT lane_id, session_id FROM dashboard_runs WHERE id = ?").get(String(id));
if (!row || row.lane_id == null) return false;
const access = laneAccess(req, row.lane_id);
if (access !== "session") return access != null;
return Boolean(row.session_id) && sessionSharedWith(row.session_id, memberId(req));
}
/**
@@ -272,6 +320,28 @@ function scopeGuard(req, res, next) {
if (bad) return notFound();
if (lanes.some((id) => !/^\d+$/.test(id) || !canSeeLane(req, Number(id)))) return notFound();
if (sessions.some((id) => !canSeeSession(req, id))) return notFound();
// A workspace seen only through a session shared on its own (phase 3):
// that session, its pane and the workspace's Changes — nothing else of it.
const write = req.method !== "GET" && req.method !== "HEAD";
const pm = /^\/(?:lanes|workspaces)\/(\d+)(\/.*)?$/i.exec(p);
if (
pm &&
laneAccess(req, Number(pm[1])) === "session" &&
!sessionShareAllows(req, pm[2] || "", Number(pm[1]))
) {
return sessionOnly(res);
}
const viaSession = lanes.some((id) => laneAccess(req, Number(id)) === "session");
// Workspace-wide reads by `?laneId=`: files and skills of every session, stage history.
if (
viaSession &&
(write || /^\/(artifacts|lanes\/pipeline-stats|workspaces\/pipeline-stats)(\/|$)/i.test(p))
) {
return sessionOnly(res);
}
// The shared session itself: open it, never rename or archive it.
const sm = /^\/sessions\/([^/]+)/i.exec(p);
if (write && sm && sessionOnlyVia(req, sm[1])) return sessionOnly(res);
// S3: a WRITE to a workspace re-checks that its owner may still own that
// folder, by the LIVE role — an admin demoted since keeps owning their
// host-folder workspaces, and `/up`, `/hook`, a commit (git hooks) or a
@@ -292,6 +362,54 @@ function scopeGuard(req, res, next) {
return next();
}
/** Whether this request sees session `sid` only because it is shared with them on its own. */
function sessionOnlyVia(req, sid) {
const uid = memberId(req);
if (uid == null || !sessionSharedWith(sid, uid)) return false;
const row = sql("SELECT lane_id FROM sessions WHERE id = ?").get(String(sid));
return !row?.lane_id || laneAccess(req, row.lane_id) === "session";
}
const sessionOnly = (res) =>
res.status(403).json({
error: {
code: "ESESSIONSHARE",
message: "only a session of this workspace is shared with you: open that session",
},
});
/**
* What a user with only a session of workspace (rest = the path after
* `/lanes/<id>`) may call there: reads of the workspace, its git, files and
* share list (not its instructions or context); git writes; and a `start` that
* resumes a session shared with them — no new session, fork or terminal.
*/
function sessionShareAllows(req, rest, laneId) {
const r = rest.toLowerCase();
// A workspace's extra folders are its own, not the session's.
if (req.query?.source !== undefined) return false;
if (req.method === "GET" || req.method === "HEAD") {
return r === "" || r === "/" || /^\/(git|fs|shares)(\/|$)/.test(r);
}
if (/^\/git\//.test(r)) return true;
if (r === "/start") {
const b = req.body && typeof req.body === "object" ? req.body : {};
return (
typeof b.resumeSessionId === "string" &&
b.forkSession !== true &&
b.shell !== true &&
b.resume !== true &&
// A free slot the server picks: pane 0 is the workspace's own run.
(b.slot === undefined || b.slot === "auto") &&
sessionSharedWith(b.resumeSessionId, memberId(req)) &&
Boolean(
sql("SELECT 1 FROM sessions WHERE id = ? AND lane_id = ?").get(b.resumeSessionId, laneId)
)
);
}
return false;
}
/** Whether a workspace's owner may still own its folder (S3, live role). */
function ownerStillFits(laneId) {
const lane = sql("SELECT cwd, owner_id FROM lanes WHERE id = ?").get(laneId);
@@ -329,12 +447,23 @@ function laneOwners(laneId) {
return new Set(row && row.owner_id != null ? [row.owner_id] : []);
}
/** The users a workspace is shared with — they get its news, but it is not "theirs". */
function laneViewers(laneId) {
/**
* The users a workspace is shared with — they get its news, but it is not
* "theirs". `sessions`: also those with only a session of it (its row
* changes, never its stack's output).
*/
function laneViewers(laneId, { sessions = false } = {}) {
if (laneId == null) return new Set();
return new Set(
sql("SELECT user_id FROM lane_shares WHERE lane_id = ?")
.all(Number(laneId))
sql(
`SELECT user_id FROM lane_shares WHERE lane_id = ?${
sessions
? ` UNION SELECT user_id FROM session_shares
WHERE session_id IN (SELECT id FROM sessions WHERE lane_id = ?)`
: ""
}`
)
.all(...(sessions ? [Number(laneId), Number(laneId)] : [Number(laneId)]))
.map((r) => r.user_id)
);
}
@@ -346,9 +475,10 @@ function sessionViewers(sessionId) {
sql(
`SELECT user_id FROM lane_shares WHERE lane_id IN (
SELECT lane_id FROM sessions WHERE id = ? AND lane_id IS NOT NULL
UNION SELECT lane_id FROM dashboard_runs WHERE session_id = ? AND lane_id IS NOT NULL)`
UNION SELECT lane_id FROM dashboard_runs WHERE session_id = ? AND lane_id IS NOT NULL)
UNION SELECT user_id FROM session_shares WHERE session_id = ?`
)
.all(String(sessionId), String(sessionId))
.all(String(sessionId), String(sessionId), String(sessionId))
.map((r) => r.user_id)
);
}
@@ -380,7 +510,10 @@ function broadcastAudience(type, data) {
case "lane_update":
// A removal names an id that no longer resolves; it reveals nothing.
if (d.removed != null && !d.lane) return null;
return { owners: laneOwners(d.lane?.id), viewers: laneViewers(d.lane?.id) };
return {
owners: laneOwners(d.lane?.id),
viewers: laneViewers(d.lane?.id, { sessions: true }),
};
case "lane_hook_output":
case "lane_hook_result":
case "lane_runtime":
@@ -433,7 +566,7 @@ function audienceIncludes(audience, user) {
if (audience === null || audience.strip) return true;
return Boolean(
(audience.owners && audience.owners.has(user.id)) ||
(audience.viewers && audience.viewers.has(user.id))
(audience.viewers && audience.viewers.has(user.id))
);
}
@@ -556,6 +689,8 @@ module.exports = {
PATH_RULES,
canSeeRowSession,
canSeeRunRow,
laneAccess,
sessionSharedWith,
folderAllowed,
ownFolder,
memberId,
+4 -2
View File
@@ -335,9 +335,11 @@ function sharedAccounts(userId) {
const out = new Map();
for (const { cwd } of db()
.prepare(
"SELECT l.cwd FROM lane_shares ls JOIN lanes l ON l.id = ls.lane_id WHERE ls.user_id = ?"
`SELECT l.cwd FROM lane_shares ls JOIN lanes l ON l.id = ls.lane_id WHERE ls.user_id = ?
UNION SELECT l.cwd FROM session_shares ss JOIN sessions s ON s.id = ss.session_id
JOIN lanes l ON l.id = s.lane_id WHERE ss.user_id = ?`
)
.all(userId)) {
.all(userId, userId)) {
try {
const acct = runAs.accountForPath(cwd);
if (acct) out.set(acct.name, acct);
+43
View File
@@ -738,6 +738,49 @@ const paths = {
},
},
},
"/api/lanes/{id}/sessions/{sid}/shares": {
get: {
tags: ["Lanes"],
summary: "The users one session of a workspace is shared with",
description:
"Server mode (local mode: `{shares: [], canManage: false}`). `{shares:[{id, username, name, sharedAt}], canManage}` for session `sid` of this workspace (`404 ENOSESSION` otherwise).",
operationId: "getSessionShares",
parameters: [
idParam,
{ name: "sid", in: "path", required: true, schema: { type: "string" } },
],
responses: { 200: { description: "`{shares, canManage}`.", ...json(obj) }, 404: notFound },
},
put: {
tags: ["Lanes"],
summary: "Set the users one session of a workspace is shared with",
description:
"`{userIds:[…]}` is the WHOLE list (≤ 200 enabled users, never the workspace's owner). The owner or an admin only (`403 ENOTOWNER`); same-origin; audited as `share session <id>` / `unshare session <id>`. A user it is shared with sees that session and its workspace (`access: \"session\"` in the workspace list), joins the pane holding it, resumes it on their own account and uses the workspace's git — every other call on the workspace answers them `403 ESESSIONSHARE`.",
operationId: "setSessionShares",
parameters: [
idParam,
{ name: "sid", in: "path", required: true, schema: { type: "string" } },
],
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["userIds"],
properties: { userIds: { type: "array", items: { type: "integer" } } },
},
},
},
},
responses: {
200: { description: "`{shares}`.", ...json(obj) },
400: { description: "EBADUSER or ELOCALMODE." },
403: { description: "ENOTOWNER." },
404: notFound,
},
},
},
"/api/lanes/{id}/memory": {
get: {
tags: ["Lanes"],
+139 -66
View File
@@ -229,11 +229,23 @@ function broadcastLane(id) {
router.get("/", (req, res) => {
// Server mode: a member lists (and counts) only their own workspaces.
const visible = scope.visibleLaneIds(req);
const rows = lanesLib.listLanes().filter((l) => visible === null || visible.includes(l.id));
// A collaborator's pane token: its own workspace only (auth.js paneLaneAllows).
const paneLane = req.user?.paneLane ?? null;
const rows = lanesLib
.listLanes()
.filter(
(l) => (visible === null || visible.includes(l.id)) && (paneLane == null || l.id === paneLane)
);
// ONE list-sessions answers every lane's run, instead of a synchronous
// has-session per lane (null when tmux could not be asked: per-lane then).
const live = rows.some((l) => l.run_id) ? tmux.liveSessions() : null;
const lanes = rows.map((l) => payload(l, live));
// `access: "session"`: only sessions of it are shared with this user (phase 3).
const lanes = rows.map((l) => {
const p = payload(l, live);
return visible !== null && scope.laneAccess(req, l.id) === "session"
? { ...p, access: "session" }
: p;
});
res.json({
lanes,
counts: {
@@ -1402,17 +1414,89 @@ router.patch("/:id", sameOriginGuard, (req, res) => {
const MAX_SHARES = 200;
function laneShares(laneId) {
/** The users a workspace (`lane_shares`) or one session (`session_shares`) is shared with. */
function sharesOf(table, keyCol, key) {
return require("../db")
.db.prepare(
`SELECT u.id, u.username, COALESCE(NULLIF(u.display_name, ''), u.username) AS name,
s.shared_at AS sharedAt, u.disabled
FROM lane_shares s JOIN users u ON u.id = s.user_id
WHERE s.lane_id = ? ORDER BY name COLLATE NOCASE`
FROM ${table} s JOIN users u ON u.id = s.user_id
WHERE s.${keyCol} = ? ORDER BY name COLLATE NOCASE`
)
.all(Number(laneId))
.all(key)
.map((u) => ({ ...u, disabled: Boolean(u.disabled) }));
}
const laneShares = (laneId) => sharesOf("lane_shares", "lane_id", Number(laneId));
const sessionShares = (sessionId) => sharesOf("session_shares", "session_id", String(sessionId));
/**
* Replace the WHOLE share list of a workspace or a session with `req.body.userIds`:
* server mode, the workspace's owner or an admin, enabled users only (one
* already listed may stay though disabled since), never the owner; every
* change audited as `<verb> <what> <id>`. Answers the new list, or sends the
* error and answers null.
*/
function replaceShares(req, res, { lane, table, keyCol, key, what }) {
const auth = require("../lib/auth");
if (!auth.isServerMode()) {
res.status(400).json({ error: { code: "ELOCALMODE", message: "sharing needs server mode" } });
return null;
}
if (!scope.isLaneOwner(req, lane.id)) {
notOwner(res);
return null;
}
const raw = req.body?.userIds;
if (
!Array.isArray(raw) ||
raw.length > MAX_SHARES ||
!raw.every((x) => Number.isInteger(x) && x > 0)
) {
res
.status(400)
.json({ error: { code: "EBADUSER", message: "userIds must be a list of user ids" } });
return null;
}
const { db } = require("../db");
const wanted = [...new Set(raw)];
const before = new Set(sharesOf(table, keyCol, key).map((u) => u.id));
const user = db.prepare("SELECT id, disabled FROM users WHERE id = ?");
for (const id of wanted) {
const u = user.get(id);
// A user already on the list may since have been disabled: keeping them
// must not block every other change (it grants nothing while disabled).
if (!u || (u.disabled && !before.has(id))) {
res.status(400).json({ error: { code: "EBADUSER", message: `no enabled user ${id}` } });
return null;
}
if (id === lane.owner_id) {
res
.status(400)
.json({ error: { code: "EBADUSER", message: `a ${what} is not shared with its owner` } });
return null;
}
}
const added = wanted.filter((id) => !before.has(id));
const removed = [...before].filter((id) => !wanted.includes(id));
const actor = req.user?.id ?? null;
db.transaction(() => {
const del = db.prepare(`DELETE FROM ${table} WHERE ${keyCol} = ? AND user_id = ?`);
const ins = db.prepare(
`INSERT OR IGNORE INTO ${table} (${keyCol}, user_id, granted_by) VALUES (?, ?, ?)`
);
for (const id of removed) del.run(key, id);
for (const id of added) ins.run(key, id, actor);
})();
const audit = require("../lib/audit");
for (const id of added) audit.recordAccountChange(actor, id, "PUT", `share ${what} ${key}`);
for (const id of removed) audit.recordAccountChange(actor, id, "PUT", `unshare ${what} ${key}`);
// The owner and everyone it is shared with now re-read it; the users taken
// off re-read their list, and their open terminals on it close at the next
// attach re-check (websocket.js).
broadcastLane(lane.id);
if (removed.length) broadcast("lane_access", { laneId: lane.id, userIds: removed });
return sharesOf(table, keyCol, key);
}
router.get("/:id/shares", (req, res) => {
const lane = lanesLib.getLane(req.params.id);
@@ -1424,67 +1508,55 @@ router.get("/:id/shares", (req, res) => {
/** `{userIds}` — the WHOLE list of users the workspace is shared with. */
router.put("/:id/shares", sameOriginGuard, (req, res) => {
const auth = require("../lib/auth");
if (!auth.isServerMode()) {
return res
.status(400)
.json({ error: { code: "ELOCALMODE", message: "sharing needs server mode" } });
}
const lane = lanesLib.getLane(req.params.id);
if (!lane)
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
if (!scope.isLaneOwner(req, lane.id)) return notOwner(res);
const raw = req.body?.userIds;
if (
!Array.isArray(raw) ||
raw.length > MAX_SHARES ||
!raw.every((x) => Number.isInteger(x) && x > 0)
) {
return res
.status(400)
.json({ error: { code: "EBADUSER", message: "userIds must be a list of user ids" } });
}
const { db } = require("../db");
const wanted = [...new Set(raw)];
const before = new Set(laneShares(lane.id).map((u) => u.id));
const user = db.prepare("SELECT id, disabled FROM users WHERE id = ?");
for (const id of wanted) {
const u = user.get(id);
// A user already on the list may since have been disabled: keeping them
// must not block every other change (it grants nothing while disabled).
if (!u || (u.disabled && !before.has(id))) {
return res
.status(400)
.json({ error: { code: "EBADUSER", message: `no enabled user ${id}` } });
}
if (id === lane.owner_id) {
return res
.status(400)
.json({ error: { code: "EBADUSER", message: "a workspace is not shared with its owner" } });
}
}
const added = wanted.filter((id) => !before.has(id));
const removed = [...before].filter((id) => !wanted.includes(id));
const actor = req.user?.id ?? null;
db.transaction(() => {
const del = db.prepare("DELETE FROM lane_shares WHERE lane_id = ? AND user_id = ?");
const ins = db.prepare(
"INSERT OR IGNORE INTO lane_shares (lane_id, user_id, granted_by) VALUES (?, ?, ?)"
);
for (const id of removed) del.run(lane.id, id);
for (const id of added) ins.run(lane.id, id, actor);
})();
const audit = require("../lib/audit");
for (const id of added) audit.recordAccountChange(actor, id, "PUT", `share workspace ${lane.id}`);
for (const id of removed) {
audit.recordAccountChange(actor, id, "PUT", `unshare workspace ${lane.id}`);
}
// The owner and everyone it is shared with now re-read it; the users taken
// off re-read their list (it is gone from it), and their open terminals on
// it close at the next attach re-check (websocket.js).
broadcastLane(lane.id);
if (removed.length) broadcast("lane_access", { laneId: lane.id, userIds: removed });
res.json({ shares: laneShares(lane.id) });
const shares = replaceShares(req, res, {
lane,
table: "lane_shares",
keyCol: "lane_id",
key: lane.id,
what: "workspace",
});
if (shares) res.json({ shares });
});
/** A session of this workspace (`sessions.lane_id`), or null after sending 404. */
function laneSession(req, res, lane) {
const row = require("../db")
.db.prepare("SELECT id FROM sessions WHERE id = ? AND lane_id = ?")
.get(String(req.params.sid), lane.id);
if (!row) res.status(404).json({ error: { code: "ENOSESSION", message: "session not found" } });
return row;
}
// One session shared on its own (sharing phase 3): the users see that session
// and its workspace's Changes, join its pane and resume it (on their own
// account) — nothing else of the workspace (scope.js sessionShareAllows).
router.get("/:id/sessions/:sid/shares", (req, res) => {
const lane = lanesLib.getLane(req.params.id);
if (!lane)
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
const row = laneSession(req, res, lane);
if (!row) return;
if (!require("../lib/auth").isServerMode()) return res.json({ shares: [], canManage: false });
res.json({ shares: sessionShares(row.id), canManage: scope.isLaneOwner(req, lane.id) });
});
router.put("/:id/sessions/:sid/shares", sameOriginGuard, (req, res) => {
const lane = lanesLib.getLane(req.params.id);
if (!lane)
return res.status(404).json({ error: { code: "ENOLANE", message: "workspace not found" } });
const row = laneSession(req, res, lane);
if (!row) return;
const shares = replaceShares(req, res, {
lane,
table: "session_shares",
keyCol: "session_id",
key: row.id,
what: "session",
});
if (shares) res.json({ shares });
});
router.post("/:id/stage", sameOriginGuard, (req, res) => {
@@ -3492,8 +3564,9 @@ router.post("/:id/:action", sameOriginGuard, async (req, res) => {
laneId: current.id,
slot,
cwd: current.cwd,
// A user it is shared with: their pane token acts as them.
startedBy: req.user?.id ?? null,
// A user it is shared with: their pane token acts as them
// (the owner's or an admin's acts as the owner, as before).
startedBy,
}).id;
return {};
});
+11 -2
View File
@@ -89,7 +89,13 @@ router.get("/", (req, res) => {
// Server mode: a member sees only the panes of their own workspaces.
const visible = scope.visibleLaneIds(req);
const items = runs.listRuns();
res.json({ items: visible === null ? items : items.filter((r) => visible.includes(r.laneId)) });
// A workspace one of whose sessions is shared with them: that session's pane only.
res.json({
items:
visible === null
? items
: items.filter((r) => visible.includes(r.laneId) && scope.canSeeRun(req, r.id)),
});
});
/**
@@ -400,8 +406,11 @@ router.get("/history", (req, res) => {
.sort((a, b) => String(b.started_at).localeCompare(String(a.started_at)))
.slice(0, Math.max(1, Math.min(500, Math.floor(opts.limit) || 50)));
const liveIds = new Set(runs.listRuns().map((h) => h.id));
// A session shared on its own: only the runs that held it.
const shown =
scope.memberId(req) == null ? items : items.filter((it) => scope.canSeeRunRow(req, it.id));
res.json({
items: items.map((it) => ({ ...it, isLive: liveIds.has(it.id) })),
items: shown.map((it) => ({ ...it, isLive: liveIds.has(it.id) })),
});
});