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
27 changes: 26 additions & 1 deletion bin/contributor-relay.js
Original file line number Diff line number Diff line change
Expand Up @@ -2304,6 +2304,25 @@ function clampFrame(msg, maxFrameBytes) {
}


// hiveNameSlug turns the display name a hub states on auth_ok into the short
// public form a contributor sees ("hivecommons hive" becomes hivecommons-hive):
// sanitized like any hub text, lowercased, whitespace to dashes, bounded.
// null when the hub stated nothing usable, so callers fall back to a name
// derived from the hostname.
const HIVE_NAME_MAX_LEN = 64;
function hiveNameSlug(raw) {
const clean = sanitizeHubText(raw).toLowerCase().replace(/\s+/g, '-').replace(/-{2,}/g, '-').replace(/^-+|-+$/g, '');
const bounded = Array.from(clean).slice(0, HIVE_NAME_MAX_LEN).join('').replace(/-+$/, '');
return bounded || null;
}

// hiveDisplayName is the name to show a contributor for a hub: the name the
// hive stated on auth_ok, or null before it has authenticated or when it sent
// none (an older hub), in which case the caller keeps its hostname-derived name.
function hiveDisplayName(hub) {
return hub && typeof hub.hiveName === 'string' && hub.hiveName ? hub.hiveName : null;
}

function readyConnLabel(hub) {
return hub ? (hub.connectionId || hub.connectGeneration || 0) : 0;
}
Expand Down Expand Up @@ -8968,7 +8987,11 @@ function handleMessage(data, hub) {
break;

case 'auth_ok':
console.log(`Authenticated with ${hub.url} as ${sanitizeHubText(msg.contributor_id)} (tier: ${sanitizeHubText(msg.trust_tier)})`);
// The hive names itself: its hostname is minted once at claim time and
// never follows a rename, so the name the hub states wins over anything
// parsed from the URL. A hub that sends none leaves it null.
hub.hiveName = hiveNameSlug(msg.hive_name);
console.log(`Authenticated with ${hub.url} as ${sanitizeHubText(msg.contributor_id)} (tier: ${sanitizeHubText(msg.trust_tier)})${hub.hiveName ? ` [hive: ${hub.hiveName}]` : ''}`);
recordHubSeen(hub);
// #2567: the hub advertises its protocol version + capability set here. We
// log them (forward-compatible: unknown/absent fields are simply skipped)
Expand Down Expand Up @@ -10044,6 +10067,8 @@ if (process.env.HIVE_RELAY_TEST_MODE === '1') {
relocateRetiredHiveURL,
normalizeRetiredHiveURL,
hubWsURL,
hiveNameSlug,
hiveDisplayName,
hubPublicURL,
isTLSHostMismatchError,
tlsHostMismatchRemediation,
Expand Down
42 changes: 42 additions & 0 deletions bin/contributor-relay.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15384,6 +15384,48 @@ test('sanitizeHubText strips ANSI/OSC escapes, C1 controls, and bounds length',
} finally { teardown(relay); }
});

test('#19059 hiveNameSlug turns the hive-stated display name into the short public form', () => {
const relay = loadRelay({ backend: 'agy' });
try {
const cases = [
['hivecommons hive', 'hivecommons-hive'],
[' Acme Platform ', 'acme-platform'],
['already-slugged', 'already-slugged'],
['evil\x1b[2Jname', 'evil-[2jname'],
['', null],
[null, null],
[undefined, null],
[42, null],
['---', null],
];
for (const [raw, want] of cases) assert.strictEqual(relay.hiveNameSlug(raw), want, JSON.stringify(raw));
assert.ok(!relay.hiveNameSlug('evil\x1b[2Jname').includes('\x1b'), 'escape sequences never survive');
assert.strictEqual(Array.from(relay.hiveNameSlug('x'.repeat(500))).length, 64);
} finally { teardown(relay); }
});

test('#19059 auth_ok stores the hive-stated name and hiveDisplayName prefers it, null when absent', () => {
const relay = loadRelay({ backend: 'agy' });
const hub = relay.getHubs()[0];
const oldLog = console.log;
const logged = [];
console.log = (...a) => logged.push(a.join(' '));
try {
assert.strictEqual(relay.hiveDisplayName(hub), null, 'nothing before auth_ok');
relay.handleMessage(JSON.stringify({ type: 'auth_ok', contributor_id: 'c-1', trust_tier: 'contributor', hive_name: 'hivecommons hive' }), hub);
assert.strictEqual(relay.hiveDisplayName(hub), 'hivecommons-hive');
assert.ok(logged.some(l => l.includes('Authenticated with') && l.includes('[hive: hivecommons-hive]')), logged.join('\n'));
logged.length = 0;
relay.handleMessage(JSON.stringify({ type: 'auth_ok', contributor_id: 'c-1', trust_tier: 'contributor' }), hub);
assert.strictEqual(relay.hiveDisplayName(hub), null, 'an older hub that sends no name leaves the hostname fallback in charge');
assert.ok(logged.some(l => l.includes('Authenticated with') && !l.includes('[hive:')), logged.join('\n'));
assert.strictEqual(relay.hiveDisplayName(null), null);
} finally {
console.log = oldLog;
teardown(relay);
}
});

test('hub announcement text is sanitized before printing', () => {
const relay = loadRelay({ backend: 'agy' });
const hub = relay.getHubs()[0];
Expand Down
1 change: 1 addition & 0 deletions changelog.d/added-19059-auth-ok-hive-name.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `auth_ok` now carries the hive's display name (`hive_name`), and the relay records it and prints `[hive: <name>]` on connect, so contributors can tell hives apart by their real name instead of a hostname minted before a rename. Additive: a hub that sends nothing keeps today's output ([#19059](https://github.com/hivecommons/hive/issues/19059)).
2 changes: 1 addition & 1 deletion src/docs/contributor-relay.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ With an explicitly configured shared pool, `just contribute-quota status` inspec

## What happens on a task

1. A successful connection logs `Connected to …`, followed by `Authenticated with … as … (tier: …)`. Authentication is not yet a task assignment.
1. A successful connection logs `Connected to …`, followed by `Authenticated with … as … (tier: …)`, plus `[hive: <name>]` when the hive states its display name on `auth_ok` (`hive_name`; the relay shows it lowercased with dashes, so "hivecommons hive" reads `hivecommons-hive`). A hub that sends no name leaves the relay on the short name derived from the hostname. Authentication is not yet a task assignment.
2. The hive assigns an issue that fits your trust tier and its filters. If it says `No task assigned … reason: no_matching_work`, the relay is connected and waiting; it retries. Other reasons may require the hive operator, not another registration.
3. The relay prepares the checkout, injects a short-lived GitHub token, and drives your coding CLI. In interactive mode, use the **attach command printed by your launch** to watch the tmux session. Container mode prints the Docker/Podman form; native mode prints `tmux attach`. Headless backends have no interactive pane.
4. Progress is reported every 2 minutes; completion/PR metadata is reported when the CLI finishes. Check the linked PR and its checks, not just a local “success” line. PRs retain the task's base branch, required hold gates, and DCO sign-off (`git commit -s`).
Expand Down
29 changes: 29 additions & 0 deletions src/pkg/dashboard/contribute_hive_name.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package dashboard

import (
"strings"

"github.com/hivecommons/hive/pkg/fleetreport"
)

// placeholderHiveNamePrefix is the display name the hub gives an unclaimed pool
// slot ("Available slot <id>"). It names inventory, not a project, so it is
// never advertised to a contributor.
const placeholderHiveNamePrefix = "Available slot"

// contributeHiveName is the hive's display name for the auth_ok frame: the
// same project.name the fleet self-report carries (hub provisioning seeds it
// from the hive's project_name), normalized so it is one safe printable line.
// "" when the hive has no name or still carries a pool-slot placeholder name,
// which makes the field vanish from the frame and leaves a relay on its
// hostname-derived short name.
func (s *Server) contributeHiveName() string {
if s == nil || s.deps == nil || s.deps.Config == nil {
return ""
}
name := fleetreport.NormalizeHiveName(s.deps.Config.Project.Name)
if strings.HasPrefix(name, placeholderHiveNamePrefix) {
return ""
}
return name
}
71 changes: 71 additions & 0 deletions src/pkg/dashboard/contribute_hive_name_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package dashboard

import (
"net/http/httptest"
"testing"

"github.com/gorilla/websocket"
)

func TestContributeHiveNameNormalizesAndSuppressesPlaceholder(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{"plain name kept", "hivecommons hive", "hivecommons hive"},
{"whitespace collapsed", " hivecommons \t hive ", "hivecommons hive"},
{"structure characters dropped", "a|b [c]", "ab c"},
{"unnamed hive", "", ""},
{"pool slot placeholder not advertised", "Available slot hosted-available-x", ""},
{"private pool slot placeholder not advertised", "Available slot (private) hosted-available-x", ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s, deps := apiServer(t)
deps.Config.Project.Name = c.in
if got := s.contributeHiveName(); got != c.want {
t.Fatalf("contributeHiveName(%q) = %q, want %q", c.in, got, c.want)
}
})
}
var nilServer *Server
if got := nilServer.contributeHiveName(); got != "" {
t.Fatalf("nil server must advertise no name, got %q", got)
}
}

// The name rides auth_ok: a relay that connects to a named hive is told the
// name, so it need not derive one from a hostname minted before a rename.
func TestAuthOKCarriesHiveName(t *testing.T) {
setupContributeEnv(t)
token := "tok-" + randomHex(8)
if err := saveContributorProfile(&ContributorProfile{
GitHubUsername: "alice",
ContributorID: "c-alice",
RegistrationToken: sha256Hex(token),
TrustTier: "contributor",
}); err != nil {
t.Fatalf("seed: %v", err)
}
s, deps := apiServer(t)
deps.Config.Project.Name = "hivecommons hive"
ts := httptest.NewServer(s.mux)
defer ts.Close()

conn, _, err := websocket.DefaultDialer.Dial(wsURL(ts), nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.Close()
if msg := readMsg(t, conn); msg.Type != "auth_challenge" {
t.Fatalf("challenge = %+v", msg)
}
if err := conn.WriteJSON(WSMessage{Type: "auth_response", RegistrationToken: token, CLIBackend: "claude", Model: "sonnet"}); err != nil {
t.Fatalf("auth write: %v", err)
}
auth := readMsg(t, conn)
if auth.Type != "auth_ok" || auth.HiveName != "hivecommons hive" {
t.Fatalf("auth_ok must carry the hive display name, got %+v", auth)
}
}
11 changes: 9 additions & 2 deletions src/pkg/dashboard/contribute_ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -639,8 +639,14 @@ type WSMessage struct {
// with it. Additive; a relay that ignores it keeps whatever default it ships.
MaxMessageBytes int `json:"max_message_bytes,omitempty"`
Announcement *config.ContributeAnnouncement `json:"announcement,omitempty"`
HelpLinks []config.ContributeHelpLink `json:"help_links,omitempty"`
Role string `json:"role,omitempty"`
// HiveName is the hive's display name, stated on auth_ok so a relay can
// name the hive to its contributor without parsing the hostname, which is
// minted once at claim time and never follows a rename. Additive and
// omitted when the hive has no name; a relay that ignores it keeps its
// hostname-derived short name.
HiveName string `json:"hive_name,omitempty"`
HelpLinks []config.ContributeHelpLink `json:"help_links,omitempty"`
Role string `json:"role,omitempty"`
// WorkbenchVersion and Incarnation are optional on auth_response for an
// external-execution workbench peer; ext_* frames below are routed to the
// attached peer after auth_ok.
Expand Down Expand Up @@ -3009,6 +3015,7 @@ func (s *wsSession) handleAuthResponse(msg WSMessage) (stop bool) {
Announcement: announcement,
ContributeNeedsDecisionLabel: &needsDecisionLabel,
HelpLinks: h.server.contributeHelpLinks(),
HiveName: h.server.contributeHiveName(),
AuditShareRequested: h.server.contributeAuditShareRequest(),
}); err != nil {
h.logger.Warn("[contribute-ws] failed to send auth_ok", "username", profile.GitHubUsername, "error", err)
Expand Down
Loading