Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-inbox-to-spek-session.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Inbox: **🔗 Share ▾ → Hive → spek…** sends one recording, or a selection, into a new or running Inception (spek) session. The hive writes each item to `.hive/inbox/<source>-<id>.md` in the session's workspace (as the session's user, mode 0640, inside the untrusted-data envelope with provenance outside it), queues a fixed Send that asks the CLI to start a spec from those files with the spek-new skill (it names only the files, never the recording's text), opens the session's tab and marks the item `routed: session/<id>`. An audio-only item is transcribed first and goes into the session when its transcript is ready. API: `POST /api/sessions/{id}/seed` and `seed_items` on `POST /api/sessions`, audited as `inbox_to_session`. An item that already has a machine transcript no longer also shows the source's "not transcribed yet" line.
72 changes: 70 additions & 2 deletions dashboard/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -40312,7 +40312,7 @@
"Sessions"
],
"summary": "Create a session (owner or read-write)",
"description": "Starts a named CLI session in the hive's shared workspace checkout (spektacular init run for the vendor). Vendor must be a known, allowed, installed backend; never a shell, never a bypass-permissions launch. ASYNCHRONOUS: answers at once with the session in status `preparing` (and a human `message`, e.g. the first session on a hive clones the project repository, which takes minutes); the start runs in the background. Poll GET /api/sessions until the session is `running` or `failed` (then `error` carries the reason and DELETE removes it).",
"description": "Starts a named CLI session in the hive's shared workspace checkout (spektacular init run for the vendor). Vendor must be a known, allowed, installed backend; never a shell, never a bypass-permissions launch. ASYNCHRONOUS: answers at once with the session in status `preparing` (and a human `message`, e.g. the first session on a hive clones the project repository, which takes minutes); the start runs in the background. Poll GET /api/sessions until the session is `running` or `failed` (then `error` carries the reason and DELETE removes it). Optional `seed_items` [{source,id}] sends Inbox items into the new session once it is running, exactly like POST /api/sessions/{id}/seed; they are read and checked first, so an item without text answers 409 (reason no_text) and creates nothing, and the 202 carries `seed` {items, files, status:\"pending\"}.",
"responses": {
"202": {
"description": "Accepted; the session is preparing"
Expand All @@ -40327,7 +40327,7 @@
"description": "Sessions disabled"
},
"409": {
"description": "Vendor not installed"
"description": "Vendor not installed, or a seed item has no text yet"
},
"429": {
"description": "Session limit reached"
Expand Down Expand Up @@ -40655,6 +40655,74 @@
]
}
},
"/api/sessions/{id}/seed": {
"post": {
"tags": [
"Sessions"
],
"summary": "Send Inbox items into a running session (owner or read-write who may use it)",
"description": "Body {items:[{source,id}]} (at most 20). The hive reads each item's current content and writes one markdown file per item to <cwd>/.hive/inbox/<source>-<id>.md in the session's workspace, as the session's uid with the sessions group and mode 0640: hive-generated provenance, then title, summary, transcript (or machine transcript) and highlights inside an untrusted-inbox-data envelope. It then queues a fixed Send through the queued-Send path (delivered when the prompt is idle, audited as session_input for the caller) that names only the sanitised file paths, never item text. Audited as inbox_to_session; each item gets a `session` route (`routed: session/<id>`). An audio-only item the hive can transcribe is transcribed first (a `spek` share intent) and seeds the session when its transcript is ready; such items are listed in `seed.waiting`. Answers 202 with `session` and `seed` ({files, instruction, queue_id, position, waiting}).",
"responses": {
"202": {
"description": "Files written and the instruction queued"
},
"400": {
"description": "No items, too many items or a malformed body"
},
"403": {
"description": "Read role, or a private session of someone else"
},
"404": {
"description": "Unknown session or item, or no Inbox on this hive"
},
"409": {
"description": "Session not running, or an item has no text yet: body {reason:\"no_text\", item, transcribe} (transcribe=true when 🎧 Transcribe can produce a machine transcript)"
},
"412": {
"description": "An audio-only item cannot be transcribed now (transcription disabled, no consent, budget used or no provider)"
},
"429": {
"description": "The session's Send queue is full"
}
},
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"source": {
"type": "string"
},
"id": {
"type": "string"
}
}
}
}
}
}
}
}
},
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
]
}
},
"/api/sessions/{id}/resume": {
"post": {
"tags": [
Expand Down
111 changes: 111 additions & 0 deletions src/crux/agent/usersession_inbox.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package agent

import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"path/filepath"
"strings"

"github.com/hivecommons/hive/crux"
)

// Inbox seed files (POST /api/sessions/{id}/seed). The dashboard sends Inbox
// items into a session as markdown files under <cwd>/.hive/inbox, where cwd is
// the session's shared workspace checkout (or its own work dir when it has
// none). Like an upload, the file is written AS THE SESSION'S UID through the
// su-exec helper, never as the hive's uid into a directory the session
// controls: a symlink planted by any session uid only reaches what that uid
// can already reach, and the script refuses one at .hive or .hive/inbox.
const (
// userSessionInboxDir is the seed directory relative to the session cwd.
userSessionInboxDir = ".hive/inbox"
// userSessionInboxSymlinkExit is the script's exit status for a symlink
// at .hive or .hive/inbox, or a directory or symlink at the target name.
userSessionInboxSymlinkExit = 76
userSessionInboxSymlinkExitText = "76"
)

// userSessionInboxScript (run as the session uid:sessions gid): $1 the
// session cwd, $2 the file name; the content arrives on stdin. Directories are
// created group-writable (umask 007) so every session of a shared workspace
// can add its own files; a `.gitignore` of "*" keeps the transcripts out of
// commits. The file is created exclusively (noclobber, which refuses a
// symlink) under umask 027, so it is 0640 from birth with the group the
// directory hands down (the sessions group in the setgid workspace), then
// renamed over any earlier copy. Nothing is chmod-ed or chgrp-ed by path
// afterwards: in a group-writable directory a peer session could swap the
// name for a symlink between the write and such a call. A symlink at .hive or
// .hive/inbox, or a directory at the target name, is refused.
const userSessionInboxScript = `set -e
ws=$1; name=$2
d="$ws/` + userSessionInboxDir + `"
umask 007
for p in "$ws/.hive" "$d"; do
if [ -L "$p" ]; then exit ` + userSessionInboxSymlinkExitText + `; fi
done
mkdir -p -- "$d"
for p in "$ws/.hive" "$d"; do
if [ -L "$p" ]; then exit ` + userSessionInboxSymlinkExitText + `; fi
done
set -C
if [ ! -e "$d/.gitignore" ] && [ ! -L "$d/.gitignore" ]; then printf '*\n' > "$d/.gitignore" 2>/dev/null || true; fi
umask 027
t="$d/.$name.$$.tmp"
cat > "$t"
if [ -d "$d/$name" ] || [ -L "$d/$name" ]; then rm -f -- "$t"; exit ` + userSessionInboxSymlinkExitText + `; fi
mv -f -- "$t" "$d/$name"`

// userSessionInboxCwd validates the working directory a seed is written
// under: "" is the session's own work dir; anything else must be exactly a
// workspace checkout path (<workspace root>/<org>/<repo>).
func userSessionInboxCwd(id, workspace string) (string, error) {
if strings.TrimSpace(workspace) == "" {
return userSessionWorkDir(id), nil
}
clean := filepath.Clean(workspace)
rel, err := filepath.Rel(userSessionWorkspaceRoot(), clean)
if err != nil {
return "", fmt.Errorf("workspace %q is not a session workspace", workspace)
}
org, name, ok := strings.Cut(filepath.ToSlash(rel), "/")
if !ok || !userSessionRepoPartPattern.MatchString(org) || !userSessionRepoPartPattern.MatchString(name) || clean != userSessionWorkspaceDir(org, name) {
return "", fmt.Errorf("workspace %q is not a session workspace", workspace)
}
return clean, nil
}

// StoreInboxFile writes data as <cwd>/.hive/inbox/<fileName>, as the session
// uid, owned by that uid with mode 0640 and the directory's group (the
// sessions group in the shared workspace), and returns
// its absolute path. workspace is the session's workspace checkout ("" for a
// session without one). fileName must be a plain name.
func (r *UserSessionRuntime) StoreInboxFile(id, workspace, fileName string, data []byte) (string, error) {
if err := checkUserSessionID(id); err != nil {
return "", err
}
if len(fileName) > userSessionUploadNameMax || !userSessionUploadNamePattern.MatchString(fileName) {
return "", fmt.Errorf("invalid inbox file name")
}
cwd, err := userSessionInboxCwd(id, workspace)
if err != nil {
return "", err
}
uid, err := r.sessionUID(id)
if err != nil {
return "", err
}
ctx, cancel := context.WithTimeout(context.Background(), userSessionUploadTimeout)
defer cancel()
out, err := r.priv(ctx, userSessionSpec(uid), bytes.NewReader(data), "sh", "-c", userSessionInboxScript, "sh", cwd, fileName)
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) && ee.ExitCode() == userSessionInboxSymlinkExit {
return "", crux.ErrUserSessionInboxSymlink
}
return "", outputErr("storing inbox file", err, out)
}
return filepath.Join(cwd, userSessionInboxDir, fileName), nil
}
158 changes: 158 additions & 0 deletions src/crux/agent/usersession_inbox_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package agent

import (
"errors"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"testing"

"github.com/hivecommons/hive/crux"
)

const testInboxFileName = "plaud-rec1.md"

// inboxScriptHandler simulates userSessionInboxScript on the temp tree.
func inboxScriptHandler(c fakePrivCall) (bool, []byte, error) {
if len(c.argv) < 6 || c.argv[0] != "sh" || c.argv[2] != userSessionInboxScript {
return false, nil, nil
}
d := filepath.Join(c.argv[4], userSessionInboxDir)
if err := os.MkdirAll(d, 0o770); err != nil {
return true, nil, err
}
return true, nil, os.WriteFile(filepath.Join(d, c.argv[5]), []byte(c.stdin), 0o640)
}

func TestUserSessionStoreInboxFileRunsAsSessionUIDInWorkDir(t *testing.T) {
r, _, p := startedRuntime(t)
p.calls = nil
p.handler = inboxScriptHandler
path, err := r.StoreInboxFile(testSessionID, "", testInboxFileName, []byte("hello"))
if err != nil {
t.Fatal(err)
}
want := filepath.Join(userSessionWorkDir(testSessionID), ".hive", "inbox", testInboxFileName)
if path != want {
t.Errorf("path = %q, want %q", path, want)
}
if len(p.calls) != 1 || p.calls[0].user != testSessionSpecUser {
t.Fatalf("the seed file must be written by the session uid:sessions gid only, never root or the hive: %+v", p.calls)
}
if strings.Contains(userSessionInboxScript, "chmod") || strings.Contains(userSessionInboxScript, "chgrp") || !strings.Contains(userSessionInboxScript, "umask 027") || !strings.Contains(userSessionInboxScript, "set -C") {
t.Error("the seed file must get its mode at an exclusive create, never from a path-based chmod/chgrp a peer could redirect")
}
if b, _ := os.ReadFile(path); string(b) != "hello" {
t.Errorf("content = %q", b)
}
}

func TestUserSessionStoreInboxFileWorkspaceAndValidation(t *testing.T) {
r, _, p := startedRuntime(t)
p.handler = inboxScriptHandler
ws := userSessionWorkspaceDir("hivecommons", "hive")
path, err := r.StoreInboxFile(testSessionID, ws, testInboxFileName, []byte("x"))
if err != nil || path != filepath.Join(ws, ".hive", "inbox", testInboxFileName) {
t.Fatalf("workspace seed = %q, %v", path, err)
}
for _, bad := range []string{"/etc", filepath.Join(userSessionWorkspaceRoot(), "only-org"), filepath.Join(ws, "sub"), filepath.Join(userSessionWorkspaceRoot(), "..", "x", "y")} {
if _, err := r.StoreInboxFile(testSessionID, bad, testInboxFileName, []byte("x")); err == nil {
t.Errorf("workspace %q accepted", bad)
}
}
for _, name := range []string{"../x.md", ".hidden", "a/b.md", "", "-rf", strings.Repeat("a", userSessionUploadNameMax+1)} {
if _, err := r.StoreInboxFile(testSessionID, "", name, []byte("x")); err == nil {
t.Errorf("file name %q accepted", name)
}
}
if _, err := r.StoreInboxFile("../etc", "", testInboxFileName, []byte("x")); err == nil {
t.Error("bad session id accepted")
}
}

func TestUserSessionStoreInboxFileSymlinkRefused(t *testing.T) {
r, _, p := startedRuntime(t)
p.handler = func(c fakePrivCall) (bool, []byte, error) {
if len(c.argv) >= 3 && c.argv[2] == userSessionInboxScript {
return true, nil, exitStatusError(userSessionInboxSymlinkExit)
}
return false, nil, nil
}
if _, err := r.StoreInboxFile(testSessionID, "", testInboxFileName, []byte("x")); !errors.Is(err, crux.ErrUserSessionInboxSymlink) {
t.Errorf("symlinked inbox dir: %v", err)
}
}

// TestUserSessionInboxScriptOnRealShell runs the fixed script itself (no
// su-exec: as the test's own uid and group) and asserts what it leaves
// behind: mode 0640, the process group, a .gitignore, a replaced re-send, and a
// refusal at a symlinked .hive.
func TestUserSessionInboxScriptOnRealShell(t *testing.T) {
if _, err := exec.LookPath("sh"); err != nil {
t.Skip("no sh")
}
ws := t.TempDir()
gid := strconv.Itoa(os.Getgid())
run := func(dir, content string) error {
cmd := exec.Command("sh", "-c", userSessionInboxScript, "sh", dir, testInboxFileName)
cmd.Stdin = strings.NewReader(content)
out, err := cmd.CombinedOutput()
if err != nil {
return errors.New(err.Error() + ": " + string(out))
}
return nil
}
if err := run(ws, "first"); err != nil {
t.Fatal(err)
}
if err := run(ws, "second"); err != nil {
t.Fatalf("re-send must replace the file: %v", err)
}
path := filepath.Join(ws, ".hive", "inbox", testInboxFileName)
fi, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if fi.Mode().Perm() != 0o640 {
t.Errorf("mode = %o, want 640", fi.Mode().Perm())
}
if st, ok := fi.Sys().(*syscall.Stat_t); ok && strconv.Itoa(int(st.Gid)) != gid {
t.Errorf("group = %d, want %s", st.Gid, gid)
}
if b, _ := os.ReadFile(path); string(b) != "second" {
t.Errorf("content = %q", b)
}
if b, _ := os.ReadFile(filepath.Join(ws, ".hive", "inbox", ".gitignore")); string(b) != "*\n" {
t.Errorf(".gitignore = %q", b)
}
if ents, _ := os.ReadDir(filepath.Join(ws, ".hive", "inbox")); len(ents) != 2 {
t.Errorf("left temp files behind: %v", ents)
}

evil := t.TempDir()
target := t.TempDir()
if err := os.Symlink(target, filepath.Join(evil, ".hive")); err != nil {
t.Fatal(err)
}
if err := run(evil, "x"); err == nil || !strings.Contains(err.Error(), "exit status "+userSessionInboxSymlinkExitText) {
t.Errorf("symlinked .hive must be refused with %d: %v", userSessionInboxSymlinkExit, err)
}
if ents, _ := os.ReadDir(target); len(ents) != 0 {
t.Errorf("wrote through the symlink: %v", ents)
}

// A directory planted at the target name is refused, not written into.
planted := t.TempDir()
if err := os.MkdirAll(filepath.Join(planted, ".hive", "inbox", testInboxFileName), 0o755); err != nil {
t.Fatal(err)
}
if err := run(planted, "x"); err == nil || !strings.Contains(err.Error(), "exit status "+userSessionInboxSymlinkExitText) {
t.Errorf("a directory at the target must be refused: %v", err)
}
if ents, _ := os.ReadDir(filepath.Join(planted, ".hive", "inbox", testInboxFileName)); len(ents) != 0 {
t.Errorf("wrote into the planted directory: %v", ents)
}
}
4 changes: 4 additions & 0 deletions src/crux/usersession_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,8 @@ var (
// ErrUserSessionUploadLimit is returned by StoreUpload when the session
// already holds the maximum number of uploaded files.
ErrUserSessionUploadLimit = errors.New("too many uploaded files")
// ErrUserSessionInboxSymlink is returned by StoreInboxFile when .hive or
// .hive/inbox in the session's working directory is a symlink; nothing is
// written.
ErrUserSessionInboxSymlink = errors.New("refusing to write through a symlinked .hive/inbox directory")
)
6 changes: 3 additions & 3 deletions src/docs/api-reference/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f
| `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` |
| `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` |
| `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` |
| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1772` |
| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1773` |
| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1774` |
| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1776` |
| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1777` |
| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1778` |
| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:551` |
| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:552` |
| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:553` |
Expand Down
Loading
Loading