mirror of
https://github.com/whyour/qinglong.git
synced 2026-09-20 16:07:11 +08:00
feat(ql3): add read-only cluster copilot console
This commit is contained in:
@@ -1,10 +1,25 @@
|
||||
# `@qinglong/cluster-admin`
|
||||
|
||||
This private QingLong 3.0 package owns explicit cluster operations and the
|
||||
bounded Cluster Copilot MCP product surface. Database/Kubernetes administration
|
||||
remains short-lived and requires distinct purpose-bound authority; the MCP
|
||||
subpath has only the remote API client, opens no database or Kubernetes
|
||||
authority, and is intentionally separate from resident `cluster-control`.
|
||||
bounded Cluster Copilot MCP and Console product surfaces.
|
||||
Database/Kubernetes administration remains short-lived and requires distinct
|
||||
purpose-bound authority. The MCP subpath has only the remote API client; the
|
||||
Console is a loopback-only read BFF serving digest-bound static assets. Neither
|
||||
opens database or Kubernetes authority, enters the legacy 2.x Web application,
|
||||
or resides in `cluster-control`.
|
||||
|
||||
The Console accepts only `inspect` and explicit `output` reads. Its Cluster
|
||||
API credential stays in a canonical owner-private file and is reread for each
|
||||
upstream request; browser JavaScript receives only a separate session token
|
||||
which cannot call Cluster APIs. It binds `127.0.0.1`, enforces exact
|
||||
Host/Origin, no-store responses and a closed CSP, renders model text only via
|
||||
`textContent`, and keeps diagnose/cancel, polling, cache, WebSocket,
|
||||
ServiceWorker and legacy session authority absent.
|
||||
|
||||
The reviewed operator-workstation setup, private-file ceremony, preflight and
|
||||
session lifecycle are documented in
|
||||
`deploy/console/ql3-cluster-copilot/README.md`. Do not expose the Console
|
||||
through a container port mapping, Kubernetes workload or shared network.
|
||||
|
||||
The admin role can append Identity/API Credential mutations and their security
|
||||
audit in one serializable transaction, and can perform bounded read-only audit
|
||||
|
||||
@@ -0,0 +1,588 @@
|
||||
:root {
|
||||
--paper: #f3f6f1;
|
||||
--paper-deep: #e7ede6;
|
||||
--ink: #17231d;
|
||||
--muted: #607067;
|
||||
--line: #cbd5cc;
|
||||
--moss: #2f654d;
|
||||
--moss-soft: #dce9df;
|
||||
--amber: #c98724;
|
||||
--plum: #69556d;
|
||||
--rust: #a84f38;
|
||||
--white: #fbfdf9;
|
||||
--shadow: 0 24px 70px rgba(31, 52, 40, 0.12);
|
||||
font-family:
|
||||
"Avenir Next", "Segoe UI Variable", "Segoe UI", "PingFang SC",
|
||||
"Hiragino Sans GB", sans-serif;
|
||||
color: var(--ink);
|
||||
background: var(--paper);
|
||||
font-synthesis: none;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html {
|
||||
min-width: 320px;
|
||||
background:
|
||||
linear-gradient(90deg, rgba(47, 101, 77, 0.035) 1px, transparent 1px)
|
||||
0 0 / 24px 24px,
|
||||
var(--paper);
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button {
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 3px;
|
||||
padding: 0.78rem 1rem;
|
||||
color: var(--ink);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
transform 140ms ease,
|
||||
background-color 140ms ease,
|
||||
color 140ms ease;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
background: var(--ink);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.42;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
background: var(--moss);
|
||||
border-color: var(--moss);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
button:focus-visible,
|
||||
input:focus-visible,
|
||||
pre:focus-visible {
|
||||
outline: 3px solid color-mix(in srgb, var(--amber) 72%, white);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-bottom: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
padding: 0.72rem 0;
|
||||
color: var(--ink);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
color: #91a097;
|
||||
}
|
||||
|
||||
.skip-link {
|
||||
position: fixed;
|
||||
left: 1rem;
|
||||
top: 1rem;
|
||||
z-index: 20;
|
||||
transform: translateY(-180%);
|
||||
padding: 0.7rem 1rem;
|
||||
background: var(--ink);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.skip-link:focus {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.shell {
|
||||
width: min(1440px, 100%);
|
||||
margin: 0 auto;
|
||||
min-height: 100vh;
|
||||
padding: 2rem clamp(1rem, 3vw, 3.5rem) 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.masthead {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 2rem;
|
||||
padding-bottom: 1.6rem;
|
||||
border-bottom: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.brand-lockup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1.2rem;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 3.15rem;
|
||||
height: 3.15rem;
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 50%;
|
||||
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.09em;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 0.42rem;
|
||||
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
font-size: 0.69rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
p {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin-bottom: 0;
|
||||
max-width: 18ch;
|
||||
font-size: clamp(1.55rem, 3vw, 3rem);
|
||||
line-height: 0.98;
|
||||
letter-spacing: -0.055em;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin-bottom: 0.7rem;
|
||||
font-size: clamp(1.45rem, 2vw, 2.15rem);
|
||||
letter-spacing: -0.035em;
|
||||
}
|
||||
|
||||
h3 {
|
||||
letter-spacing: -0.025em;
|
||||
}
|
||||
|
||||
.boundary {
|
||||
min-width: 11rem;
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0.22rem 0.52rem;
|
||||
align-items: center;
|
||||
font-size: 0.76rem;
|
||||
}
|
||||
|
||||
.boundary strong {
|
||||
grid-column: 2;
|
||||
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
font-weight: 500;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.boundary-dot {
|
||||
width: 0.65rem;
|
||||
height: 0.65rem;
|
||||
border-radius: 50%;
|
||||
background: var(--moss);
|
||||
box-shadow: 0 0 0 5px var(--moss-soft);
|
||||
}
|
||||
|
||||
.workspace {
|
||||
flex: 1;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(18rem, 0.82fr) minmax(28rem, 1.4fr);
|
||||
min-height: 680px;
|
||||
border-bottom: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.control-deck,
|
||||
.evidence-panel {
|
||||
padding: clamp(1.5rem, 3vw, 3.25rem);
|
||||
}
|
||||
|
||||
.control-deck {
|
||||
border-right: 1px solid var(--ink);
|
||||
background: rgba(251, 253, 249, 0.72);
|
||||
}
|
||||
|
||||
.section-heading > p:last-child {
|
||||
max-width: 44ch;
|
||||
line-height: 1.7;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.session-gate {
|
||||
margin: 2.5rem 0 2rem;
|
||||
padding: 1.1rem;
|
||||
border-left: 3px solid var(--plum);
|
||||
background: color-mix(in srgb, var(--plum) 8%, var(--white));
|
||||
}
|
||||
|
||||
.inline-control {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.field-note {
|
||||
margin: 0.75rem 0 0;
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.55;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.target-form {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.target-form label,
|
||||
.session-gate label {
|
||||
margin-top: 0.9rem;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 750;
|
||||
letter-spacing: 0.025em;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.65rem;
|
||||
margin-top: 1.7rem;
|
||||
}
|
||||
|
||||
.trust-note {
|
||||
margin-top: 2.4rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.trust-note span {
|
||||
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
font-size: 0.68rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
color: var(--plum);
|
||||
}
|
||||
|
||||
.trust-note p {
|
||||
margin: 0.45rem 0 0;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.55;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.evidence-panel {
|
||||
position: relative;
|
||||
background: var(--paper-deep);
|
||||
}
|
||||
|
||||
.evidence-header,
|
||||
.output-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.status-chip {
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 999px;
|
||||
padding: 0.35rem 0.64rem;
|
||||
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.status-chip[data-tone="running"] {
|
||||
color: var(--amber);
|
||||
}
|
||||
|
||||
.status-chip[data-tone="success"] {
|
||||
color: var(--moss);
|
||||
}
|
||||
|
||||
.status-chip[data-tone="failed"] {
|
||||
color: var(--rust);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
min-height: 450px;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
justify-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
max-width: 38ch;
|
||||
line-height: 1.65;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.empty-glyph {
|
||||
width: 12rem;
|
||||
height: 7rem;
|
||||
margin-bottom: 2rem;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
gap: 1.3rem;
|
||||
border-bottom: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.empty-glyph span {
|
||||
width: 1px;
|
||||
background: var(--ink);
|
||||
transform-origin: bottom;
|
||||
animation: signal 2.4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.empty-glyph span:nth-child(1) {
|
||||
height: 35%;
|
||||
}
|
||||
|
||||
.empty-glyph span:nth-child(2) {
|
||||
height: 82%;
|
||||
animation-delay: 180ms;
|
||||
}
|
||||
|
||||
.empty-glyph span:nth-child(3) {
|
||||
height: 54%;
|
||||
animation-delay: 360ms;
|
||||
}
|
||||
|
||||
@keyframes signal {
|
||||
0%,
|
||||
100% {
|
||||
transform: scaleY(0.55);
|
||||
opacity: 0.42;
|
||||
}
|
||||
45% {
|
||||
transform: scaleY(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.trace-rail {
|
||||
list-style: none;
|
||||
margin: 2.2rem 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
|
||||
.trace-rail li {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0.75rem;
|
||||
min-height: 5rem;
|
||||
}
|
||||
|
||||
.trace-rail li:not(:last-child)::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0.42rem;
|
||||
left: 0.45rem;
|
||||
right: -0.45rem;
|
||||
height: 1px;
|
||||
background: var(--moss);
|
||||
}
|
||||
|
||||
.trace-node {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
width: 0.9rem;
|
||||
height: 0.9rem;
|
||||
border: 3px solid var(--paper-deep);
|
||||
border-radius: 50%;
|
||||
background: var(--moss);
|
||||
box-shadow: 0 0 0 1px var(--moss);
|
||||
}
|
||||
|
||||
.trace-rail small,
|
||||
.fact-grid dt,
|
||||
.output-meta dt {
|
||||
display: block;
|
||||
margin-bottom: 0.42rem;
|
||||
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
font-size: 0.65rem;
|
||||
letter-spacing: 0.11em;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.trace-rail strong {
|
||||
font-size: 0.9rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.fact-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
margin: 0;
|
||||
border-top: 1px solid var(--ink);
|
||||
border-left: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.fact-grid div {
|
||||
min-height: 6.4rem;
|
||||
padding: 1rem;
|
||||
border-right: 1px solid var(--ink);
|
||||
border-bottom: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.fact-grid dd,
|
||||
.output-meta dd {
|
||||
margin: 0;
|
||||
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
font-size: 0.82rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.output-panel {
|
||||
margin-top: 2rem;
|
||||
padding: 1.2rem;
|
||||
border: 1px solid var(--plum);
|
||||
background: var(--white);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.output-heading span {
|
||||
border: 1px solid var(--plum);
|
||||
padding: 0.3rem 0.55rem;
|
||||
font-size: 0.66rem;
|
||||
color: var(--plum);
|
||||
}
|
||||
|
||||
.output-panel pre {
|
||||
max-height: 28rem;
|
||||
overflow: auto;
|
||||
margin: 1rem 0;
|
||||
padding: 1rem;
|
||||
border-left: 3px solid var(--plum);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font: 0.82rem/1.7 ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
background: #f1eef2;
|
||||
}
|
||||
|
||||
.output-meta {
|
||||
display: grid;
|
||||
grid-template-columns: 0.7fr 0.7fr 1.6fr;
|
||||
gap: 1rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.message {
|
||||
min-height: 1.4rem;
|
||||
margin-top: 1.2rem;
|
||||
font-size: 0.82rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.message[data-tone="error"] {
|
||||
color: var(--rust);
|
||||
}
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding-top: 1rem;
|
||||
font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
|
||||
font-size: 0.65rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.masthead,
|
||||
footer {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.workspace {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.control-deck {
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.trace-rail {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.trace-rail li {
|
||||
min-height: 3rem;
|
||||
}
|
||||
|
||||
.trace-rail li:not(:last-child)::after {
|
||||
left: 0.42rem;
|
||||
right: auto;
|
||||
top: 0.8rem;
|
||||
bottom: -1.45rem;
|
||||
width: 1px;
|
||||
height: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.shell {
|
||||
padding-inline: 0.75rem;
|
||||
}
|
||||
|
||||
.brand-lockup {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
flex: 0 0 auto;
|
||||
width: 2.7rem;
|
||||
height: 2.7rem;
|
||||
}
|
||||
|
||||
.control-deck,
|
||||
.evidence-panel {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.inline-control,
|
||||
.actions,
|
||||
.fact-grid,
|
||||
.output-meta {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
scroll-behavior: auto !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
"use strict";
|
||||
|
||||
(function () {
|
||||
const commandSchema = "qinglong/cluster-copilot-console-read-request@v1";
|
||||
const sessionForm = document.getElementById("session-form");
|
||||
const sessionInput = document.getElementById("session-token");
|
||||
const targetForm = document.getElementById("target-form");
|
||||
const inspectButton = document.getElementById("inspect-button");
|
||||
const outputButton = document.getElementById("output-button");
|
||||
const emptyState = document.getElementById("empty-state");
|
||||
const resultView = document.getElementById("result-view");
|
||||
const outputPanel = document.getElementById("output-panel");
|
||||
const outputText = document.getElementById("output-text");
|
||||
const message = document.getElementById("message");
|
||||
const statusChip = document.getElementById("status-chip");
|
||||
let sessionToken = "";
|
||||
let currentTarget = null;
|
||||
|
||||
const setText = function (id, value) {
|
||||
document.getElementById(id).textContent =
|
||||
value === null || value === undefined || value === "" ? "—" : String(value);
|
||||
};
|
||||
|
||||
const setMessage = function (value, tone) {
|
||||
message.textContent = value;
|
||||
message.dataset.tone = tone || "neutral";
|
||||
};
|
||||
|
||||
const dateTime = function (value) {
|
||||
if (!Number.isSafeInteger(value)) return "—";
|
||||
return new Intl.DateTimeFormat("zh-CN", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "medium",
|
||||
}).format(new Date(value));
|
||||
};
|
||||
|
||||
const setBusy = function (busy) {
|
||||
inspectButton.disabled = busy;
|
||||
outputButton.disabled =
|
||||
busy || !currentTarget || currentTarget.outputAvailable !== true;
|
||||
};
|
||||
|
||||
const request = async function (operation, target) {
|
||||
const response = await fetch("/api/v1/copilot/" + operation, {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
credentials: "omit",
|
||||
redirect: "error",
|
||||
referrerPolicy: "no-referrer",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
Authorization: "QL3-Console " + sessionToken,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
schema: commandSchema,
|
||||
operation: operation,
|
||||
projectId: target.projectId,
|
||||
sourceRunId: target.sourceRunId,
|
||||
requestId: target.requestId,
|
||||
}),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) {
|
||||
const error = new Error(
|
||||
typeof body.code === "string" ? body.code : "console_request_failed",
|
||||
);
|
||||
error.code = typeof body.code === "string" ? body.code : "console_request_failed";
|
||||
throw error;
|
||||
}
|
||||
return body;
|
||||
};
|
||||
|
||||
const targetFromForm = function () {
|
||||
const form = new FormData(targetForm);
|
||||
return {
|
||||
projectId: String(form.get("projectId") || "").trim(),
|
||||
sourceRunId: String(form.get("sourceRunId") || "").trim(),
|
||||
requestId: String(form.get("requestId") || "").trim(),
|
||||
};
|
||||
};
|
||||
|
||||
const renderInspection = function (response) {
|
||||
const result = response.result;
|
||||
const fact = result.result;
|
||||
currentTarget = {
|
||||
projectId: fact.projectId,
|
||||
sourceRunId: fact.sourceRunId,
|
||||
requestId: fact.requestId,
|
||||
outputAvailable: fact.outputAvailable,
|
||||
};
|
||||
emptyState.hidden = true;
|
||||
resultView.hidden = false;
|
||||
outputPanel.hidden = true;
|
||||
outputText.textContent = "";
|
||||
setText("admitted-at", dateTime(fact.admittedAtMs));
|
||||
setText("stage", fact.stage || (fact.status === "running" ? "processing" : null));
|
||||
setText("outcome", fact.outcome || fact.status);
|
||||
setText("diagnosis-run", fact.diagnosisRunId);
|
||||
setText("reason", fact.reason);
|
||||
setText(
|
||||
"tokens",
|
||||
fact.usage === null ? null : fact.usage.totalTokens,
|
||||
);
|
||||
setText(
|
||||
"cost",
|
||||
fact.usage === null || fact.usage.costMicros === null
|
||||
? null
|
||||
: "$" + (fact.usage.costMicros / 1000000).toFixed(6),
|
||||
);
|
||||
statusChip.textContent = fact.status === "running" ? "诊断进行中" : fact.outcome;
|
||||
statusChip.dataset.tone =
|
||||
fact.status === "running"
|
||||
? "running"
|
||||
: fact.outcome === "succeeded"
|
||||
? "success"
|
||||
: "failed";
|
||||
outputButton.disabled = fact.outputAvailable !== true;
|
||||
setMessage(
|
||||
fact.outputAvailable
|
||||
? "状态已验证。诊断内容仍未读取。"
|
||||
: "状态已验证;当前没有可读取的诊断内容。",
|
||||
);
|
||||
};
|
||||
|
||||
const renderOutput = function (response) {
|
||||
const fact = response.result.result;
|
||||
outputPanel.hidden = false;
|
||||
outputText.textContent = fact.result.text;
|
||||
setText("finish-reason", fact.result.finishReason);
|
||||
setText("output-bytes", fact.reference.outputBytes);
|
||||
setText("content-digest", fact.reference.contentDigest);
|
||||
setMessage("诊断内容已显式读取;请把它当作不可信建议进行复核。");
|
||||
outputPanel.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||||
};
|
||||
|
||||
sessionForm.addEventListener("submit", function (event) {
|
||||
event.preventDefault();
|
||||
const candidate = sessionInput.value.trim();
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(candidate)) {
|
||||
setMessage("浏览器访问密钥格式无效。", "error");
|
||||
return;
|
||||
}
|
||||
sessionToken = candidate;
|
||||
sessionInput.value = "";
|
||||
sessionForm.hidden = true;
|
||||
targetForm.hidden = false;
|
||||
setMessage("本次页面已解锁。访问密钥只保留在内存中。");
|
||||
document.getElementById("project-id").focus();
|
||||
});
|
||||
|
||||
targetForm.addEventListener("submit", async function (event) {
|
||||
event.preventDefault();
|
||||
const target = targetFromForm();
|
||||
setBusy(true);
|
||||
setMessage("正在读取 durable status…");
|
||||
try {
|
||||
const response = await request("inspect", target);
|
||||
renderInspection(response);
|
||||
} catch (error) {
|
||||
currentTarget = null;
|
||||
outputPanel.hidden = true;
|
||||
statusChip.textContent = "读取失败";
|
||||
statusChip.dataset.tone = "failed";
|
||||
setMessage("无法读取诊断状态:" + error.code, "error");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
|
||||
outputButton.addEventListener("click", async function () {
|
||||
if (!currentTarget || currentTarget.outputAvailable !== true) return;
|
||||
setBusy(true);
|
||||
setMessage("正在显式读取诊断内容…");
|
||||
try {
|
||||
const response = await request("output", currentTarget);
|
||||
renderOutput(response);
|
||||
} catch (error) {
|
||||
setMessage("无法读取诊断内容:" + error.code, "error");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener("pagehide", function () {
|
||||
sessionToken = "";
|
||||
currentTarget = null;
|
||||
outputText.textContent = "";
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,218 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="light" />
|
||||
<meta
|
||||
name="description"
|
||||
content="QingLong 3.0 Cluster Copilot 只读诊断台"
|
||||
/>
|
||||
<title>QingLong 3.0 · Copilot 诊断台</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<script src="/app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#workspace">跳到诊断工作区</a>
|
||||
<div class="shell">
|
||||
<header class="masthead">
|
||||
<div class="brand-lockup" aria-label="QingLong 3.0 Cluster Console">
|
||||
<span class="brand-mark" aria-hidden="true">QL</span>
|
||||
<div>
|
||||
<p class="eyebrow">QingLong 3.0 / Cluster field console</p>
|
||||
<h1>故障诊断,不替你执行。</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div class="boundary" aria-label="当前权限边界">
|
||||
<span class="boundary-dot" aria-hidden="true"></span>
|
||||
<span>只读边界</span>
|
||||
<strong>inspect · output</strong>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="workspace" class="workspace">
|
||||
<section class="control-deck" aria-labelledby="target-title">
|
||||
<div class="section-heading">
|
||||
<p class="eyebrow">Target coordinates</p>
|
||||
<h2 id="target-title">定位一次诊断</h2>
|
||||
<p>
|
||||
输入已存在的 Project、源 Run 和诊断请求。页面不会创建、取消或重试任何任务。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form id="session-form" class="session-gate" autocomplete="off">
|
||||
<label for="session-token">浏览器访问密钥</label>
|
||||
<div class="inline-control">
|
||||
<input
|
||||
id="session-token"
|
||||
name="sessionToken"
|
||||
type="password"
|
||||
inputmode="text"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
required
|
||||
pattern="[A-Za-z0-9_\-]{43}"
|
||||
aria-describedby="session-note"
|
||||
/>
|
||||
<button type="submit">解锁本次页面</button>
|
||||
</div>
|
||||
<p id="session-note" class="field-note">
|
||||
从独立的 0600 session 文件读取并粘贴;仅保留在当前页面内存,不会发送到 Cluster API。
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<form id="target-form" class="target-form" autocomplete="off" hidden>
|
||||
<label for="project-id">Project</label>
|
||||
<input
|
||||
id="project-id"
|
||||
name="projectId"
|
||||
type="text"
|
||||
maxlength="128"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
placeholder="project-main"
|
||||
required
|
||||
/>
|
||||
|
||||
<label for="run-id">源 Run</label>
|
||||
<input
|
||||
id="run-id"
|
||||
name="sourceRunId"
|
||||
type="text"
|
||||
maxlength="36"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
placeholder="run_..."
|
||||
required
|
||||
/>
|
||||
|
||||
<label for="request-id">诊断请求</label>
|
||||
<input
|
||||
id="request-id"
|
||||
name="requestId"
|
||||
type="text"
|
||||
maxlength="128"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
placeholder="diag-request-..."
|
||||
required
|
||||
/>
|
||||
|
||||
<div class="actions">
|
||||
<button id="inspect-button" class="primary" type="submit">
|
||||
读取诊断状态
|
||||
</button>
|
||||
<button id="output-button" type="button" disabled>
|
||||
显式读取诊断内容
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<aside class="trust-note">
|
||||
<span>Authority note</span>
|
||||
<p>
|
||||
Cluster credential 只存在于本机 BFF 的私有文件中。浏览器不能读取它,也不能调用 diagnose 或 cancel。
|
||||
</p>
|
||||
</aside>
|
||||
</section>
|
||||
|
||||
<section class="evidence-panel" aria-labelledby="evidence-title">
|
||||
<div class="evidence-header">
|
||||
<div>
|
||||
<p class="eyebrow">Durable evidence</p>
|
||||
<h2 id="evidence-title">诊断轨迹</h2>
|
||||
</div>
|
||||
<span id="status-chip" class="status-chip" data-tone="idle">等待目标</span>
|
||||
</div>
|
||||
|
||||
<div id="empty-state" class="empty-state">
|
||||
<div class="empty-glyph" aria-hidden="true">
|
||||
<span></span><span></span><span></span>
|
||||
</div>
|
||||
<h3>先读取状态,再决定是否查看内容</h3>
|
||||
<p>
|
||||
状态响应只包含有界、低敏的 durable facts。模型文本必须由你再次明确选择。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div id="result-view" hidden>
|
||||
<ol class="trace-rail" aria-label="诊断状态时间线">
|
||||
<li>
|
||||
<span class="trace-node"></span>
|
||||
<div>
|
||||
<small>ADMITTED</small>
|
||||
<strong id="admitted-at">—</strong>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<span class="trace-node"></span>
|
||||
<div>
|
||||
<small>STAGE</small>
|
||||
<strong id="stage">—</strong>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<span class="trace-node"></span>
|
||||
<div>
|
||||
<small>OUTCOME</small>
|
||||
<strong id="outcome">—</strong>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<dl class="fact-grid">
|
||||
<div>
|
||||
<dt>Diagnosis Run</dt>
|
||||
<dd id="diagnosis-run">—</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Reason</dt>
|
||||
<dd id="reason">—</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Tokens</dt>
|
||||
<dd id="tokens">—</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Settled cost</dt>
|
||||
<dd id="cost">—</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<section id="output-panel" class="output-panel" hidden>
|
||||
<div class="output-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Explicit content read</p>
|
||||
<h3>诊断内容</h3>
|
||||
</div>
|
||||
<span>不可信模型输出</span>
|
||||
</div>
|
||||
<pre id="output-text" tabindex="0"></pre>
|
||||
<dl class="output-meta">
|
||||
<div>
|
||||
<dt>Finish reason</dt>
|
||||
<dd id="finish-reason">—</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Output bytes</dt>
|
||||
<dd id="output-bytes">—</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Content digest</dt>
|
||||
<dd id="content-digest">—</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div id="message" class="message" role="status" aria-live="polite"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<span>Loopback only · no legacy session · no browser credential</span>
|
||||
<span>QingLong 3.0 incubation / D-327</span>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "@qinglong/cluster-admin",
|
||||
"version": "3.0.0-alpha.0",
|
||||
"private": true,
|
||||
"description": "QingLong 3.0 cluster operations and bounded Copilot MCP surface",
|
||||
"description": "QingLong 3.0 cluster operations and bounded Copilot MCP/Console surfaces",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=24.18.0 <25"
|
||||
@@ -384,11 +384,17 @@
|
||||
"types": "./dist/copilot-mcp/server.d.ts",
|
||||
"require": "./dist/copilot-mcp/server.js",
|
||||
"default": "./dist/copilot-mcp/server.js"
|
||||
},
|
||||
"./copilot-console": {
|
||||
"types": "./dist/copilot-console/server.d.ts",
|
||||
"require": "./dist/copilot-console/server.js",
|
||||
"default": "./dist/copilot-console/server.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.d.ts"
|
||||
"dist/**/*.d.ts",
|
||||
"assets/copilot-console/*"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
@@ -400,6 +406,7 @@
|
||||
"ql3-cluster-admin": "dist/product-cli/cli.js",
|
||||
"ql3-copilot-client": "dist/copilot-client/cli.js",
|
||||
"ql3-copilot-mcp": "dist/copilot-mcp/cli.js",
|
||||
"ql3-copilot-console": "dist/copilot-console/cli.js",
|
||||
"ql3-plugin-package-recover": "dist/plugin-package/recovery/pluginPackageRecoveryCli.js",
|
||||
"ql3-plugin-package-manage": "dist/plugin-package/management/pluginPackageManagementCli.js",
|
||||
"ql3-plugin-package-client": "dist/plugin-package/management/pluginPackageManagementClientCli.js",
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
lstatSync,
|
||||
readFileSync,
|
||||
realpathSync,
|
||||
type PathLike,
|
||||
} from 'node:fs';
|
||||
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
||||
import { TextDecoder } from 'node:util';
|
||||
|
||||
export interface ClusterCopilotConsoleAssets {
|
||||
readonly html: string;
|
||||
readonly css: string;
|
||||
readonly javascript: string;
|
||||
}
|
||||
|
||||
export class ClusterCopilotConsoleAssetError extends Error {
|
||||
readonly code = 'QL3_CLUSTER_COPILOT_CONSOLE_ASSET_INVALID';
|
||||
|
||||
constructor() {
|
||||
super('Cluster Copilot Console asset is invalid');
|
||||
this.name = 'ClusterCopilotConsoleAssetError';
|
||||
}
|
||||
}
|
||||
|
||||
const ASSETS = Object.freeze([
|
||||
Object.freeze({
|
||||
name: 'index.html',
|
||||
field: 'html',
|
||||
maximumBytes: 32 * 1024,
|
||||
digest: 'f9fa959f30b92c6b000eecb744ce1d0a7fce822c62b3e17dcf10d4d579a072ac',
|
||||
}),
|
||||
Object.freeze({
|
||||
name: 'app.css',
|
||||
field: 'css',
|
||||
maximumBytes: 64 * 1024,
|
||||
digest: '200c3405e1e12329fcfb50509b31b19f1567a91552865f039ce0c2de1530032c',
|
||||
}),
|
||||
Object.freeze({
|
||||
name: 'app.js',
|
||||
field: 'javascript',
|
||||
maximumBytes: 32 * 1024,
|
||||
digest: 'd60913e725e767d9fa2cb65d60c0eae6d75d219f4bec8aad166bed8b6507fe02',
|
||||
}),
|
||||
] as const);
|
||||
|
||||
function invalid(): never {
|
||||
throw new ClusterCopilotConsoleAssetError();
|
||||
}
|
||||
|
||||
function inside(parent: string, candidate: string): boolean {
|
||||
const pathFromParent = relative(parent, candidate);
|
||||
return (
|
||||
pathFromParent !== '' &&
|
||||
pathFromParent !== '..' &&
|
||||
!pathFromParent.startsWith('..' + sep) &&
|
||||
!isAbsolute(pathFromParent)
|
||||
);
|
||||
}
|
||||
|
||||
function readAsset(
|
||||
assetRoot: string,
|
||||
name: string,
|
||||
maximumBytes: number,
|
||||
digest: string,
|
||||
): string {
|
||||
const candidate = resolve(assetRoot, name);
|
||||
const status = lstatSync(candidate, { throwIfNoEntry: false });
|
||||
if (
|
||||
status === undefined ||
|
||||
!status.isFile() ||
|
||||
status.isSymbolicLink() ||
|
||||
status.size < 1 ||
|
||||
status.size > maximumBytes
|
||||
) {
|
||||
return invalid();
|
||||
}
|
||||
const canonicalRoot = realpathSync(assetRoot);
|
||||
const canonicalCandidate = realpathSync(candidate);
|
||||
if (
|
||||
!inside(canonicalRoot, canonicalCandidate) ||
|
||||
canonicalCandidate !== resolve(canonicalRoot, name)
|
||||
) {
|
||||
return invalid();
|
||||
}
|
||||
let bytes: Buffer | undefined;
|
||||
try {
|
||||
bytes = readFileSync(candidate as PathLike);
|
||||
if (
|
||||
bytes.byteLength !== status.size ||
|
||||
createHash('sha256').update(bytes).digest('hex') !== digest ||
|
||||
bytes.includes(0)
|
||||
) {
|
||||
return invalid();
|
||||
}
|
||||
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
||||
} catch (error) {
|
||||
if (error instanceof ClusterCopilotConsoleAssetError) throw error;
|
||||
return invalid();
|
||||
} finally {
|
||||
bytes?.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
export function loadClusterCopilotConsoleAssets(
|
||||
moduleDirectory: string,
|
||||
): Readonly<ClusterCopilotConsoleAssets> {
|
||||
if (typeof moduleDirectory !== 'string' || !isAbsolute(moduleDirectory)) {
|
||||
return invalid();
|
||||
}
|
||||
const packageRoot = resolve(moduleDirectory, '..', '..');
|
||||
const assetRoot = resolve(packageRoot, 'assets', 'copilot-console');
|
||||
const packageStatus = lstatSync(packageRoot, { throwIfNoEntry: false });
|
||||
const assetStatus = lstatSync(assetRoot, { throwIfNoEntry: false });
|
||||
if (
|
||||
packageStatus === undefined ||
|
||||
!packageStatus.isDirectory() ||
|
||||
packageStatus.isSymbolicLink() ||
|
||||
assetStatus === undefined ||
|
||||
!assetStatus.isDirectory() ||
|
||||
assetStatus.isSymbolicLink() ||
|
||||
realpathSync(assetRoot) !==
|
||||
resolve(realpathSync(packageRoot), 'assets', 'copilot-console')
|
||||
) {
|
||||
return invalid();
|
||||
}
|
||||
const result: Record<string, string> = {};
|
||||
for (const asset of ASSETS) {
|
||||
result[asset.field] = readAsset(
|
||||
assetRoot,
|
||||
asset.name,
|
||||
asset.maximumBytes,
|
||||
asset.digest,
|
||||
);
|
||||
}
|
||||
return Object.freeze({
|
||||
html: result.html!,
|
||||
css: result.css!,
|
||||
javascript: result.javascript!,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import {
|
||||
executeClusterCopilotCommand,
|
||||
probeClusterCopilotClientReadiness,
|
||||
validateClusterCopilotClientConfiguration,
|
||||
validateClusterCopilotClientCredentialFile,
|
||||
type ClusterCopilotClientCommand,
|
||||
} from '../copilot-client/client';
|
||||
import { readCanonicalFile } from '../management-support/managementClientConfiguration';
|
||||
import { loadClusterCopilotConsoleAssets } from './assets';
|
||||
import {
|
||||
clusterCopilotConsoleSessionDigest,
|
||||
startClusterCopilotConsoleServer,
|
||||
} from './server';
|
||||
|
||||
const USAGE = [
|
||||
'Usage:',
|
||||
' ql3-copilot-console --config /absolute/client.json --credential /absolute/credential --session /absolute/session [--port=0..65535]',
|
||||
' ql3-copilot-console --check --config /absolute/client.json --credential /absolute/credential --session /absolute/session',
|
||||
'',
|
||||
'The Console binds only 127.0.0.1 and exposes inspect/output reads.',
|
||||
'The browser session key remains in a separate owner-private 0600 file.',
|
||||
].join('\n');
|
||||
|
||||
interface ClusterCopilotConsoleCliArguments {
|
||||
readonly check: boolean;
|
||||
readonly configFile: string;
|
||||
readonly credentialFile: string;
|
||||
readonly sessionFile: string;
|
||||
readonly port: number;
|
||||
}
|
||||
|
||||
const SESSION_TOKEN = /^[A-Za-z0-9_-]{43}$/;
|
||||
const MAXIMUM_SESSION_BYTES = 128;
|
||||
|
||||
function usageFailure(): never {
|
||||
process.stderr.write(USAGE + '\n');
|
||||
process.exit(64);
|
||||
}
|
||||
|
||||
function argumentValue(
|
||||
argv: readonly string[],
|
||||
index: number,
|
||||
name: string,
|
||||
): Readonly<{ value: string; consumed: number }> | null {
|
||||
const current = argv[index];
|
||||
if (current === name) {
|
||||
const next = argv[index + 1];
|
||||
if (typeof next !== 'string' || next === '' || next.startsWith('--')) {
|
||||
return usageFailure();
|
||||
}
|
||||
return Object.freeze({ value: next, consumed: 2 });
|
||||
}
|
||||
const prefix = name + '=';
|
||||
if (current?.startsWith(prefix) && current.length > prefix.length) {
|
||||
return Object.freeze({
|
||||
value: current.slice(prefix.length),
|
||||
consumed: 1,
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parseClusterCopilotConsoleCliArguments(
|
||||
argv: readonly string[],
|
||||
): Readonly<ClusterCopilotConsoleCliArguments> {
|
||||
let check = false;
|
||||
let configFile: string | undefined;
|
||||
let credentialFile: string | undefined;
|
||||
let sessionFile: string | undefined;
|
||||
let port = 0;
|
||||
let portSeen = false;
|
||||
for (let index = 0; index < argv.length; ) {
|
||||
const current = argv[index];
|
||||
if (current === '--check' && !check) {
|
||||
check = true;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
const config = argumentValue(argv, index, '--config');
|
||||
if (config) {
|
||||
if (configFile !== undefined) return usageFailure();
|
||||
configFile = config.value;
|
||||
index += config.consumed;
|
||||
continue;
|
||||
}
|
||||
const credential = argumentValue(argv, index, '--credential');
|
||||
if (credential) {
|
||||
if (credentialFile !== undefined) return usageFailure();
|
||||
credentialFile = credential.value;
|
||||
index += credential.consumed;
|
||||
continue;
|
||||
}
|
||||
const session = argumentValue(argv, index, '--session');
|
||||
if (session) {
|
||||
if (sessionFile !== undefined) return usageFailure();
|
||||
sessionFile = session.value;
|
||||
index += session.consumed;
|
||||
continue;
|
||||
}
|
||||
const portArgument = argumentValue(argv, index, '--port');
|
||||
if (portArgument) {
|
||||
if (portSeen || !/^(?:0|[1-9][0-9]{0,4})$/.test(portArgument.value)) {
|
||||
return usageFailure();
|
||||
}
|
||||
portSeen = true;
|
||||
port = Number(portArgument.value);
|
||||
if (
|
||||
!Number.isSafeInteger(port) ||
|
||||
(port !== 0 && (port < 1_024 || port > 65_535))
|
||||
) {
|
||||
return usageFailure();
|
||||
}
|
||||
index += portArgument.consumed;
|
||||
continue;
|
||||
}
|
||||
return usageFailure();
|
||||
}
|
||||
if (
|
||||
configFile === undefined ||
|
||||
credentialFile === undefined ||
|
||||
sessionFile === undefined ||
|
||||
(check && port !== 0)
|
||||
) {
|
||||
return usageFailure();
|
||||
}
|
||||
return Object.freeze({
|
||||
check,
|
||||
configFile,
|
||||
credentialFile,
|
||||
sessionFile,
|
||||
port,
|
||||
});
|
||||
}
|
||||
|
||||
function readSessionDigest(sessionFile: string): Buffer {
|
||||
let bytes: Buffer | undefined;
|
||||
try {
|
||||
bytes = readCanonicalFile(
|
||||
sessionFile,
|
||||
MAXIMUM_SESSION_BYTES,
|
||||
'private',
|
||||
);
|
||||
if (
|
||||
bytes.some((byte) => byte > 0x7f) ||
|
||||
!SESSION_TOKEN.test(bytes.toString('ascii'))
|
||||
) {
|
||||
throw new Error('invalid session token');
|
||||
}
|
||||
return clusterCopilotConsoleSessionDigest(bytes.toString('ascii'));
|
||||
} finally {
|
||||
bytes?.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
if (
|
||||
process.argv.length === 3 &&
|
||||
(process.argv[2] === '--help' || process.argv[2] === '-h')
|
||||
) {
|
||||
process.stdout.write(USAGE + '\n');
|
||||
return;
|
||||
}
|
||||
const parsed = parseClusterCopilotConsoleCliArguments(process.argv.slice(2));
|
||||
const assets = loadClusterCopilotConsoleAssets(__dirname);
|
||||
validateClusterCopilotClientConfiguration(parsed.configFile);
|
||||
validateClusterCopilotClientCredentialFile(parsed.credentialFile);
|
||||
const sessionDigest = readSessionDigest(parsed.sessionFile);
|
||||
if (parsed.check) {
|
||||
try {
|
||||
const readiness = await probeClusterCopilotClientReadiness(
|
||||
parsed.configFile,
|
||||
);
|
||||
process.stdout.write(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-cluster-copilot-console',
|
||||
event: 'preflight_checked',
|
||||
ready: readiness.ready,
|
||||
listenAddress: '127.0.0.1',
|
||||
browserCredential: 'forbidden',
|
||||
clusterCredential: 'server_only',
|
||||
operations: ['inspect', 'output'],
|
||||
mutation: false,
|
||||
}) + '\n',
|
||||
);
|
||||
if (!readiness.ready) process.exitCode = 69;
|
||||
return;
|
||||
} finally {
|
||||
sessionDigest.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
const server = await startClusterCopilotConsoleServer({
|
||||
assets,
|
||||
executor: Object.freeze({
|
||||
execute(command: Readonly<ClusterCopilotClientCommand>) {
|
||||
return executeClusterCopilotCommand({
|
||||
configFile: parsed.configFile,
|
||||
credentialFile: parsed.credentialFile,
|
||||
command,
|
||||
});
|
||||
},
|
||||
}),
|
||||
port: parsed.port,
|
||||
sessionDigest,
|
||||
});
|
||||
sessionDigest.fill(0);
|
||||
process.stdout.write(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-cluster-copilot-console',
|
||||
event: 'started',
|
||||
origin: server.origin,
|
||||
listenAddress: '127.0.0.1',
|
||||
browserCredential: 'forbidden',
|
||||
clusterCredential: 'server_only',
|
||||
operations: ['inspect', 'output'],
|
||||
mutation: false,
|
||||
}) + '\n',
|
||||
);
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
let stopping = false;
|
||||
const stop = (): void => {
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
void server.close().finally(resolve);
|
||||
};
|
||||
process.once('SIGINT', stop);
|
||||
process.once('SIGTERM', stop);
|
||||
});
|
||||
}
|
||||
|
||||
void main().catch(() => {
|
||||
process.stderr.write(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-cluster-copilot-console',
|
||||
event: 'process_failed',
|
||||
}) + '\n',
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import {
|
||||
CLUSTER_COPILOT_CLIENT_COMMAND_SCHEMA,
|
||||
type ClusterCopilotClientCommand,
|
||||
} from '../copilot-client/contracts';
|
||||
|
||||
export const CLUSTER_COPILOT_CONSOLE_READ_REQUEST_SCHEMA =
|
||||
'qinglong/cluster-copilot-console-read-request@v1' as const;
|
||||
export const CLUSTER_COPILOT_CONSOLE_READ_RESPONSE_SCHEMA =
|
||||
'qinglong/cluster-copilot-console-read-response@v1' as const;
|
||||
|
||||
export type ClusterCopilotConsoleReadOperation = 'inspect' | 'output';
|
||||
|
||||
export interface ClusterCopilotConsoleReadRequest {
|
||||
readonly schema: typeof CLUSTER_COPILOT_CONSOLE_READ_REQUEST_SCHEMA;
|
||||
readonly operation: ClusterCopilotConsoleReadOperation;
|
||||
readonly projectId: string;
|
||||
readonly sourceRunId: string;
|
||||
readonly requestId: string;
|
||||
}
|
||||
|
||||
export class InvalidClusterCopilotConsoleReadRequestError extends TypeError {
|
||||
readonly code = 'QL3_CLUSTER_COPILOT_CONSOLE_READ_REQUEST_INVALID';
|
||||
|
||||
constructor() {
|
||||
super('Cluster Copilot Console read request is invalid');
|
||||
this.name = 'InvalidClusterCopilotConsoleReadRequestError';
|
||||
}
|
||||
}
|
||||
|
||||
const IDENTITY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
||||
const RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,35}$/;
|
||||
|
||||
function invalid(): never {
|
||||
throw new InvalidClusterCopilotConsoleReadRequestError();
|
||||
}
|
||||
|
||||
export function normalizeClusterCopilotConsoleReadRequest(
|
||||
value: unknown,
|
||||
): Readonly<ClusterCopilotConsoleReadRequest> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return invalid();
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
const keys = Object.keys(record).sort();
|
||||
const expected = [
|
||||
'operation',
|
||||
'projectId',
|
||||
'requestId',
|
||||
'schema',
|
||||
'sourceRunId',
|
||||
];
|
||||
if (
|
||||
keys.length !== expected.length ||
|
||||
keys.some((key, index) => key !== expected[index]) ||
|
||||
record.schema !== CLUSTER_COPILOT_CONSOLE_READ_REQUEST_SCHEMA ||
|
||||
(record.operation !== 'inspect' && record.operation !== 'output') ||
|
||||
typeof record.projectId !== 'string' ||
|
||||
!IDENTITY.test(record.projectId) ||
|
||||
typeof record.sourceRunId !== 'string' ||
|
||||
!RUN_ID.test(record.sourceRunId) ||
|
||||
typeof record.requestId !== 'string' ||
|
||||
!IDENTITY.test(record.requestId)
|
||||
) {
|
||||
return invalid();
|
||||
}
|
||||
return Object.freeze({
|
||||
schema: CLUSTER_COPILOT_CONSOLE_READ_REQUEST_SCHEMA,
|
||||
operation: record.operation,
|
||||
projectId: record.projectId,
|
||||
sourceRunId: record.sourceRunId,
|
||||
requestId: record.requestId,
|
||||
});
|
||||
}
|
||||
|
||||
export function clusterCopilotConsoleClientCommand(
|
||||
request: Readonly<ClusterCopilotConsoleReadRequest>,
|
||||
): Readonly<ClusterCopilotClientCommand> {
|
||||
const normalized = normalizeClusterCopilotConsoleReadRequest(request);
|
||||
return Object.freeze({
|
||||
schema: CLUSTER_COPILOT_CLIENT_COMMAND_SCHEMA,
|
||||
operation: normalized.operation,
|
||||
projectId: normalized.projectId,
|
||||
sourceRunId: normalized.sourceRunId,
|
||||
requestId: normalized.requestId,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
import { createHash, timingSafeEqual } from 'node:crypto';
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type ServerResponse,
|
||||
} from 'node:http';
|
||||
|
||||
import {
|
||||
ClusterCopilotClientConfigurationError,
|
||||
ClusterCopilotClientRemoteError,
|
||||
ClusterCopilotClientRequestError,
|
||||
type ClusterCopilotClientCommand,
|
||||
type ClusterCopilotClientResult,
|
||||
} from '../copilot-client/client';
|
||||
import {
|
||||
type ClusterCopilotConsoleAssets,
|
||||
} from './assets';
|
||||
import {
|
||||
CLUSTER_COPILOT_CONSOLE_READ_RESPONSE_SCHEMA,
|
||||
InvalidClusterCopilotConsoleReadRequestError,
|
||||
clusterCopilotConsoleClientCommand,
|
||||
normalizeClusterCopilotConsoleReadRequest,
|
||||
} from './contracts';
|
||||
|
||||
export const CLUSTER_COPILOT_CONSOLE_LIMITS = Object.freeze({
|
||||
maximumBodyBytes: 4 * 1024,
|
||||
maximumResponseBytes: 2 * 1024 * 1024 + 4 * 1024,
|
||||
maximumConcurrentRequests: 2,
|
||||
maximumConnections: 16,
|
||||
shutdownTimeoutMs: 2_000,
|
||||
});
|
||||
|
||||
export interface ClusterCopilotConsoleExecutor {
|
||||
execute(
|
||||
command: Readonly<ClusterCopilotClientCommand>,
|
||||
): Promise<Readonly<ClusterCopilotClientResult>>;
|
||||
}
|
||||
|
||||
export interface ClusterCopilotConsoleServerOptions {
|
||||
readonly assets: Readonly<ClusterCopilotConsoleAssets>;
|
||||
readonly executor: ClusterCopilotConsoleExecutor;
|
||||
readonly port: number;
|
||||
readonly sessionDigest: Buffer;
|
||||
}
|
||||
|
||||
export interface ClusterCopilotConsoleServer {
|
||||
readonly origin: string;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export class ClusterCopilotConsoleConfigurationError extends TypeError {
|
||||
readonly code = 'QL3_CLUSTER_COPILOT_CONSOLE_CONFIG_INVALID';
|
||||
|
||||
constructor() {
|
||||
super('Cluster Copilot Console configuration is invalid');
|
||||
this.name = 'ClusterCopilotConsoleConfigurationError';
|
||||
}
|
||||
}
|
||||
|
||||
const SESSION_TOKEN = /^[A-Za-z0-9_-]{43}$/;
|
||||
const SESSION_DIGEST_DOMAIN = Buffer.from(
|
||||
'qinglong-cluster-copilot-console-session-v1\0',
|
||||
'utf8',
|
||||
);
|
||||
const CONTENT_SECURITY_POLICY = [
|
||||
"default-src 'none'",
|
||||
"base-uri 'none'",
|
||||
"connect-src 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'none'",
|
||||
"font-src 'none'",
|
||||
"object-src 'none'",
|
||||
"media-src 'none'",
|
||||
"manifest-src 'none'",
|
||||
"worker-src 'none'",
|
||||
].join('; ');
|
||||
|
||||
function invalid(): never {
|
||||
throw new ClusterCopilotConsoleConfigurationError();
|
||||
}
|
||||
|
||||
function exactObject(
|
||||
value: unknown,
|
||||
keys: readonly string[],
|
||||
): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return invalid();
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
const actual = Object.keys(record).sort();
|
||||
const expected = [...keys].sort();
|
||||
if (
|
||||
actual.length !== expected.length ||
|
||||
actual.some((key, index) => key !== expected[index])
|
||||
) {
|
||||
return invalid();
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
export function clusterCopilotConsoleSessionDigest(value: string): Buffer {
|
||||
if (typeof value !== 'string' || !SESSION_TOKEN.test(value)) {
|
||||
return invalid();
|
||||
}
|
||||
const decoded = Buffer.from(value, 'base64url');
|
||||
if (
|
||||
decoded.byteLength !== 32 ||
|
||||
decoded.toString('base64url') !== value
|
||||
) {
|
||||
decoded.fill(0);
|
||||
return invalid();
|
||||
}
|
||||
decoded.fill(0);
|
||||
return createHash('sha256')
|
||||
.update(SESSION_DIGEST_DOMAIN)
|
||||
.update(value, 'ascii')
|
||||
.digest();
|
||||
}
|
||||
|
||||
function securityHeaders(contentType: string): Readonly<Record<string, string>> {
|
||||
return Object.freeze({
|
||||
'cache-control': 'no-store',
|
||||
'content-security-policy': CONTENT_SECURITY_POLICY,
|
||||
'content-type': contentType,
|
||||
'cross-origin-opener-policy': 'same-origin',
|
||||
'cross-origin-resource-policy': 'same-origin',
|
||||
'origin-agent-cluster': '?1',
|
||||
'permissions-policy':
|
||||
'camera=(), display-capture=(), geolocation=(), microphone=(), payment=(), usb=()',
|
||||
'referrer-policy': 'no-referrer',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'x-frame-options': 'DENY',
|
||||
});
|
||||
}
|
||||
|
||||
function send(
|
||||
response: ServerResponse,
|
||||
statusCode: number,
|
||||
contentType: string,
|
||||
body: string,
|
||||
extraHeaders: Readonly<Record<string, string>> = {},
|
||||
): void {
|
||||
const bytes = Buffer.from(body, 'utf8');
|
||||
response.writeHead(statusCode, {
|
||||
...securityHeaders(contentType),
|
||||
...extraHeaders,
|
||||
connection: 'close',
|
||||
'content-length': String(bytes.byteLength),
|
||||
});
|
||||
response.end(bytes, () => bytes.fill(0));
|
||||
}
|
||||
|
||||
function sendJson(
|
||||
response: ServerResponse,
|
||||
statusCode: number,
|
||||
body: Readonly<Record<string, unknown>>,
|
||||
extraHeaders: Readonly<Record<string, string>> = {},
|
||||
): void {
|
||||
send(
|
||||
response,
|
||||
statusCode,
|
||||
'application/json; charset=utf-8',
|
||||
JSON.stringify(body),
|
||||
extraHeaders,
|
||||
);
|
||||
}
|
||||
|
||||
function headerCount(request: IncomingMessage, name: string): number {
|
||||
let count = 0;
|
||||
for (let index = 0; index < request.rawHeaders.length; index += 2) {
|
||||
if (request.rawHeaders[index]?.toLowerCase() === name) count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function targetPath(request: IncomingMessage): 'inspect' | 'output' | null {
|
||||
if (request.method !== 'POST') return null;
|
||||
if (request.url === '/api/v1/copilot/inspect') return 'inspect';
|
||||
if (request.url === '/api/v1/copilot/output') return 'output';
|
||||
return null;
|
||||
}
|
||||
|
||||
function authorize(
|
||||
request: IncomingMessage,
|
||||
expectedOrigin: string,
|
||||
sessionDigest: Buffer,
|
||||
): boolean {
|
||||
if (
|
||||
headerCount(request, 'authorization') !== 1 ||
|
||||
headerCount(request, 'origin') !== 1 ||
|
||||
request.headers.origin !== expectedOrigin ||
|
||||
request.headers.host !== expectedOrigin.slice('http://'.length)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const authorization = request.headers.authorization;
|
||||
if (
|
||||
typeof authorization !== 'string' ||
|
||||
!authorization.startsWith('QL3-Console ')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
let candidate: Buffer | undefined;
|
||||
try {
|
||||
candidate = clusterCopilotConsoleSessionDigest(
|
||||
authorization.slice('QL3-Console '.length),
|
||||
);
|
||||
return timingSafeEqual(candidate, sessionDigest);
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
candidate?.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function readJsonBody(request: IncomingMessage): Promise<unknown> {
|
||||
if (
|
||||
headerCount(request, 'content-type') !== 1 ||
|
||||
headerCount(request, 'content-length') !== 1 ||
|
||||
request.headers['content-type'] !== 'application/json; charset=utf-8' ||
|
||||
request.headers['content-encoding'] !== undefined ||
|
||||
request.headers['transfer-encoding'] !== undefined ||
|
||||
typeof request.headers['content-length'] !== 'string' ||
|
||||
!/^[1-9][0-9]*$/.test(request.headers['content-length'])
|
||||
) {
|
||||
throw new InvalidClusterCopilotConsoleReadRequestError();
|
||||
}
|
||||
const expectedLength = Number(request.headers['content-length']);
|
||||
if (
|
||||
!Number.isSafeInteger(expectedLength) ||
|
||||
expectedLength < 2 ||
|
||||
expectedLength > CLUSTER_COPILOT_CONSOLE_LIMITS.maximumBodyBytes
|
||||
) {
|
||||
throw new InvalidClusterCopilotConsoleReadRequestError();
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
let length = 0;
|
||||
try {
|
||||
for await (const chunk of request) {
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
length += bytes.byteLength;
|
||||
if (
|
||||
length > expectedLength ||
|
||||
length > CLUSTER_COPILOT_CONSOLE_LIMITS.maximumBodyBytes
|
||||
) {
|
||||
throw new InvalidClusterCopilotConsoleReadRequestError();
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
if (request.aborted || length !== expectedLength) {
|
||||
throw new InvalidClusterCopilotConsoleReadRequestError();
|
||||
}
|
||||
const body = Buffer.concat(chunks, length);
|
||||
try {
|
||||
return JSON.parse(body.toString('utf8'));
|
||||
} finally {
|
||||
body.fill(0);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof InvalidClusterCopilotConsoleReadRequestError) {
|
||||
throw error;
|
||||
}
|
||||
throw new InvalidClusterCopilotConsoleReadRequestError();
|
||||
} finally {
|
||||
for (const chunk of chunks) chunk.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
function remoteFailure(
|
||||
response: ServerResponse,
|
||||
error: ClusterCopilotClientRemoteError,
|
||||
): void {
|
||||
const statusCode =
|
||||
error.statusCode === 404
|
||||
? 404
|
||||
: error.statusCode === 429
|
||||
? 429
|
||||
: 502;
|
||||
sendJson(
|
||||
response,
|
||||
statusCode,
|
||||
Object.freeze({
|
||||
schema: CLUSTER_COPILOT_CONSOLE_READ_RESPONSE_SCHEMA,
|
||||
code: error.responseCode,
|
||||
requestId: error.requestId,
|
||||
retryAfterSeconds: error.retryAfterSeconds,
|
||||
}),
|
||||
error.retryAfterSeconds === null
|
||||
? {}
|
||||
: { 'retry-after': String(error.retryAfterSeconds) },
|
||||
);
|
||||
}
|
||||
|
||||
export async function startClusterCopilotConsoleServer(
|
||||
options: ClusterCopilotConsoleServerOptions,
|
||||
): Promise<Readonly<ClusterCopilotConsoleServer>> {
|
||||
const record = exactObject(options, [
|
||||
'assets',
|
||||
'executor',
|
||||
'port',
|
||||
'sessionDigest',
|
||||
]);
|
||||
const assets = exactObject(record.assets, ['css', 'html', 'javascript']);
|
||||
if (
|
||||
typeof assets.html !== 'string' ||
|
||||
assets.html.length < 1 ||
|
||||
typeof assets.css !== 'string' ||
|
||||
assets.css.length < 1 ||
|
||||
typeof assets.javascript !== 'string' ||
|
||||
assets.javascript.length < 1 ||
|
||||
!record.executor ||
|
||||
typeof (record.executor as ClusterCopilotConsoleExecutor).execute !==
|
||||
'function' ||
|
||||
!Number.isSafeInteger(record.port) ||
|
||||
((record.port as number) !== 0 &&
|
||||
((record.port as number) < 1_024 || (record.port as number) > 65_535)) ||
|
||||
!Buffer.isBuffer(record.sessionDigest) ||
|
||||
(record.sessionDigest as Buffer).byteLength !== 32
|
||||
) {
|
||||
return invalid();
|
||||
}
|
||||
const sessionDigest = Buffer.from(record.sessionDigest as Buffer);
|
||||
const executor = record.executor as ClusterCopilotConsoleExecutor;
|
||||
let expectedOrigin = '';
|
||||
let inFlight = 0;
|
||||
let closed = false;
|
||||
|
||||
const server = createServer(async (request, response) => {
|
||||
response.shouldKeepAlive = false;
|
||||
const hostMatches =
|
||||
expectedOrigin !== '' &&
|
||||
request.headers.host === expectedOrigin.slice('http://'.length);
|
||||
if (request.method === 'GET' && hostMatches) {
|
||||
if (request.url === '/') {
|
||||
send(response, 200, 'text/html; charset=utf-8', assets.html as string);
|
||||
return;
|
||||
}
|
||||
if (request.url === '/app.css') {
|
||||
send(response, 200, 'text/css; charset=utf-8', assets.css as string);
|
||||
return;
|
||||
}
|
||||
if (request.url === '/app.js') {
|
||||
send(
|
||||
response,
|
||||
200,
|
||||
'text/javascript; charset=utf-8',
|
||||
assets.javascript as string,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const operation = targetPath(request);
|
||||
if (
|
||||
!hostMatches ||
|
||||
operation === null ||
|
||||
!authorize(request, expectedOrigin, sessionDigest)
|
||||
) {
|
||||
sendJson(response, 404, Object.freeze({ code: 'not_found' }));
|
||||
request.resume();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
inFlight >= CLUSTER_COPILOT_CONSOLE_LIMITS.maximumConcurrentRequests
|
||||
) {
|
||||
sendJson(
|
||||
response,
|
||||
429,
|
||||
Object.freeze({
|
||||
schema: CLUSTER_COPILOT_CONSOLE_READ_RESPONSE_SCHEMA,
|
||||
code: 'cluster_copilot_console_busy',
|
||||
}),
|
||||
{ 'retry-after': '1' },
|
||||
);
|
||||
request.resume();
|
||||
return;
|
||||
}
|
||||
|
||||
inFlight += 1;
|
||||
try {
|
||||
const body = await readJsonBody(request);
|
||||
const normalized = normalizeClusterCopilotConsoleReadRequest(body);
|
||||
if (normalized.operation !== operation) {
|
||||
throw new InvalidClusterCopilotConsoleReadRequestError();
|
||||
}
|
||||
const result = await executor.execute(
|
||||
clusterCopilotConsoleClientCommand(normalized),
|
||||
);
|
||||
const envelope = Object.freeze({
|
||||
schema: CLUSTER_COPILOT_CONSOLE_READ_RESPONSE_SCHEMA,
|
||||
operation,
|
||||
requestId: result.requestId,
|
||||
result,
|
||||
});
|
||||
const encoded = JSON.stringify(envelope);
|
||||
if (
|
||||
Buffer.byteLength(encoded, 'utf8') >
|
||||
CLUSTER_COPILOT_CONSOLE_LIMITS.maximumResponseBytes
|
||||
) {
|
||||
throw new ClusterCopilotClientRequestError();
|
||||
}
|
||||
send(
|
||||
response,
|
||||
200,
|
||||
'application/json; charset=utf-8',
|
||||
encoded,
|
||||
);
|
||||
} catch (error) {
|
||||
if (response.headersSent) {
|
||||
response.destroy();
|
||||
} else if (
|
||||
error instanceof InvalidClusterCopilotConsoleReadRequestError
|
||||
) {
|
||||
sendJson(
|
||||
response,
|
||||
400,
|
||||
Object.freeze({
|
||||
schema: CLUSTER_COPILOT_CONSOLE_READ_RESPONSE_SCHEMA,
|
||||
code: 'invalid_cluster_copilot_console_read_request',
|
||||
}),
|
||||
);
|
||||
} else if (error instanceof ClusterCopilotClientRemoteError) {
|
||||
remoteFailure(response, error);
|
||||
} else if (
|
||||
error instanceof ClusterCopilotClientConfigurationError ||
|
||||
error instanceof ClusterCopilotClientRequestError
|
||||
) {
|
||||
sendJson(
|
||||
response,
|
||||
503,
|
||||
Object.freeze({
|
||||
schema: CLUSTER_COPILOT_CONSOLE_READ_RESPONSE_SCHEMA,
|
||||
code: 'cluster_copilot_console_upstream_unavailable',
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
sendJson(
|
||||
response,
|
||||
503,
|
||||
Object.freeze({
|
||||
schema: CLUSTER_COPILOT_CONSOLE_READ_RESPONSE_SCHEMA,
|
||||
code: 'cluster_copilot_console_unavailable',
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
inFlight -= 1;
|
||||
}
|
||||
});
|
||||
|
||||
server.maxConnections = CLUSTER_COPILOT_CONSOLE_LIMITS.maximumConnections;
|
||||
server.headersTimeout = 5_000;
|
||||
server.requestTimeout = 5_000;
|
||||
server.keepAliveTimeout = 1;
|
||||
server.maxRequestsPerSocket = 1;
|
||||
server.on('clientError', (_error, socket) => socket.destroy());
|
||||
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(record.port as number, '127.0.0.1', () => {
|
||||
server.off('error', reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') return invalid();
|
||||
expectedOrigin = 'http://127.0.0.1:' + String(address.port);
|
||||
} catch (error) {
|
||||
sessionDigest.fill(0);
|
||||
server.closeAllConnections();
|
||||
if (error instanceof ClusterCopilotConsoleConfigurationError) throw error;
|
||||
throw new ClusterCopilotConsoleConfigurationError();
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
origin: expectedOrigin,
|
||||
async close(): Promise<void> {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(() => {
|
||||
server.closeAllConnections();
|
||||
}, CLUSTER_COPILOT_CONSOLE_LIMITS.shutdownTimeoutMs);
|
||||
timeout.unref();
|
||||
server.close(() => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
server.closeIdleConnections();
|
||||
});
|
||||
sessionDigest.fill(0);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -46,6 +46,12 @@ export const QINGLONG3_CLUSTER_PRODUCT_COMMANDS: readonly QingLong3ClusterProduc
|
||||
target: 'copilot-mcp/cli.js',
|
||||
description: 'serve the bounded Cluster Copilot MCP over stdio',
|
||||
}),
|
||||
Object.freeze({
|
||||
name: 'copilot-console',
|
||||
binary: 'ql3-copilot-console',
|
||||
target: 'copilot-console/cli.js',
|
||||
description: 'open the loopback-only read-only Copilot Console',
|
||||
}),
|
||||
Object.freeze({
|
||||
name: 'package',
|
||||
binary: 'ql3-plugin-package-client',
|
||||
@@ -192,7 +198,7 @@ export function qingLong3ClusterProductHelp(): string {
|
||||
'',
|
||||
'Use `ql3-cluster-admin <command> --help` for command-specific usage.',
|
||||
'Use `--context=/absolute/operator-context.json` only with remote client commands.',
|
||||
'Keep the MCP config explicit; it contains stable paths to a separately rotated credential.',
|
||||
'Keep MCP and Console authority explicit; neither belongs in operator context.',
|
||||
'Command and short-lived assertion files always remain explicit per invocation.',
|
||||
'Server, migration, recovery, executor and key-custody authorities remain isolated.',
|
||||
].join('\n');
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { randomBytes } = require('node:crypto');
|
||||
const { request: httpRequest } = require('node:http');
|
||||
const { mkdtemp, mkdir, cp, writeFile } = require('node:fs/promises');
|
||||
const { tmpdir } = require('node:os');
|
||||
const { join, resolve } = require('node:path');
|
||||
const test = require('node:test');
|
||||
|
||||
const {
|
||||
ClusterCopilotClientRemoteError,
|
||||
} = require('../dist/copilot-client/client.js');
|
||||
const {
|
||||
ClusterCopilotConsoleAssetError,
|
||||
loadClusterCopilotConsoleAssets,
|
||||
} = require('../dist/copilot-console/assets.js');
|
||||
const {
|
||||
CLUSTER_COPILOT_CONSOLE_READ_REQUEST_SCHEMA,
|
||||
clusterCopilotConsoleClientCommand,
|
||||
normalizeClusterCopilotConsoleReadRequest,
|
||||
} = require('../dist/copilot-console/contracts.js');
|
||||
const {
|
||||
clusterCopilotConsoleSessionDigest,
|
||||
startClusterCopilotConsoleServer,
|
||||
} = require('../dist/copilot-console/server.js');
|
||||
|
||||
const moduleDirectory = resolve(__dirname, '../dist/copilot-console');
|
||||
|
||||
function target(operation = 'inspect') {
|
||||
return {
|
||||
schema: CLUSTER_COPILOT_CONSOLE_READ_REQUEST_SCHEMA,
|
||||
operation,
|
||||
projectId: 'project-main',
|
||||
sourceRunId: 'run-source-1',
|
||||
requestId: 'diagnosis-request-1',
|
||||
};
|
||||
}
|
||||
|
||||
function inspection() {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
operation: 'inspect',
|
||||
requestId: 'transport-read-1',
|
||||
result: {
|
||||
schema: 'qinglong/cluster-copilot-failure-diagnosis-inspection-response@v1',
|
||||
status: 'terminal',
|
||||
projectId: 'project-main',
|
||||
sourceRunId: 'run-source-1',
|
||||
requestId: 'diagnosis-request-1',
|
||||
diagnosisRunId: 'run-diagnosis-1',
|
||||
outcome: 'succeeded',
|
||||
stage: 'model',
|
||||
reason: null,
|
||||
outputAvailable: true,
|
||||
admittedAtMs: 1_700_000_000_000,
|
||||
finalizedAtMs: 1_700_000_001_000,
|
||||
usage: {
|
||||
inputTokens: 20,
|
||||
outputTokens: 10,
|
||||
totalTokens: 30,
|
||||
currency: 'USD',
|
||||
costMicros: 42,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function output() {
|
||||
const text = '<script>never execute</script>';
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
operation: 'output',
|
||||
requestId: 'transport-read-2',
|
||||
result: {
|
||||
schema: 'qinglong/cluster-copilot-failure-diagnosis-output-read-response@v1',
|
||||
status: 'available',
|
||||
projectId: 'project-main',
|
||||
sourceRunId: 'run-source-1',
|
||||
requestId: 'diagnosis-request-1',
|
||||
diagnosisRunId: 'run-diagnosis-1',
|
||||
reference: {
|
||||
artifactId: 'artifact-diagnosis-1',
|
||||
artifactDigest: 'a'.repeat(64),
|
||||
contentDigest: 'b'.repeat(64),
|
||||
outputBytes: Buffer.byteLength(text),
|
||||
sealedAtMs: 1_700_000_001_000,
|
||||
},
|
||||
result: {
|
||||
text,
|
||||
finishReason: 'stop',
|
||||
usage: {
|
||||
inputTokens: 20,
|
||||
outputTokens: 10,
|
||||
totalTokens: 30,
|
||||
costMicros: 42,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function request(origin, options = {}) {
|
||||
const url = new URL(origin);
|
||||
const body =
|
||||
options.body === undefined
|
||||
? undefined
|
||||
: Buffer.from(JSON.stringify(options.body), 'utf8');
|
||||
return new Promise((resolve, reject) => {
|
||||
const outgoing = httpRequest(
|
||||
{
|
||||
hostname: '127.0.0.1',
|
||||
port: Number(url.port),
|
||||
method: options.method || 'GET',
|
||||
path: options.path || '/',
|
||||
agent: false,
|
||||
headers: {
|
||||
...(options.headers || {}),
|
||||
...(body === undefined
|
||||
? {}
|
||||
: {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'content-length': String(body.length),
|
||||
}),
|
||||
},
|
||||
},
|
||||
(incoming) => {
|
||||
const chunks = [];
|
||||
incoming.on('data', (chunk) => chunks.push(chunk));
|
||||
incoming.on('end', () => {
|
||||
const bytes = Buffer.concat(chunks);
|
||||
const text = bytes.toString('utf8');
|
||||
resolve({
|
||||
statusCode: incoming.statusCode,
|
||||
headers: incoming.headers,
|
||||
text,
|
||||
body:
|
||||
incoming.headers['content-type'] ===
|
||||
'application/json; charset=utf-8'
|
||||
? JSON.parse(text)
|
||||
: null,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
outgoing.once('error', reject);
|
||||
if (body !== undefined) outgoing.end(body);
|
||||
else outgoing.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function fixture(execute = async () => inspection()) {
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const server = await startClusterCopilotConsoleServer({
|
||||
assets: loadClusterCopilotConsoleAssets(moduleDirectory),
|
||||
executor: { execute },
|
||||
port: 0,
|
||||
sessionDigest: clusterCopilotConsoleSessionDigest(token),
|
||||
});
|
||||
return {
|
||||
token,
|
||||
server,
|
||||
headers: {
|
||||
authorization: 'QL3-Console ' + token,
|
||||
origin: server.origin,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('normalizes only the two read operations into the shared client contract', () => {
|
||||
assert.deepEqual(
|
||||
clusterCopilotConsoleClientCommand(
|
||||
normalizeClusterCopilotConsoleReadRequest(target('inspect')),
|
||||
),
|
||||
{
|
||||
schema: 'qinglong/cluster-copilot-client-command@v1',
|
||||
operation: 'inspect',
|
||||
projectId: 'project-main',
|
||||
sourceRunId: 'run-source-1',
|
||||
requestId: 'diagnosis-request-1',
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
clusterCopilotConsoleClientCommand(target('output')).operation,
|
||||
'output',
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
normalizeClusterCopilotConsoleReadRequest({
|
||||
...target(),
|
||||
operation: 'diagnose',
|
||||
}),
|
||||
{ code: 'QL3_CLUSTER_COPILOT_CONSOLE_READ_REQUEST_INVALID' },
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
normalizeClusterCopilotConsoleReadRequest({
|
||||
...target(),
|
||||
mutationId: 'forbidden',
|
||||
}),
|
||||
{ code: 'QL3_CLUSTER_COPILOT_CONSOLE_READ_REQUEST_INVALID' },
|
||||
);
|
||||
});
|
||||
|
||||
test('loads only digest-bound packaged assets and rejects drift', async (t) => {
|
||||
const assets = loadClusterCopilotConsoleAssets(moduleDirectory);
|
||||
assert.match(assets.html, /故障诊断,不替你执行/);
|
||||
assert.match(assets.css, /prefers-reduced-motion/);
|
||||
assert.match(assets.javascript, /textContent = fact\.result\.text/);
|
||||
assert.doesNotMatch(assets.javascript, /localStorage|sessionStorage|innerHTML/);
|
||||
|
||||
const root = await mkdtemp(join(tmpdir(), 'ql3-console-assets-'));
|
||||
t.after(() => require('node:fs').rmSync(root, { recursive: true, force: true }));
|
||||
const fakeModuleDirectory = join(root, 'dist', 'copilot-console');
|
||||
await mkdir(fakeModuleDirectory, { recursive: true });
|
||||
await cp(
|
||||
resolve(moduleDirectory, '../../assets'),
|
||||
join(root, 'assets'),
|
||||
{ recursive: true },
|
||||
);
|
||||
await writeFile(
|
||||
join(root, 'assets', 'copilot-console', 'app.js'),
|
||||
'"drift";\n',
|
||||
);
|
||||
assert.throws(
|
||||
() => loadClusterCopilotConsoleAssets(fakeModuleDirectory),
|
||||
ClusterCopilotConsoleAssetError,
|
||||
);
|
||||
});
|
||||
|
||||
test('serves an immutable same-origin shell with a closed browser policy', async (t) => {
|
||||
const { server } = await fixture();
|
||||
t.after(() => server.close());
|
||||
const html = await request(server.origin);
|
||||
assert.equal(html.statusCode, 200);
|
||||
assert.equal(html.headers['cache-control'], 'no-store');
|
||||
assert.equal(html.headers['x-frame-options'], 'DENY');
|
||||
assert.match(html.headers['content-security-policy'], /default-src 'none'/);
|
||||
assert.match(html.headers['content-security-policy'], /connect-src 'self'/);
|
||||
assert.match(html.text, /Cluster field console/);
|
||||
|
||||
const css = await request(server.origin, { path: '/app.css' });
|
||||
const javascript = await request(server.origin, { path: '/app.js' });
|
||||
assert.equal(css.statusCode, 200);
|
||||
assert.equal(javascript.statusCode, 200);
|
||||
assert.equal(javascript.headers['content-type'], 'text/javascript; charset=utf-8');
|
||||
});
|
||||
|
||||
test('keeps the Cluster credential server-side and forwards one exact inspect', async (t) => {
|
||||
const commands = [];
|
||||
const { server, headers } = await fixture(async (command) => {
|
||||
commands.push(command);
|
||||
return inspection();
|
||||
});
|
||||
t.after(() => server.close());
|
||||
const response = await request(server.origin, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/copilot/inspect',
|
||||
headers,
|
||||
body: target('inspect'),
|
||||
});
|
||||
assert.equal(response.statusCode, 200);
|
||||
assert.deepEqual(commands, [
|
||||
{
|
||||
schema: 'qinglong/cluster-copilot-client-command@v1',
|
||||
operation: 'inspect',
|
||||
projectId: 'project-main',
|
||||
sourceRunId: 'run-source-1',
|
||||
requestId: 'diagnosis-request-1',
|
||||
},
|
||||
]);
|
||||
assert.equal(
|
||||
response.body.schema,
|
||||
'qinglong/cluster-copilot-console-read-response@v1',
|
||||
);
|
||||
assert.equal(response.body.result.result.outputAvailable, true);
|
||||
assert.doesNotMatch(response.text, /ql3c_|authorization|credential/i);
|
||||
});
|
||||
|
||||
test('returns model text as JSON data only after an explicit output read', async (t) => {
|
||||
const { server, headers } = await fixture(async (command) => {
|
||||
assert.equal(command.operation, 'output');
|
||||
return output();
|
||||
});
|
||||
t.after(() => server.close());
|
||||
const response = await request(server.origin, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/copilot/output',
|
||||
headers,
|
||||
body: target('output'),
|
||||
});
|
||||
assert.equal(response.statusCode, 200);
|
||||
assert.equal(
|
||||
response.body.result.result.result.text,
|
||||
'<script>never execute</script>',
|
||||
);
|
||||
assert.equal(response.headers['content-type'], 'application/json; charset=utf-8');
|
||||
assert.equal(response.headers['x-content-type-options'], 'nosniff');
|
||||
});
|
||||
|
||||
test('masks wrong Host, Origin, session and every non-read route', async (t) => {
|
||||
let calls = 0;
|
||||
const { server, token, headers } = await fixture(async () => {
|
||||
calls += 1;
|
||||
return inspection();
|
||||
});
|
||||
t.after(() => server.close());
|
||||
const cases = [
|
||||
{ ...headers, origin: 'https://attacker.example' },
|
||||
{ ...headers, authorization: 'QL3-Console ' + randomBytes(32).toString('base64url') },
|
||||
{ ...headers, host: 'attacker.example' },
|
||||
];
|
||||
for (const candidate of cases) {
|
||||
const response = await request(server.origin, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/copilot/inspect',
|
||||
headers: candidate,
|
||||
body: target(),
|
||||
});
|
||||
assert.equal(response.statusCode, 404);
|
||||
assert.deepEqual(response.body, { code: 'not_found' });
|
||||
}
|
||||
const mutation = await request(server.origin, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/copilot/diagnose',
|
||||
headers: {
|
||||
authorization: 'QL3-Console ' + token,
|
||||
origin: server.origin,
|
||||
},
|
||||
body: target(),
|
||||
});
|
||||
assert.equal(mutation.statusCode, 404);
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test('rejects widened and route-confused read bodies before upstream authority', async (t) => {
|
||||
let calls = 0;
|
||||
const { server, headers } = await fixture(async () => {
|
||||
calls += 1;
|
||||
return inspection();
|
||||
});
|
||||
t.after(() => server.close());
|
||||
const widened = await request(server.origin, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/copilot/inspect',
|
||||
headers,
|
||||
body: { ...target(), endpoint: 'https://attacker.example' },
|
||||
});
|
||||
const confused = await request(server.origin, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/copilot/output',
|
||||
headers,
|
||||
body: target('inspect'),
|
||||
});
|
||||
assert.equal(widened.statusCode, 400);
|
||||
assert.equal(confused.statusCode, 400);
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test('rejects a third concurrent read without a hidden queue', async (t) => {
|
||||
const releases = [];
|
||||
const { server, headers } = await fixture(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
releases.push(() => resolve(inspection()));
|
||||
}),
|
||||
);
|
||||
t.after(() => server.close());
|
||||
const options = {
|
||||
method: 'POST',
|
||||
path: '/api/v1/copilot/inspect',
|
||||
headers,
|
||||
body: target(),
|
||||
};
|
||||
const first = request(server.origin, options);
|
||||
const second = request(server.origin, options);
|
||||
while (releases.length < 2) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
const third = await request(server.origin, options);
|
||||
assert.equal(third.statusCode, 429);
|
||||
assert.equal(third.body.code, 'cluster_copilot_console_busy');
|
||||
assert.equal(releases.length, 2);
|
||||
releases.splice(0).forEach((release) => release());
|
||||
assert.equal((await first).statusCode, 200);
|
||||
assert.equal((await second).statusCode, 200);
|
||||
});
|
||||
|
||||
test('projects only bounded remote failure facts and closes idempotently', async () => {
|
||||
const { server, headers } = await fixture(async () => {
|
||||
throw new ClusterCopilotClientRemoteError(
|
||||
429,
|
||||
'project_read_rate_limited',
|
||||
'transport-read-3',
|
||||
7,
|
||||
);
|
||||
});
|
||||
const response = await request(server.origin, {
|
||||
method: 'POST',
|
||||
path: '/api/v1/copilot/inspect',
|
||||
headers,
|
||||
body: target(),
|
||||
});
|
||||
assert.equal(response.statusCode, 429);
|
||||
assert.deepEqual(response.body, {
|
||||
schema: 'qinglong/cluster-copilot-console-read-response@v1',
|
||||
code: 'project_read_rate_limited',
|
||||
requestId: 'transport-read-3',
|
||||
retryAfterSeconds: 7,
|
||||
});
|
||||
assert.equal(response.headers['retry-after'], '7');
|
||||
await server.close();
|
||||
await server.close();
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { spawn } = require('node:child_process');
|
||||
const { randomBytes } = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const { request: httpRequest } = require('node:http');
|
||||
const { createServer } = require('node:https');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { test } = require('node:test');
|
||||
|
||||
const {
|
||||
CLUSTER_COPILOT_CLIENT_CONFIG_SCHEMA,
|
||||
} = require('../dist/copilot-client/client.js');
|
||||
|
||||
const packageRoot = path.resolve(__dirname, '..');
|
||||
const cliPath = path.join(packageRoot, 'dist', 'copilot-console', 'cli.js');
|
||||
const tlsFixture = path.resolve(
|
||||
packageRoot,
|
||||
'../ql3-cluster-control/test/fixtures/mtls',
|
||||
);
|
||||
const credential =
|
||||
'ql3c_console_' + Buffer.alloc(32, 9).toString('base64url');
|
||||
|
||||
function privateFile(directory, name, contents) {
|
||||
const filePath = path.join(directory, name);
|
||||
fs.writeFileSync(filePath, contents, { mode: 0o600 });
|
||||
return fs.realpathSync(filePath);
|
||||
}
|
||||
|
||||
function runCli(args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [cliPath, ...args], {
|
||||
cwd: packageRoot,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
const stdout = [];
|
||||
const stderr = [];
|
||||
child.stdout.on('data', (chunk) => stdout.push(chunk));
|
||||
child.stderr.on('data', (chunk) => stderr.push(chunk));
|
||||
child.once('error', reject);
|
||||
child.once('close', (status, signal) => {
|
||||
resolve({
|
||||
status,
|
||||
signal,
|
||||
stdout: Buffer.concat(stdout).toString('utf8'),
|
||||
stderr: Buffer.concat(stderr).toString('utf8'),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function firstLine(stream) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let buffered = '';
|
||||
const receive = (chunk) => {
|
||||
buffered += chunk.toString('utf8');
|
||||
const newline = buffered.indexOf('\n');
|
||||
if (newline === -1) return;
|
||||
stream.off('data', receive);
|
||||
stream.off('error', reject);
|
||||
resolve(buffered.slice(0, newline));
|
||||
};
|
||||
stream.on('data', receive);
|
||||
stream.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function get(origin) {
|
||||
const url = new URL(origin);
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = httpRequest(
|
||||
{
|
||||
hostname: '127.0.0.1',
|
||||
port: Number(url.port),
|
||||
method: 'GET',
|
||||
path: '/',
|
||||
agent: false,
|
||||
},
|
||||
(response) => {
|
||||
const chunks = [];
|
||||
response.on('data', (chunk) => chunks.push(chunk));
|
||||
response.on('end', () =>
|
||||
resolve({
|
||||
statusCode: response.statusCode,
|
||||
body: Buffer.concat(chunks).toString('utf8'),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
request.once('error', reject);
|
||||
request.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function fixture(t) {
|
||||
const directory = fs.realpathSync(
|
||||
fs.mkdtempSync(path.join(os.tmpdir(), 'ql3-copilot-console-cli-')),
|
||||
);
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const requests = [];
|
||||
const server = createServer(
|
||||
{
|
||||
key: fs.readFileSync(path.join(tlsFixture, 'server-key.pem')),
|
||||
cert: fs.readFileSync(path.join(tlsFixture, 'server-cert.pem')),
|
||||
minVersion: 'TLSv1.3',
|
||||
maxVersion: 'TLSv1.3',
|
||||
},
|
||||
(request, response) => {
|
||||
requests.push({
|
||||
method: request.method,
|
||||
path: request.url,
|
||||
authorization: request.headers.authorization,
|
||||
tls: request.socket.getProtocol(),
|
||||
});
|
||||
const bytes = Buffer.from('{"status":"ready"}', 'utf8');
|
||||
response.writeHead(200, {
|
||||
'content-type': 'application/json; charset=utf-8',
|
||||
'content-length': String(bytes.byteLength),
|
||||
});
|
||||
response.end(bytes);
|
||||
},
|
||||
);
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', resolve);
|
||||
});
|
||||
t.after(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
server.close(() => resolve());
|
||||
}),
|
||||
);
|
||||
const caFile = privateFile(
|
||||
directory,
|
||||
'ca.pem',
|
||||
fs.readFileSync(path.join(tlsFixture, 'ca-cert.pem')),
|
||||
);
|
||||
const configFile = privateFile(
|
||||
directory,
|
||||
'client.json',
|
||||
JSON.stringify({
|
||||
schema: CLUSTER_COPILOT_CLIENT_CONFIG_SCHEMA,
|
||||
endpoint: `https://localhost:${server.address().port}/`,
|
||||
servername: 'localhost',
|
||||
caFile,
|
||||
requestTimeoutMs: 2_000,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
requests,
|
||||
configFile,
|
||||
credentialFile: privateFile(directory, 'credential', credential),
|
||||
sessionFile: privateFile(
|
||||
directory,
|
||||
'session',
|
||||
randomBytes(32).toString('base64url'),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
test('CLI exposes deterministic help and a low-sensitive failure surface', async () => {
|
||||
const usage = [
|
||||
'Usage:',
|
||||
' ql3-copilot-console --config /absolute/client.json --credential /absolute/credential --session /absolute/session [--port=0..65535]',
|
||||
' ql3-copilot-console --check --config /absolute/client.json --credential /absolute/credential --session /absolute/session',
|
||||
'',
|
||||
'The Console binds only 127.0.0.1 and exposes inspect/output reads.',
|
||||
'The browser session key remains in a separate owner-private 0600 file.',
|
||||
].join('\n');
|
||||
assert.deepEqual(await runCli(['--help']), {
|
||||
status: 0,
|
||||
signal: null,
|
||||
stdout: usage + '\n',
|
||||
stderr: '',
|
||||
});
|
||||
const failed = await runCli([
|
||||
'--config',
|
||||
'/private/operator/client-secret.json',
|
||||
'--credential',
|
||||
'/private/operator/cluster-secret',
|
||||
'--session',
|
||||
'/private/operator/browser-secret',
|
||||
]);
|
||||
assert.equal(failed.status, 1);
|
||||
assert.equal(failed.stdout, '');
|
||||
assert.deepEqual(JSON.parse(failed.stderr), {
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-cluster-copilot-console',
|
||||
event: 'process_failed',
|
||||
});
|
||||
assert.doesNotMatch(failed.stderr, /client-secret|cluster-secret|browser-secret/);
|
||||
});
|
||||
|
||||
test('preflight proves private authority and unauthenticated TLS 1.3 readiness', async (t) => {
|
||||
const value = await fixture(t);
|
||||
const result = await runCli([
|
||||
'--check',
|
||||
'--config',
|
||||
value.configFile,
|
||||
'--credential',
|
||||
value.credentialFile,
|
||||
'--session',
|
||||
value.sessionFile,
|
||||
]);
|
||||
assert.equal(result.status, 0);
|
||||
assert.equal(result.stderr, '');
|
||||
assert.deepEqual(JSON.parse(result.stdout), {
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-cluster-copilot-console',
|
||||
event: 'preflight_checked',
|
||||
ready: true,
|
||||
listenAddress: '127.0.0.1',
|
||||
browserCredential: 'forbidden',
|
||||
clusterCredential: 'server_only',
|
||||
operations: ['inspect', 'output'],
|
||||
mutation: false,
|
||||
});
|
||||
assert.deepEqual(value.requests, [
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/readyz',
|
||||
authorization: undefined,
|
||||
tls: 'TLSv1.3',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('serve mode starts an ephemeral loopback origin and shuts down cleanly', async (t) => {
|
||||
const value = await fixture(t);
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
cliPath,
|
||||
'--config',
|
||||
value.configFile,
|
||||
'--credential',
|
||||
value.credentialFile,
|
||||
'--session',
|
||||
value.sessionFile,
|
||||
'--port=0',
|
||||
],
|
||||
{ cwd: packageRoot, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||
);
|
||||
t.after(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
|
||||
});
|
||||
const started = JSON.parse(await firstLine(child.stdout));
|
||||
assert.equal(started.event, 'started');
|
||||
assert.match(started.origin, /^http:\/\/127\.0\.0\.1:[0-9]+$/);
|
||||
assert.deepEqual(started.operations, ['inspect', 'output']);
|
||||
assert.equal(started.mutation, false);
|
||||
const shell = await get(started.origin);
|
||||
assert.equal(shell.statusCode, 200);
|
||||
assert.match(shell.body, /Cluster field console/);
|
||||
child.kill('SIGTERM');
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
child.once('error', reject);
|
||||
child.once('close', (status, signal) => resolve({ status, signal }));
|
||||
});
|
||||
assert.deepEqual(result, { status: 0, signal: null });
|
||||
});
|
||||
@@ -333,7 +333,7 @@ function validContextFixture(t) {
|
||||
|
||||
test('catalog exposes only reviewed product entrypoints from the same package', () => {
|
||||
assert.equal(manifest.bin['ql3-cluster-admin'], 'dist/product-cli/cli.js');
|
||||
assert.equal(QINGLONG3_CLUSTER_PRODUCT_COMMANDS.length, 9);
|
||||
assert.equal(QINGLONG3_CLUSTER_PRODUCT_COMMANDS.length, 10);
|
||||
assert.equal(
|
||||
new Set(QINGLONG3_CLUSTER_PRODUCT_COMMANDS.map(({ name }) => name)).size,
|
||||
QINGLONG3_CLUSTER_PRODUCT_COMMANDS.length,
|
||||
@@ -351,7 +351,8 @@ test('catalog exposes only reviewed product entrypoints from the same package',
|
||||
);
|
||||
assert.equal(
|
||||
command.binary.includes('-client') ||
|
||||
command.binary === 'ql3-copilot-mcp',
|
||||
command.binary === 'ql3-copilot-mcp' ||
|
||||
command.binary === 'ql3-copilot-console',
|
||||
true,
|
||||
);
|
||||
}
|
||||
@@ -380,6 +381,7 @@ test('help and version are bounded installation-derived product facts', () => {
|
||||
assert.match(help, /\n run\s+retry or stop Runs/);
|
||||
assert.match(help, /\n copilot\s+diagnose, inspect, read or cancel Runs/);
|
||||
assert.match(help, /\n copilot-mcp\s+serve the bounded Cluster Copilot MCP/);
|
||||
assert.match(help, /\n copilot-console\s+open the loopback-only read-only/);
|
||||
assert.match(help, /Server, migration, recovery, executor and key-custody/);
|
||||
assert.equal(help.includes('plugin-package-manage'), false);
|
||||
assert.equal(
|
||||
|
||||
Reference in New Issue
Block a user