diff --git a/.dockerignore b/.dockerignore index 508ac32de..de3070461 100644 --- a/.dockerignore +++ b/.dockerignore @@ -36,6 +36,7 @@ dist/ coverage.* mobile/agentmesh-node-app/build/ sdk/js/build/ +internal/webapp/public/sdk/ site/public/ site/resources/ rootfs.ext4 diff --git a/.github/k8s/agentmesh-webapp-template.yaml b/.github/k8s/agentmesh-webapp-template.yaml new file mode 100644 index 000000000..0b08906a1 --- /dev/null +++ b/.github/k8s/agentmesh-webapp-template.yaml @@ -0,0 +1,83 @@ +apiVersion: v1 +kind: Service +metadata: + name: agentmesh-webapp-${ENV_NAME} + namespace: ${NAMESPACE} +spec: + ports: + - port: 8082 + targetPort: 8082 + protocol: TCP + name: http + selector: + app: agentmesh-webapp-${ENV_NAME} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: agentmesh-webapp-${ENV_NAME} + namespace: ${NAMESPACE} +spec: + replicas: 1 + selector: + matchLabels: + app: agentmesh-webapp-${ENV_NAME} + template: + metadata: + labels: + app: agentmesh-webapp-${ENV_NAME} + spec: + containers: + - name: agentmesh-webapp + image: ghcr.io/google/agentmesh-webapp:${IMAGE_TAG} + imagePullPolicy: IfNotPresent + args: + - "--bind-addr=:8082" + ports: + - containerPort: 8082 + readinessProbe: + httpGet: + path: / + port: 8082 + resources: + requests: + cpu: 10m + memory: 32Mi +--- +# The page needs no host of its own: it shares the testnet's Gateway, host and +# certificate under /node/, and the prefix is stripped before the web app sees it. +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: agentmesh-webapp-route-${ENV_NAME} + namespace: ${NAMESPACE} +spec: + parentRefs: + - name: sam-control-plane-gateway-${ENV_NAME} + hostnames: + - "${ENV_NAME}.sam-mesh.dev" + rules: + - matches: + - path: + type: Exact + value: /node + filters: + - type: RequestRedirect + requestRedirect: + path: + type: ReplaceFullPath + replaceFullPath: /node/ + statusCode: 302 + - matches: + - path: + type: PathPrefix + value: /node/ + filters: + - type: URLRewrite + urlRewrite: + path: + type: ReplacePrefixMatch + replacePrefixMatch: / + backendRefs: + - name: agentmesh-webapp-${ENV_NAME} + port: 8082 diff --git a/.github/k8s/dex-config.yaml b/.github/k8s/dex-config.yaml index 83f5a2d2e..aec506429 100644 --- a/.github/k8s/dex-config.yaml +++ b/.github/k8s/dex-config.yaml @@ -16,6 +16,10 @@ data: web: # Serve plain HTTP locally; the GKE Ingress handles HTTPS termination http: 0.0.0.0:5556 + # The web app at /node/ reads discovery and trades its sign-in code from the browser. + allowedOrigins: + - 'https://bananas.sam-mesh.dev' + - 'https://hub.sam-mesh.dev' oauth2: grantTypes: @@ -54,6 +58,8 @@ data: - 'http://localhost/callback' - 'https://bananas.sam-mesh.dev/console/auth/callback' - 'https://hub.sam-mesh.dev/console/auth/callback' + - 'https://bananas.sam-mesh.dev/node/' + - 'https://hub.sam-mesh.dev/node/' - 'https://auth.sam-mesh.dev/device/callback' - 'urn:ietf:wg:oauth:2.0:oob' - '/device/callback' diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index eab027623..42805d4a4 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -143,6 +143,29 @@ jobs: tags: ${{ steps.meta-console.outputs.tags }} labels: ${{ steps.meta-console.outputs.labels }} + - name: Extract metadata for agentmesh-webapp + id: meta-webapp + uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 + with: + images: ${{ env.REGISTRY }}/google/agentmesh-webapp + tags: | + type=ref,event=branch + type=ref,event=tag + type=raw,value=${{ github.sha }} + type=raw,value=latest,enable={{is_default_branch}} + type=raw,value=stable,enable=${{ startsWith(github.ref, 'refs/tags/v') }} + + - name: Build and push agentmesh-webapp image + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: Dockerfile.agentmesh-webapp + build-args: VERSION=${{ github.ref_type == 'tag' && github.ref_name || github.sha }} + platforms: ${{ github.ref_type == 'tag' && 'linux/amd64,linux/arm64' || 'linux/amd64' }} + push: true + tags: ${{ steps.meta-webapp.outputs.tags }} + labels: ${{ steps.meta-webapp.outputs.labels }} + - name: Extract metadata for agentmesh-one id: meta-agentmesh-one uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 @@ -404,6 +427,7 @@ jobs: envsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID} ${CLUSTER_NAME} ${CLUSTER_REGION} ${IMAGE_TAG} ${NODE_RETENTION}' < .github/k8s/agentmesh-control-plane-template.yaml | kubectl apply -f - envsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID} ${CLUSTER_NAME} ${CLUSTER_REGION} ${IMAGE_TAG} ${ROUTER_REPLICAS} ${ROUTER_HIGH_WATERMARK}' < .github/k8s/agentmesh-router-template.yaml | kubectl apply -f - envsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID} ${CLUSTER_NAME} ${CLUSTER_REGION} ${IMAGE_TAG}' < .github/k8s/agentmesh-console-template.yaml | kubectl apply -f - + envsubst '${ENV_NAME} ${NAMESPACE} ${IMAGE_TAG}' < .github/k8s/agentmesh-webapp-template.yaml | kubectl apply -f - envsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID}' < .github/k8s/dns-sync-cronjob-template.yaml | kubectl apply -f - # Managed Prometheus ships with GKE; a cluster without it should not block the mesh rollout. if kubectl get crd podmonitorings.monitoring.googleapis.com >/dev/null 2>&1; then @@ -467,6 +491,12 @@ jobs: exit 1 } + kubectl rollout status deployment/agentmesh-webapp-${ENV_NAME} -n ${NAMESPACE} --timeout=120s || { + echo "Web app Deployment failed!" + print_rollout_diagnostics "${NAMESPACE}" "deployment/agentmesh-webapp-${ENV_NAME}" "app=agentmesh-webapp-${ENV_NAME}" + exit 1 + } + # Each router is held 90s after it is ready (minReadySeconds) so # members re-attach before the next one goes, which with its # startup is about two minutes a router. The wait follows the diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 4a8953e47..3ef2bedb1 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -49,7 +49,9 @@ jobs: with: node-version: "22" cache: npm - cache-dependency-path: tests/ui/package-lock.json + cache-dependency-path: | + tests/ui/package-lock.json + sdk/js/package-lock.json - name: Run console UI smoke test run: make ui-test diff --git a/.gitignore b/.gitignore index 0edc3dad3..183762b63 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,9 @@ dist/ /agentmesh-box /agentmesh-router /agentmesh-console +/agentmesh-webapp + +/internal/webapp/public/sdk/ # Playwright console UI tests node_modules/ diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 47b98d5ab..a63156d19 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -1,8 +1,9 @@ version: 2 project_name: agentmesh # Deliberately not released: agentmesh-bench (a measurement instrument for people -# working on the mesh, built from the repo, not something operators install) -# and chaos-agent (a Python dev tool). +# working on the mesh, built from the repo, not something operators install), +# chaos-agent (a Python dev tool) and agentmesh-webapp (an image and a Helm +# chart only). builds: - id: agentmesh-node main: ./cmd/agentmesh-node diff --git a/Dockerfile.agentmesh-webapp b/Dockerfile.agentmesh-webapp new file mode 100644 index 000000000..f82071cbe --- /dev/null +++ b/Dockerfile.agentmesh-webapp @@ -0,0 +1,30 @@ +# The web app embeds the SDK bundle; JavaScript and wasm are the same on every platform. +FROM --platform=$BUILDPLATFORM node:22-bookworm-slim@sha256:c3de60bf2f9dd0ac6370e6117950ff62d6e339527e7472301c9c78a017978392 AS sdk-bundle +WORKDIR /src/sdk/js +COPY sdk/js/package.json sdk/js/package-lock.json sdk/js/.npmrc ./ +RUN npm ci --no-fund --no-audit +COPY sdk/js/ ./ +RUN npm run build && npm run bundle:app + +FROM --platform=$BUILDPLATFORM golang:1.27.4@sha256:205c7636d74e0ffbe3d007162df7d74f859f5a8c8322dfb9f907977686c126cf AS builder + +WORKDIR /app +COPY go.mod go.sum ./ +RUN --mount=type=cache,target=/go/pkg/mod go mod download + +COPY . . +COPY --from=sdk-bundle /src/internal/webapp/public/sdk/ internal/webapp/public/sdk/ +ARG VERSION=devel +ARG TARGETOS=linux +ARG TARGETARCH +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/root/.cache/go-build \ + CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -buildvcs=false -ldflags="-X github.com/google/agentmesh/internal/version.Version=${VERSION}" -o /bin/agentmesh-webapp ./cmd/agentmesh-webapp + +FROM gcr.io/distroless/static:nonroot@sha256:8ce6dd87e9823c5b48dcfb2c8604714ccb351ce59607327bcc4957448da279b5 + +COPY --from=builder --chown=nonroot:nonroot /bin/agentmesh-webapp /usr/local/bin/agentmesh-webapp + +USER nonroot:nonroot +EXPOSE 8082 +ENTRYPOINT ["/usr/local/bin/agentmesh-webapp"] diff --git a/Makefile b/Makefile index c1b0c5ec8..6c7f3f594 100644 --- a/Makefile +++ b/Makefile @@ -32,7 +32,14 @@ build: go build -v -ldflags "$(VERSION_LDFLAGS)" -o "$(OUT_DIR)/mcp-client" ./cmd/mcp-client go build -v -ldflags "$(VERSION_LDFLAGS)" -o "$(OUT_DIR)/agentmesh-bench" ./cmd/agentmesh-bench go build -v -ldflags "$(VERSION_LDFLAGS)" -o "$(OUT_DIR)/agentmesh-console" ./cmd/agentmesh-console + go build -v -ldflags "$(VERSION_LDFLAGS)" -o "$(OUT_DIR)/agentmesh-webapp" ./cmd/agentmesh-webapp +# The binaries plus the web app agentmesh-webapp embeds, which needs Node.js 22 and npm. +# build runs in the recipe, not as a prerequisite, so make -j cannot embed before the bundle exists. +.PHONY: all +all: + $(MAKE) app + $(MAKE) build .PHONY: mobile-ffi-host mobile-ffi-android mobile-ffi-android-x86_64 mobile-ffi-ios mobile-ffi mobile-app-apk mobile-app-apk-emulator mobile-app-bundle mobile-ffi-host: @@ -187,8 +194,26 @@ sdk-docs: sdk-test: sdk-js sdk-python go test ./tests/integration -run TestNativeSDK -count=1 -v +# The SDK bundle the web app imports; the next go build of agentmesh-webapp embeds it. +# The relay is the recipe's last output, so a failed relay build leaves the bundle out of date. +APP_SDK_BUNDLE := internal/webapp/public/sdk/agentmesh-relay.mjs + +.PHONY: app app-test +app: $(APP_SDK_BUNDLE) + +$(APP_SDK_BUNDLE): sdk/js/node_modules/.package-lock.json sdk/js/package.json sdk/js/scripts/bundle-browser.mjs \ + $(shell find sdk/js/src sdk/js/webapp -name '*.ts' ! -name '*.test.ts') sdk/js/webapp/index.mjs + cd sdk/js && npm run build && npm run bundle:app + +sdk/js/node_modules/.package-lock.json: sdk/js/package-lock.json + cd sdk/js && npm ci --no-fund --no-audit + +app-test: + node --test internal/webapp/model.test.mjs + .PHONY: ui-test -ui-test: build +ui-test: app-test + $(MAKE) all chmod +x ./tests/ui/run.sh ./tests/ui/run.sh $(if $(WHAT),--grep "$(WHAT)") @@ -235,7 +260,7 @@ helm-lint: exit 1; \ fi; \ fi; \ - $$HELM_BIN lint ./charts/agentmesh && $$HELM_BIN lint ./charts/agentmesh-node --set controlPlaneUrl=http://required-for-lint:8080 + $$HELM_BIN lint ./charts/agentmesh && $$HELM_BIN lint ./charts/agentmesh-node --set controlPlaneUrl=http://required-for-lint:8080 && $$HELM_BIN lint ./charts/agentmesh-webapp # render the chart to bin/chart/ for inspection; pass extra flags via ARGS, e.g. ARGS="--set gateway.enabled=true" .PHONY: helm-template @@ -250,7 +275,7 @@ lint: fmt helm-lint .PHONY: helm-test helm-test: @helm plugin list 2>/dev/null | grep -q '^unittest' || helm plugin install https://github.com/helm-unittest/helm-unittest --version 0.8.2 - helm unittest charts/agentmesh charts/agentmesh-node + helm unittest charts/agentmesh charts/agentmesh-node charts/agentmesh-webapp .PHONY: verify verify: @@ -281,6 +306,9 @@ docker-build-e2e-runtime: docker-build-agentmesh-console: docker build --load --build-arg VERSION="$(VERSION)" -t agentmesh-console:local -f Dockerfile.agentmesh-console . -docker-build: docker-build-control-plane docker-build-router docker-build-node docker-build-one docker-build-mock-oidc docker-build-e2e-runtime docker-build-agentmesh-console +docker-build-agentmesh-webapp: + docker build --load --build-arg VERSION="$(VERSION)" -t agentmesh-webapp:local -f Dockerfile.agentmesh-webapp . + +docker-build: docker-build-control-plane docker-build-router docker-build-node docker-build-one docker-build-mock-oidc docker-build-e2e-runtime docker-build-agentmesh-console docker-build-agentmesh-webapp -.PHONY: docker-build-control-plane docker-build-router docker-build-node docker-build-one docker-build-mock-oidc docker-build-e2e-runtime docker-build-agentmesh-console docker-build +.PHONY: docker-build-control-plane docker-build-router docker-build-node docker-build-one docker-build-mock-oidc docker-build-e2e-runtime docker-build-agentmesh-console docker-build-agentmesh-webapp docker-build diff --git a/charts/agentmesh-webapp/Chart.yaml b/charts/agentmesh-webapp/Chart.yaml new file mode 100644 index 000000000..59d189e70 --- /dev/null +++ b/charts/agentmesh-webapp/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: agentmesh-webapp +description: A Helm chart for deploying Agent Mesh Connect, the web app that puts a browser on any Agent Mesh +type: application +version: 0.2.0 +appVersion: "v0.2.0" diff --git a/charts/agentmesh-webapp/README.md b/charts/agentmesh-webapp/README.md new file mode 100644 index 000000000..17fc9480e --- /dev/null +++ b/charts/agentmesh-webapp/README.md @@ -0,0 +1,36 @@ +# agentmesh-webapp Helm chart + +Deploys Agent Mesh Connect, the web app that puts a browser on an Agent Mesh. +The web app knows no control plane: the person using the page enters one, or +opens a join link that names it. One deployment serves any mesh. + +## Install + +```bash +helm upgrade --install agentmesh-webapp ./charts/agentmesh-webapp --namespace agentmesh-webapp --create-namespace \ + --set image.repository=ghcr.io/google/agentmesh-webapp --set image.tag= +``` + +## Expose it + +Browsers refuse the page's cryptography on plain `http` to any host but +`localhost`, so other devices must reach it over `https`. + +With `gateway.enabled=true` the chart creates a Gateway and an HTTPRoute: + +| Value | Default | Meaning | +| --- | --- | --- | +| `gateway.className` | none, required | The GatewayClass, for example `gke-l7-global-external-managed`. | +| `gateway.path` | `""` | The prefix the page is served under, for example `/node`. Empty serves it at `/`. A prefix needs a GatewayClass that supports `URLRewrite`, and helps only when another route shares the hostname. | +| `gateway.hostnames` | `[]` | The hostnames the route answers. | +| `gateway.listeners` | one `http` listener on port 80 | Put an `https` listener here for other devices. | +| `gateway.addresses`, `gateway.annotations` | empty | Passed to the Gateway as given, for example a static IP or a certificate map. | + +Without the Gateway, route the `` Service, port `8082`, from an +`https` proxy or Gateway you already run. + +## Sign in + +If the mesh's control plane has a sign-in provider, that provider must list +the page's address as a redirect URI and allow its origin. Without that, the +page offers only enrollment tokens. diff --git a/charts/agentmesh-webapp/templates/_helpers.tpl b/charts/agentmesh-webapp/templates/_helpers.tpl new file mode 100644 index 000000000..1f789b7e3 --- /dev/null +++ b/charts/agentmesh-webapp/templates/_helpers.tpl @@ -0,0 +1,51 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "agentmesh-webapp.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "agentmesh-webapp.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "agentmesh-webapp.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "agentmesh-webapp.labels" -}} +helm.sh/chart: {{ include "agentmesh-webapp.chart" . }} +{{ include "agentmesh-webapp.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "agentmesh-webapp.selectorLabels" -}} +app.kubernetes.io/name: {{ include "agentmesh-webapp.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} diff --git a/charts/agentmesh-webapp/templates/deployment.yaml b/charts/agentmesh-webapp/templates/deployment.yaml new file mode 100644 index 000000000..2c5b7fc62 --- /dev/null +++ b/charts/agentmesh-webapp/templates/deployment.yaml @@ -0,0 +1,58 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "agentmesh-webapp.fullname" . }} + labels: + {{- include "agentmesh-webapp.labels" . | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "agentmesh-webapp.selectorLabels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "agentmesh-webapp.selectorLabels" . | nindent 8 }} + spec: + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.podSecurityContext }} + securityContext: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: agentmesh-webapp + image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + {{- with .Values.securityContext }} + securityContext: + {{- toYaml . | nindent 10 }} + {{- end }} + args: + - "--bind-addr=:8082" + ports: + - containerPort: 8082 + name: http + protocol: TCP + readinessProbe: + httpGet: + path: / + port: http + periodSeconds: 5 + livenessProbe: + httpGet: + path: / + port: http + periodSeconds: 15 + resources: + {{- toYaml .Values.resources | nindent 10 }} diff --git a/charts/agentmesh-webapp/templates/gateway.yaml b/charts/agentmesh-webapp/templates/gateway.yaml new file mode 100644 index 000000000..fe711bcd0 --- /dev/null +++ b/charts/agentmesh-webapp/templates/gateway.yaml @@ -0,0 +1,72 @@ +{{- if .Values.gateway.enabled -}} +{{- $fullName := include "agentmesh-webapp.fullname" . -}} +apiVersion: gateway.networking.k8s.io/v1 +kind: Gateway +metadata: + name: {{ $fullName }}-gateway + labels: + {{- include "agentmesh-webapp.labels" . | nindent 4 }} + {{- with .Values.gateway.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + gatewayClassName: {{ required "gateway.className is required when gateway.enabled is true" .Values.gateway.className }} + {{- with .Values.gateway.addresses }} + addresses: + {{- toYaml . | nindent 2 }} + {{- end }} + listeners: + {{- toYaml .Values.gateway.listeners | nindent 2 }} +--- +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: {{ $fullName }}-route + labels: + {{- include "agentmesh-webapp.labels" . | nindent 4 }} +spec: + parentRefs: + - name: {{ $fullName }}-gateway + {{- with .Values.gateway.hostnames }} + hostnames: + {{- toYaml . | nindent 2 }} + {{- end }} + rules: + {{- with .Values.gateway.path }} + # The bare prefix 302s to /, and URLRewrite (Extended conformance) + # strips it, because the web app serves at /. + - matches: + - path: + type: Exact + value: {{ . }} + filters: + - type: RequestRedirect + requestRedirect: + path: + type: ReplaceFullPath + replaceFullPath: {{ . }}/ + statusCode: 302 + - matches: + - path: + type: PathPrefix + value: {{ . }}/ + filters: + - type: URLRewrite + urlRewrite: + path: + type: ReplacePrefixMatch + replacePrefixMatch: / + backendRefs: + - name: {{ $fullName }} + port: {{ $.Values.service.port }} + {{- else }} + - matches: + - path: + type: PathPrefix + value: / + backendRefs: + - name: {{ $fullName }} + port: {{ .Values.service.port }} + {{- end }} +{{- end }} diff --git a/charts/agentmesh-webapp/templates/service.yaml b/charts/agentmesh-webapp/templates/service.yaml new file mode 100644 index 000000000..f892f4826 --- /dev/null +++ b/charts/agentmesh-webapp/templates/service.yaml @@ -0,0 +1,18 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "agentmesh-webapp.fullname" . }} + labels: + {{- include "agentmesh-webapp.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + ports: + - name: http + port: {{ .Values.service.port }} + targetPort: http + {{- if and (eq .Values.service.type "NodePort") .Values.service.nodePort }} + nodePort: {{ .Values.service.nodePort }} + {{- end }} + protocol: TCP + selector: + {{- include "agentmesh-webapp.selectorLabels" . | nindent 4 }} diff --git a/charts/agentmesh-webapp/tests/deployment_test.yaml b/charts/agentmesh-webapp/tests/deployment_test.yaml new file mode 100644 index 000000000..fad335349 --- /dev/null +++ b/charts/agentmesh-webapp/tests/deployment_test.yaml @@ -0,0 +1,20 @@ +suite: deployment +templates: + - templates/deployment.yaml +release: + name: agentmesh-webapp +tests: + - it: runs as the image's numeric nonroot uid + asserts: + - equal: + path: spec.template.spec.securityContext.runAsUser + value: 65532 + + - it: probes the page at /, where the web app serves it + asserts: + - equal: + path: spec.template.spec.containers[0].readinessProbe.httpGet.path + value: / + - equal: + path: spec.template.spec.containers[0].args + value: ["--bind-addr=:8082"] diff --git a/charts/agentmesh-webapp/tests/gateway_test.yaml b/charts/agentmesh-webapp/tests/gateway_test.yaml new file mode 100644 index 000000000..fca4ec931 --- /dev/null +++ b/charts/agentmesh-webapp/tests/gateway_test.yaml @@ -0,0 +1,69 @@ +suite: gateway +templates: + - templates/gateway.yaml +release: + name: agentmesh-webapp +tests: + - it: disabled by default renders nothing + asserts: + - hasDocuments: + count: 0 + + - it: enabling it requires gateway.className + set: + gateway.enabled: true + asserts: + - failedTemplate: + errorPattern: gateway.className is required when gateway.enabled is true + + - it: serves the web app at / when no path is set + set: + gateway.enabled: true + gateway.className: x + documentSelector: + path: kind + value: HTTPRoute + asserts: + - lengthEqual: + path: spec.rules + count: 1 + - equal: + path: spec.rules[0].matches[0].path + value: { type: PathPrefix, value: / } + - notExists: + path: spec.rules[0].filters + - equal: + path: spec.rules[0].backendRefs[0] + value: { name: agentmesh-webapp, port: 8082 } + + - it: a path redirects its bare prefix and strips it before the web app + set: + gateway.enabled: true + gateway.className: x + gateway.path: /node + gateway.hostnames: [mesh.example.com] + documentSelector: + path: kind + value: HTTPRoute + asserts: + - lengthEqual: + path: spec.rules + count: 2 + - equal: + path: spec.hostnames + value: [mesh.example.com] + - equal: + path: spec.rules[0].matches[0].path + value: { type: Exact, value: /node } + - equal: + path: spec.rules[0].filters[0].requestRedirect.path.replaceFullPath + value: /node/ + - equal: + path: spec.rules[1].matches[0].path + value: { type: PathPrefix, value: /node/ } + - equal: + path: spec.rules[1].filters[0].urlRewrite.path + value: { type: ReplacePrefixMatch, replacePrefixMatch: / } + - equal: + path: spec.rules[1].backendRefs[0] + value: { name: agentmesh-webapp, port: 8082 } diff --git a/charts/agentmesh-webapp/values.yaml b/charts/agentmesh-webapp/values.yaml new file mode 100644 index 000000000..0ca5116fa --- /dev/null +++ b/charts/agentmesh-webapp/values.yaml @@ -0,0 +1,51 @@ +image: + repository: agentmesh-webapp + tag: local + pullPolicy: IfNotPresent + +replicaCount: 1 + +nodeSelector: {} +tolerations: [] +affinity: {} +podSecurityContext: + runAsNonRoot: true + # The Dockerfile says "USER nonroot" by name; runAsNonRoot needs the numeric uid. + runAsUser: 65532 + runAsGroup: 65532 + seccompProfile: + type: RuntimeDefault +securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] +resources: + requests: + cpu: 10m + memory: 32Mi + +service: + type: ClusterIP + port: 8082 + nodePort: null + +# A Gateway in front of the web app. Browsers refuse the page's cryptography on +# plain http to any host but localhost, so other devices need an https listener. +gateway: + enabled: false + # Required when enabled. No default: the GatewayClass is provider-specific, e.g. + # cloud-provider-kind in kind, gke-l7-global-external-managed on GKE. + className: "" + # External prefix the web app is served under, e.g. /node. Empty serves it at /. + path: "" + listeners: + - name: http + protocol: HTTP + port: 80 + allowedRoutes: + namespaces: + from: Same + hostnames: [] + addresses: [] + annotations: {} diff --git a/cmd/agentmesh-webapp/main.go b/cmd/agentmesh-webapp/main.go new file mode 100644 index 000000000..1b9bd0eac --- /dev/null +++ b/cmd/agentmesh-webapp/main.go @@ -0,0 +1,77 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// agentmesh-webapp serves the Agent Mesh Connect web app at /. It knows no +// control plane: the person using the page names one. +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "github.com/google/agentmesh/internal/version" + "github.com/google/agentmesh/internal/webapp" +) + +func main() { + var ( + bindAddr = flag.String("bind-addr", "127.0.0.1:8082", "Address to serve the web app on. Loopback by default; to reach other devices put it behind https, because browsers refuse the page's cryptography on plain http to any host but localhost") + showVersion = flag.Bool("version", false, "Print the version and exit") + ) + flag.Parse() + if *showVersion { + fmt.Println(version.String()) + return + } + + if missing := webapp.MissingBundle(); len(missing) > 0 { + log.Printf("WARNING: this binary was built without the web app's SDK bundle (make all builds it); the page tells visitors so instead of enrolling them. Missing: %v", missing) + } + + httpSrv := &http.Server{ + Addr: *bindAddr, + Handler: webapp.Handler(), + // Mitigate Slowloris-style resource exhaustion from slow/malicious clients. + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 120 * time.Second, + } + + go func() { + log.Printf("Agent Mesh web app listening on %s", *bindAddr) + if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("Web app server error: %v", err) + } + }() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + <-ctx.Done() + log.Println("Shutting down the web app server...") + + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := httpSrv.Shutdown(shutdownCtx); err != nil { + log.Fatalf("Server shutdown failed: %v", err) + } +} diff --git a/internal/webapp/app.go b/internal/webapp/app.go new file mode 100644 index 000000000..ae3a136ef --- /dev/null +++ b/internal/webapp/app.go @@ -0,0 +1,158 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package webapp serves Agent Mesh Connect, the web app that puts a browser on the mesh. +package webapp + +import ( + "bytes" + "crypto/sha256" + "embed" + "encoding/hex" + "html" + "io/fs" + "net/http" + "path" + "strings" + "time" + + "github.com/google/agentmesh/internal/version" +) + +//go:embed all:public +var embedded embed.FS + +var bundleFiles = []string{"sdk/index.js", "sdk/biscuit_bg.wasm", "sdk/webmcp-polyfill.js", "sdk/webmcp-relay.js", "sdk/agentmesh-relay.mjs"} + +// contentTypes is a fixed table, not mime.TypeByExtension: the Windows +// registry can map .js to text/plain, and nosniff then blocks the module. +var contentTypes = map[string]string{ + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json", + ".wasm": "application/wasm", + ".png": "image/png", + ".mjs": "text/javascript; charset=utf-8", +} + +// connect-src allows any ws/wss/https host because the person names the control +// plane and the control plane names the routers; WebTransport dials a router as +// https://:. Plain http reaches only a control plane on this computer; +// CSP has no source for an IPv6 literal, so the page takes localhost and 127.0.0.1 only. +// no-cache plus the ETag makes a phone revalidate instead of running stale JS after an upgrade. +var securityHeaders = map[string]string{ + "Content-Security-Policy": "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self'; " + + "img-src 'self'; connect-src 'self' ws: wss: https: http://localhost:* http://127.0.0.1:*; manifest-src 'self'; base-uri 'none'; " + + "form-action 'none'; frame-ancestors 'none'", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Frame-Options": "DENY", + "Cross-Origin-Opener-Policy": "same-origin", + "Cache-Control": "no-cache", +} + +const versionPlaceholder = "__AGENTMESH_VERSION__" + +// Handler serves the app at /. A name not in the embedded tree is a 404, +// with no SPA fallback, so a missing SDK bundle is a failed import the page can +// report rather than HTML parsed as JavaScript. +func Handler() http.Handler { + h, err := newHandler(public(), version.String()) + if err != nil { + panic(err) + } + return h +} + +// MissingBundle names the SDK bundle files this binary lacks, nil when it +// was built with `make all` (or `make app` before go build). +func MissingBundle() []string { + return missingBundle(public()) +} + +func public() fs.FS { + sub, err := fs.Sub(embedded, "public") + if err != nil { + panic(err) + } + return sub +} + +func missingBundle(files fs.FS) []string { + var missing []string + for _, name := range bundleFiles { + if _, err := fs.Stat(files, name); err != nil { + missing = append(missing, name) + } + } + return missing +} + +type asset struct { + body []byte + contentType string + etag string +} + +type handler struct { + assets map[string]asset +} + +func newHandler(files fs.FS, buildVersion string) (*handler, error) { + h := &handler{assets: map[string]asset{}} + err := fs.WalkDir(files, ".", func(name string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + contentType, known := contentTypes[path.Ext(name)] + if entry.IsDir() || !known { + return nil + } + body, err := fs.ReadFile(files, name) + if err != nil { + return err + } + if name == "index.html" { + body = bytes.ReplaceAll(body, []byte(versionPlaceholder), []byte(html.EscapeString(buildVersion))) + } + sum := sha256.Sum256(body) + h.assets[name] = asset{body: body, contentType: contentType, etag: `"` + hex.EncodeToString(sum[:16]) + `"`} + return nil + }) + return h, err +} + +func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + for name, value := range securityHeaders { + w.Header().Set(name, value) + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", "GET, HEAD") + http.Error(w, "Method Not Allowed: the app serves GET and HEAD only", http.StatusMethodNotAllowed) + return + } + name := strings.TrimPrefix(r.URL.Path, "/") + if name == "" { + name = "index.html" + } + a, ok := h.assets[name] + if !ok { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", a.contentType) + w.Header().Set("ETag", a.etag) + http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(a.body)) +} diff --git a/internal/webapp/app_test.go b/internal/webapp/app_test.go new file mode 100644 index 000000000..0cf67df60 --- /dev/null +++ b/internal/webapp/app_test.go @@ -0,0 +1,214 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package webapp + +import ( + "encoding/json" + "fmt" + "image/png" + "io/fs" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "testing/fstest" +) + +func testFiles() fstest.MapFS { + return fstest.MapFS{ + "index.html": {Data: []byte(`
Agent Mesh __AGENTMESH_VERSION__
`)}, + "app.js": {Data: []byte(`import "./model.js";`)}, + "model.js": {Data: []byte(`export {};`)}, + "style.css": {Data: []byte(`body {}`)}, + "manifest.json": {Data: []byte(`{}`)}, + "icon-192.png": {Data: []byte("\x89PNG")}, + "app.js.map": {Data: []byte(`{}`)}, + "sdk/index.js": {Data: []byte(`export const sdk = 1;`)}, + "sdk/biscuit_bg.wasm": {Data: []byte("\x00asm")}, + "sdk/webmcp-polyfill.js": {Data: []byte(`export {};`)}, + "sdk/webmcp-relay.js": {Data: []byte(`(function(){})();`)}, + "sdk/agentmesh-relay.mjs": {Data: []byte(`export {};`)}, + } +} + +func newTestHandler(t *testing.T, files fstest.MapFS) *handler { + t.Helper() + h, err := newHandler(files, "v1.2.3") + if err != nil { + t.Fatalf("newHandler: %v", err) + } + return h +} + +func serve(h http.Handler, method, target string, header http.Header) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, target, nil) + for name, values := range header { + req.Header[name] = values + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +func TestHandlerSetsSecurityHeadersOnEveryResponse(t *testing.T) { + h := newTestHandler(t, testFiles()) + for _, target := range []string{"/", "/app.js", "/missing.js"} { + rec := serve(h, http.MethodGet, target, nil) + csp := rec.Header().Get("Content-Security-Policy") + for _, want := range []string{"default-src 'none'", "script-src 'self' 'wasm-unsafe-eval'", "connect-src 'self' ws: wss: https: http://localhost:* http://127.0.0.1:*;", "frame-ancestors 'none'"} { + if !strings.Contains(csp, want) { + t.Errorf("GET %s Content-Security-Policy = %q, want it to contain %q", target, csp, want) + } + } + for name, want := range map[string]string{"X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "Cache-Control": "no-cache"} { + if got := rec.Header().Get(name); got != want { + t.Errorf("GET %s %s = %q, want %q", target, name, got, want) + } + } + } +} + +func TestHandlerContentTypes(t *testing.T) { + h := newTestHandler(t, testFiles()) + for target, want := range map[string]string{ + "/": "text/html; charset=utf-8", + "/app.js": "text/javascript; charset=utf-8", + "/style.css": "text/css; charset=utf-8", + "/manifest.json": "application/json", + "/sdk/biscuit_bg.wasm": "application/wasm", + "/sdk/agentmesh-relay.mjs": "text/javascript; charset=utf-8", + "/icon-192.png": "image/png", + } { + rec := serve(h, http.MethodGet, target, nil) + if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != want { + t.Errorf("GET %s = %d %q, want 200 %q", target, rec.Code, rec.Header().Get("Content-Type"), want) + } + } +} + +func TestHandlerAnswersRevalidationWith304(t *testing.T) { + h := newTestHandler(t, testFiles()) + first := serve(h, http.MethodGet, "/sdk/index.js", nil) + etag := first.Header().Get("ETag") + if first.Code != http.StatusOK || !strings.HasPrefix(etag, `"`) { + t.Fatalf("GET /sdk/index.js = %d with ETag %q, want 200 with a strong ETag", first.Code, etag) + } + again := serve(h, http.MethodGet, "/sdk/index.js", http.Header{"If-None-Match": {etag}}) + if again.Code != http.StatusNotModified || again.Body.Len() != 0 { + t.Errorf("revalidating with If-None-Match %s = %d with %d bytes, want 304 with none", etag, again.Code, again.Body.Len()) + } +} + +func TestHandlerServesOnlyEmbeddedFiles(t *testing.T) { + h := newTestHandler(t, testFiles()) + for _, target := range []string{"/sdk/", "/../go.mod", "/app.js.map", "/unknown", "/node/"} { + rec := serve(h, http.MethodGet, target, nil) + if rec.Code != http.StatusNotFound || strings.Contains(rec.Body.String(), " { + const peer = "12D3KooWPeerIdThatIsLong1234"; + assert.equal(agentCallTarget("call_remote_tool", { peer_id: peer, tool_name: "mcp://calc/add", arguments: { secret: "x" } }), "mcp://calc/add on 12D3KooW…1234"); + assert.equal(agentCallTarget("describe_remote_tool", { peer_id: "short", tool_name: "mcp://calc/add" }), "mcp://calc/add on short"); + assert.equal(agentCallTarget("find_remote_tools", { service_name: "calc" }), "calc"); + assert.equal(agentCallTarget("find_remote_tools", {}), ""); + assert.equal(agentCallTarget("discover_remote_services", { type: "mcp", name: "calc" }), "mcp calc"); + assert.equal(agentCallTarget("get_mesh_info", {}), ""); + assert.equal(agentCallTarget("call_remote_tool", { peer_id: 7, tool_name: null }), ""); +}); + +test("the prompt saves the relay this page serves with Node alone, runs that copy for the page's origin and carries the pairing token", () => { + const origin = "https://mesh.example.com"; + const appUrl = `${origin}/node/`; + assert.equal(RELAY_FILE, "sdk/agentmesh-relay.mjs"); + assert.equal(RELAY_SCRIPT, "~/.local/share/agentmesh/webapp-relay/relay.mjs"); + const install = relayInstallCommand(appUrl); + assert.ok(install.startsWith('node -e "') && install.endsWith('"'), install); + assert.ok(install.includes("fetch('https://mesh.example.com/node/sdk/agentmesh-relay.mjs')"), install); + assert.ok(install.includes("homedir(),'.local','share','agentmesh','webapp-relay')"), install); + assert.ok(install.includes("r.arrayBuffer()"), "saved byte for byte"); + assert.ok(!/[!$`"]/.test(install.slice('node -e "'.length, -1)), "the script survives bash, PowerShell and cmd quoting"); + assert.deepEqual(relayServer(origin), { + command: "node", + args: [RELAY_SCRIPT, "--widget-origin", origin, "--agent-name", AGENT_NAME_PLACEHOLDER], + }); + assert.deepEqual(JSON.parse(relayServerConfig(origin)).mcpServers["agentmesh-webapp"], relayServer(origin)); + + const prompt = agentPrompt(appUrl, "tok_abc", "23:52"); + assert.ok(prompt.includes(`It runs in my browser at ${appUrl} and`), prompt); + assert.ok(relayInstallCommand(`${origin}/console/node/`).includes("fetch('https://mesh.example.com/console/node/sdk/agentmesh-relay.mjs')"), "a page under a prefix downloads its own copy"); + assert.ok(prompt.includes(` ${install}\n`), prompt); + assert.ok(prompt.includes(` node ${RELAY_SCRIPT} --widget-origin ${origin} --agent-name "${AGENT_NAME_PLACEHOLDER}"\n`), prompt); + assert.ok(prompt.includes("Show me steps 1 and 2 together and ask me once to approve them. Then do every step without asking again."), prompt); + assert.ok(prompt.includes("Call pair_agent from agentmesh-webapp with the token tok_abc. It works once, until 23:52."), prompt); + assert.ok(!relayServerConfig(origin).includes("tok_abc"), "the MCP server's configuration carries no secret"); +}); + +test("the page pairs only through an open, unexpired pairing, and pairing again under a name replaces that agent", () => { + const request = { name: "Claude Code", relay_nonce: "n", proof: "p" }; + const open = { token: "tok", expires: 1_000 }; + assert.deepEqual(pairingRequest(open, request, 999), { token: "tok", request }); + assert.match(pairingRequest(open, request, 1_000).refused, /token expired/); + assert.match(pairingRequest(undefined, request, 0).refused, /No pairing is open/); + assert.match(pairingRequest(open, { token: "tok" }, 0).refused, /cannot pair/); + assert.deepEqual(pairingRequest(open, { ...request, extra: 1 }, 0), { token: "tok", request }); + + const cursor = { name: "Cursor", key_id: "c" }; + const agents = withPairedAgent(withPairedAgent([], { name: "Claude Code", key_id: "old" }), cursor); + assert.deepEqual(withPairedAgent(agents, { name: "Claude Code", key_id: "new" }), [cursor, { name: "Claude Code", key_id: "new" }]); +}); + +test("parseServer accepts https, or http to this computer, as the control plane's base URL", () => { + assert.deepEqual(parseServer(" https://cp.example.com/ "), { server }); + assert.deepEqual(parseServer("https://cp.example.com/mesh/"), { server: "https://cp.example.com/mesh" }); + assert.deepEqual(parseServer("http://localhost:8080"), { server: "http://localhost:8080" }); + assert.deepEqual(parseServer("http://127.0.0.1:8080/"), { server: "http://127.0.0.1:8080" }); + // The page's CSP can name only these two loopback hosts. + assert.match(parseServer("http://[::1]:8080").error, /https/); + assert.match(parseServer("http://127.0.0.2:8080").error, /https/); + assert.match(parseServer("http://cp.example.com").error, /https/); + assert.match(parseServer("http://127.0.0.1.evil.example").error, /https/); + assert.match(parseServer("ftp://cp.example.com").error, /https/); + assert.match(parseServer("https://cp.example.com/?x=1").error, /query/); + assert.match(parseServer("https://user@cp.example.com").error, /user name/); + assert.match(parseServer("cp.example.com").error, /not a valid URL/); + assert.match(parseServer("").error, /Enter the mesh address/); +}); + +test("takeFragmentOffer reads #server=…&token=…, or the token alone for the mesh this device belongs to", () => { + assert.deepEqual(takeFragmentOffer(`#server=${encodeURIComponent(server)}&token=mesh_dev_ab`, undefined), { offer }); + assert.deepEqual(takeFragmentOffer("#server=https://cp.example.com&token=a%2Bb%3Dc", undefined), { offer: { server, token: "a+b=c" } }); + assert.deepEqual(takeFragmentOffer("#token=mesh_dev_ab", server), { offer }); + assert.match(takeFragmentOffer("#token=mesh_dev_ab", undefined).error, /Enter the mesh address/); + assert.match(takeFragmentOffer("#server=http://cp.example.com&token=x", undefined).error, /https/); + assert.match(takeFragmentOffer("#server=https://other.example.com&token=x", server).error, /belongs to the mesh at cp\.example\.com/); + assert.equal(takeFragmentOffer("#other=1", server), undefined); + assert.equal(takeFragmentOffer("", server), undefined); +}); + +test("takeSignInReturn reads the provider's code and state, or its error, from the query", () => { + assert.deepEqual(takeSignInReturn("?code=c1&state=s1"), { code: "c1", state: "s1" }); + assert.deepEqual(takeSignInReturn("?error=access_denied&error_description=The+user+said+no&state=s1"), { error: "The user said no", state: "s1" }); + assert.deepEqual(takeSignInReturn("?error=access_denied"), { error: "access_denied", state: "" }); + assert.equal(takeSignInReturn("?code=c1"), undefined); + assert.equal(takeSignInReturn(""), undefined); +}); + +test("signInUrl asks for a code with PKCE back to the page, for the audience the control plane accepts", () => { + const provider = { authorizationEndpoint: "https://auth.example/auth?prompt=login", clientId: "agentmesh-audience", audience: "agentmesh-audience" }; + const url = new URL(signInUrl(provider, "https://mesh.example/node/", "s1", "ch1")); + assert.equal(url.origin + url.pathname, "https://auth.example/auth"); + assert.deepEqual(Object.fromEntries(url.searchParams), { + prompt: "login", + response_type: "code", + client_id: "agentmesh-audience", + redirect_uri: "https://mesh.example/node/", + scope: "openid email profile", + state: "s1", + code_challenge: "ch1", + code_challenge_method: "S256", + audience: "agentmesh-audience", + }); + const none = new URL(signInUrl({ ...provider, audience: "" }, "https://mesh.example/node/", "s1", "ch1")); + assert.equal(none.searchParams.has("audience"), false); +}); + +test("lockRefusal lets a device join only the mesh it belongs to, or any mesh when it belongs to none", () => { + assert.equal(lockRefusal(server, undefined), undefined); + assert.equal(lockRefusal(server, server), undefined); + assert.equal(lockRefusal("https://other.example.com", server), "This device belongs to the mesh at cp.example.com. Reset device identity to join another mesh."); +}); + +test("a link with only #server=… names the mesh, under the same rules and lock as a join link", () => { + assert.deepEqual(takeFragmentOffer("#server=https://cp.example.com/", undefined), { server }); + assert.deepEqual(takeFragmentOffer("#server=https://cp.example.com&token=", undefined), { server }); + assert.match(takeFragmentOffer("#server=http://cp.example.com", undefined).error, /https/); + assert.match(takeFragmentOffer("#server=https://other.example.com", server).error, /belongs to the mesh at cp\.example\.com/); + assert.equal(takeFragmentOffer("#token=", undefined), undefined); +}); + +test("parseOffer takes a mesh://enroll code, a link to this page, or a bare token for the mesh address entered", () => { + const origin = "https://app.example.com"; + const code = `mesh://enroll?server=${encodeURIComponent(server)}&token=mesh_dev_ab`; + assert.deepEqual(parseOffer(code, "", undefined, origin), { offer }); + assert.deepEqual(parseOffer(code, "https://typed.example.com", undefined, origin), { offer }); + assert.deepEqual(parseOffer(" mesh_dev_ab \n", "https://cp.example.com/", undefined, origin), { offer }); + assert.deepEqual(parseOffer(`https://app.example.com/#server=${server}&token=mesh_dev_ab`, "", undefined, origin), { offer }); + assert.deepEqual(parseOffer("https://app.example.com/#token=mesh_dev_ab", server, undefined, origin), { offer }); + assert.match(parseOffer("https://other.example.com/#token=mesh_dev_ab", server, undefined, origin).error, /other\.example\.com/); + assert.match(parseOffer("https://app.example.com/", server, undefined, origin).error, /no token/); + assert.match(parseOffer("mesh_dev_ab", "", undefined, origin).error, /Enter the mesh address/); + assert.match(parseOffer("mesh_dev_ab", "http://cp.example.com", undefined, origin).error, /https/); + assert.match(parseOffer("mesh://enroll?server=http%3A%2F%2Fcp.example.com&token=x", "", undefined, origin).error, /https/); + assert.match(parseOffer("mesh://enroll?token=x", server, undefined, origin).error, /Enter the mesh address/); + assert.match(parseOffer("mesh://other?server=https%3A%2F%2Fcp.example.com&token=x", "", undefined, origin).error, /enrollment code/); + assert.match(parseOffer("", server, undefined, origin).error, /Paste/); + assert.match(parseOffer("mesh dev ab", server, undefined, origin).error, /token/); +}); + +test("a device that belongs to a mesh takes offers for that mesh only, whatever the address field says", () => { + const origin = "https://app.example.com"; + assert.deepEqual(parseOffer("mesh_dev_ab", "https://typed.example.com", server, origin), { offer }); + assert.deepEqual(parseOffer(`mesh://enroll?server=${encodeURIComponent(server)}&token=mesh_dev_ab`, "", server, origin), { offer }); + const other = "mesh://enroll?server=https%3A%2F%2Fother.example.com&token=x"; + assert.match(parseOffer(other, "", server, origin).error, /belongs to the mesh at cp\.example\.com\. Reset device identity/); + assert.match(parseOffer("https://app.example.com/#server=https://other.example.com&token=x", "", server, origin).error, /belongs to/); +}); + +test("parseLabels checks the key=value shape and leaves the rest to the control plane", () => { + assert.deepEqual(parseLabels(" region=eu-west-1, tier=a "), { labels: { region: "eu-west-1", tier: "a" } }); + assert.deepEqual(parseLabels(""), { labels: {} }); + for (const bad of ["x", "=v", "k=", "a=1,a=2"]) { + assert.ok("error" in parseLabels(bad), `parseLabels(${JSON.stringify(bad)}) accepted a malformed label`); + } +}); + +test("classify maps errors by name and status", () => { + const cp = (status) => ({ name: "ControlPlaneError", status }); + const cases = [ + [{ name: "NotEnrolledError" }, "notEnrolled"], + [{ name: "AbortError" }, "aborted"], + [cp(400), "refused"], + [cp(401), "refused"], + [cp(403), "banned"], + [cp(500), "transient"], + [cp(503), "transient"], + [{ name: "EnrollmentRejectedError" }, "refused"], + [new TypeError("Failed to fetch"), "transient"], + [new Error("no router admitted this member"), "transient"], + [undefined, "transient"], + ]; + for (const [err, want] of cases) { + assert.equal(classify(err), want, `classify(${JSON.stringify(err)})`); + } +}); + +test("shouldRefreshBeforeJoin refreshes a lapsing credential and probes once, on attempt 2", () => { + const now = 1_000_000_000_000; + const fresh = now / 1000 + 3600; + assert.equal(shouldRefreshBeforeJoin(fresh, now, 1), false); + assert.equal(shouldRefreshBeforeJoin(now / 1000 + 4 * 60, now, 1), true); + assert.equal(shouldRefreshBeforeJoin(now / 1000 - 86_400, now, 1), true); + assert.equal(shouldRefreshBeforeJoin(fresh, now, 2), true); + assert.equal(shouldRefreshBeforeJoin(fresh, now, 3), false); +}); + +test("retryDelayMs backs off from 2 s to a 60 s cap", () => { + assert.deepEqual([1, 2, 3, 10].map(retryDelayMs), [2_000, 4_000, 8_000, 60_000]); +}); + +const transitions = [ + ["boot", { kind: "boot" }, { type: "blocked", why: "bundle" }, { kind: "blocked", why: "bundle", detail: undefined }], + ["first launch", { kind: "boot" }, { type: "booted", online: true }, { kind: "welcome", offer: undefined }], + ["first launch from a scanned link", { kind: "boot" }, { type: "booted", online: true, offer }, { kind: "welcome", offer }], + ["launch, left running", { kind: "boot" }, { type: "booted", peerId, online: true }, { kind: "joining", peerId, attempt: 1, offer: undefined }], + ["launch, left stopped", { kind: "boot" }, { type: "booted", peerId, online: false }, { kind: "stopped", peerId }], + ["back from a sign-in", { kind: "boot" }, { type: "booted", online: true, offer: signedIn }, { kind: "enrolling", offer: signedIn }], + ["back from a sign-in on a refused device", { kind: "boot" }, { type: "booted", peerId, online: false, offer: signedIn }, { kind: "enrolling", offer: signedIn }], + ["launch, left stopped, from a scanned link", { kind: "boot" }, { type: "booted", peerId, online: false, offer }, { kind: "joining", peerId, attempt: 1, offer }], + ["use here", { kind: "blocked", why: "elsewhere" }, { type: "useHere" }, { kind: "boot", steal: true }], + ["pasted code", { kind: "welcome" }, { type: "offer", offer }, { kind: "welcome", offer }], + ["dialog cancelled", { kind: "welcome", offer }, { type: "dismiss" }, { kind: "welcome" }], + ["dialog confirmed", { kind: "welcome", offer }, { type: "confirm" }, { kind: "enrolling", offer }], + ["enrolled", { kind: "enrolling", offer }, { type: "enrolled", peerId }, { kind: "joining", peerId, attempt: 1 }], + ["enrollment refused", { kind: "enrolling", offer }, { type: "failed", failure: "refused", message: "HTTP 401" }, { kind: "welcome", status: "Enrollment failed: HTTP 401" }], + ["enrollment cancelled", { kind: "enrolling", offer }, { type: "cancel" }, { kind: "welcome", status: "Enrollment cancelled." }], + ["start", { kind: "stopped", peerId }, { type: "start" }, { kind: "joining", peerId, attempt: 1 }], + ["code on a refused device", { kind: "stopped", peerId, refused: true }, { type: "offer", offer }, { kind: "stopped", peerId, refused: true, offer }], + ["rejoin confirmed", { kind: "stopped", peerId, refused: true, offer }, { type: "confirm" }, { kind: "enrolling", offer }], + ["rejoin cancelled", { kind: "stopped", peerId, refused: true, offer }, { type: "dismiss" }, { kind: "stopped", peerId, refused: true, offer: undefined }], + ["joined", { kind: "joining", peerId, attempt: 1 }, { type: "joined", stats }, { kind: "online", peerId, stats, status: undefined }], + ["join fails on the network", { kind: "joining", peerId, attempt: 2 }, { type: "failed", failure: "transient", message: "offline" }, { kind: "reconnecting", peerId, attempt: 2, offer: undefined, status: "offline" }], + ["stop while joining", { kind: "joining", peerId, attempt: 1 }, { type: "stop" }, { kind: "stopped", peerId }], + ["stats", { kind: "online", peerId, stats }, { type: "stats", stats, at: 1 }, { kind: "online", peerId, stats, emptySince: undefined }], + ["page hidden and restored", { kind: "online", peerId, stats }, { type: "lost", message: "left the page" }, { kind: "reconnecting", peerId, attempt: 1, status: "left the page" }], + ["stop", { kind: "online", peerId, stats }, { type: "stop" }, { kind: "stopped", peerId }], + ["retry", { kind: "reconnecting", peerId, attempt: 1, status: "x" }, { type: "retry" }, { kind: "joining", peerId, attempt: 2, offer: undefined }], + ["stop while reconnecting", { kind: "reconnecting", peerId, attempt: 3, status: "x" }, { type: "stop" }, { kind: "stopped", peerId }], + ["unenroll", { kind: "online", peerId, stats }, { type: "unenroll", keepIdentity: true }, { kind: "forgetting", peerId, keepIdentity: true }], + ["reset while joining", { kind: "joining", peerId, attempt: 1 }, { type: "unenroll", keepIdentity: false }, { kind: "forgetting", peerId, keepIdentity: false }], + ["unenroll while stopped", { kind: "stopped", peerId }, { type: "unenroll", keepIdentity: true }, { kind: "forgetting", peerId, keepIdentity: true }], + ["unenroll while reconnecting", { kind: "reconnecting", peerId, attempt: 1, status: "x" }, { type: "unenroll", keepIdentity: true }, { kind: "forgetting", peerId, keepIdentity: true }], + ["unenrolled", { kind: "forgetting", peerId, keepIdentity: true }, { type: "forgotten", keepIdentity: true }, { kind: "welcome", status: "Unenrolled; the Node ID is kept." }], + ["reset", { kind: "forgetting", peerId, keepIdentity: false }, { type: "forgotten", keepIdentity: false }, { kind: "welcome", status: "Device identity reset." }], + ["unenroll fails", { kind: "forgetting", peerId, keepIdentity: true }, { type: "failed", failure: "transient", message: "quota" }, { kind: "stopped", peerId, status: "Could not unenroll: quota" }], + ["reset a kept key from the welcome view", { kind: "welcome" }, { type: "unenroll", keepIdentity: false }, { kind: "forgetting", keepIdentity: false }], + ["no unenroll that keeps the key from the welcome view", { kind: "welcome" }, { type: "unenroll", keepIdentity: true }, { kind: "welcome" }], + ["reset from the welcome view", { kind: "forgetting", keepIdentity: false }, { type: "forgotten", keepIdentity: false }, { kind: "welcome", status: "Device identity reset." }], + ["reset from the welcome view fails", { kind: "forgetting", keepIdentity: false }, { type: "failed", failure: "transient", message: "quota" }, { kind: "welcome", status: "Could not unenroll: quota" }], +]; + +test("reduce: one row per transition", () => { + for (const [name, state, event, want] of transitions) { + assert.deepEqual(reduce(state, event), want, name); + } +}); + +const states = [ + { kind: "boot" }, + { kind: "blocked", why: "bundle" }, + { kind: "blocked", why: "elsewhere" }, + { kind: "welcome" }, + { kind: "welcome", offer }, + { kind: "enrolling", offer }, + { kind: "stopped", peerId }, + { kind: "stopped", peerId, refused: true, offer }, + { kind: "joining", peerId, attempt: 1 }, + { kind: "online", peerId, stats }, + { kind: "reconnecting", peerId, attempt: 1, status: "x" }, + { kind: "forgetting", peerId, keepIdentity: true }, + { kind: "forgetting", keepIdentity: false }, +]; +const events = [ + { type: "blocked", why: "storage" }, + { type: "booted", peerId, online: true }, + { type: "useHere" }, + { type: "offer", offer }, + { type: "dismiss" }, + { type: "confirm" }, + { type: "cancel" }, + { type: "enrolled", peerId }, + { type: "start" }, + { type: "stop" }, + { type: "joined", stats }, + { type: "failed", failure: "transient", message: "x" }, + { type: "failed", failure: "aborted", message: "x" }, + { type: "stats", stats, at: 1 }, + { type: "lost", message: "x" }, + { type: "retry" }, + { type: "unenroll", keepIdentity: true }, + { type: "unenroll", keepIdentity: false }, + { type: "forgotten", keepIdentity: true }, +]; + +const takes = { + boot: ["blocked", "booted"], + blocked: [], + welcome: ["offer", "dismiss", "confirm", "unenroll"], + enrolling: ["enrolled", "failed", "cancel"], + stopped: ["start", "offer", "dismiss", "confirm", "unenroll"], + joining: ["joined", "failed", "stop", "offer", "unenroll"], + online: ["stats", "lost", "stop", "offer", "unenroll"], + reconnecting: ["retry", "stop", "offer", "unenroll"], + forgetting: ["forgotten", "failed"], +}; + +function taken(state, event) { + if (state.kind === "blocked") return state.why === "elsewhere" && event.type === "useHere"; + if (event.type === "failed" && event.failure === "aborted") return false; + if ((event.type === "confirm" || event.type === "dismiss") && !state.offer) return false; + // The welcome view only resets a kept key; there is no credential to unenroll. + if (state.kind === "welcome" && event.type === "unenroll") return !event.keepIdentity; + return takes[state.kind].includes(event.type); +} + +test("reduce returns the same object for every event a state does not take", () => { + for (const state of states) { + for (const event of events) { + const next = reduce(state, event); + if (taken(state, event)) { + assert.notEqual(next, state, `${state.kind} ignored ${JSON.stringify(event)}`); + } else { + assert.equal(next, state, `${JSON.stringify(state)} took ${JSON.stringify(event)} and became ${JSON.stringify(next)}`); + } + } + } +}); + +test("losing the Web Lock ends whatever this window was doing", () => { + for (const state of states) { + assert.deepEqual(reduce(state, { type: "stolen" }), { kind: "blocked", why: "elsewhere" }, state.kind); + } +}); + +test("a join that finishes after Stop is dropped", () => { + const stopped = reduce({ kind: "joining", peerId, attempt: 1 }, { type: "stop" }); + assert.equal(reduce(stopped, { type: "joined", stats }), stopped); +}); + +test("a scanned code on an enrolled device rides along and is reported unused when the join works", () => { + const joining = reduce({ kind: "boot" }, { type: "booted", peerId, online: true, offer }); + const online = reduce(joining, { type: "joined", stats }); + assert.equal(online.kind, "online"); + assert.match(online.status, /already enrolled/); + assert.match(reduce({ kind: "online", peerId, stats }, { type: "offer", offer }).status, /already enrolled/); +}); + +test("a refusal while joining with a scanned code opens the dialog for it", () => { + const stopped = reduce({ kind: "joining", peerId, attempt: 2, offer }, { type: "failed", failure: "refused", message: "HTTP 401" }); + assert.deepEqual(stopped, { kind: "stopped", peerId, refused: true, offer, status: stopped.status }); + assert.match(stopped.status, /Rejoin below; the Node ID stays the same/); + assert.equal(reduce(stopped, { type: "confirm" }).kind, "enrolling"); + const banned = reduce({ kind: "joining", peerId, attempt: 1 }, { type: "failed", failure: "banned", message: "HTTP 403" }); + assert.match(banned.status, /banned/); +}); + +test("online reports a lost session only after the SDK's recovery window passed with no router", () => { + let state = { kind: "online", peerId, stats }; + state = reduce(state, { type: "stats", stats: noRouters, at: 1_000 }); + assert.equal(state.kind, "online"); + state = reduce(state, { type: "stats", stats: noRouters, at: 1_000 + ROUTER_LOSS_GRACE_MS - 1 }); + assert.equal(state.kind, "online", "reported lost while the SDK could still re-admit a router"); + state = reduce(state, { type: "stats", stats, at: 1_000 + ROUTER_LOSS_GRACE_MS }); + assert.equal(state.emptySince, undefined, "a router coming back resets the window"); + state = reduce(state, { type: "stats", stats: noRouters, at: 50_000 }); + state = reduce(state, { type: "stats", stats: noRouters, at: 50_000 + ROUTER_LOSS_GRACE_MS }); + assert.deepEqual(state, { kind: "reconnecting", peerId, attempt: 1, status: "No router holds this device any more." }); +}); + +function recordingMachine(initial, held = {}) { + const log = []; + const machine = createMachine(initial, { + async enter(state, signal) { + log.push(`enter ${state.kind}`); + if (held[state.kind]) await held[state.kind]; + log.push(`settled ${state.kind}${signal.aborted ? " (aborted)" : ""}`); + }, + leave(prev) { + log.push(`leave ${prev.kind}`); + }, + changed() {}, + }); + return { machine, log }; +} + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +test("unenroll waits for the join's refresh to settle before it forgets", async () => { + let refreshLands; + const { machine, log } = recordingMachine({ kind: "joining", peerId, attempt: 1 }, { joining: new Promise((resolve) => (refreshLands = resolve)) }); + await flush(); + machine.dispatch({ type: "unenroll", keepIdentity: true }); + await flush(); + assert.equal(machine.state.kind, "forgetting"); + assert.deepEqual(log, ["enter joining"], "forget started while the refresh could still save the credential"); + refreshLands(); + await flush(); + assert.deepEqual(log, ["enter joining", "settled joining (aborted)", "leave joining", "enter forgetting", "settled forgetting"]); +}); + +test("a kind left before its effect started never runs it", async () => { + let refreshLands; + const { machine, log } = recordingMachine({ kind: "joining", peerId, attempt: 1 }, { joining: new Promise((resolve) => (refreshLands = resolve)) }); + await flush(); + machine.dispatch({ type: "stop" }); + machine.dispatch({ type: "start" }); + refreshLands(); + await flush(); + assert.deepEqual(log, ["enter joining", "settled joining (aborted)", "leave joining", "leave stopped", "enter joining", "settled joining"]); +}); + +test("one pairing token pairs one agent, even when two requests overlap while the page checks them", async () => { + let open = { token: "tok", expires: 1_000 }; + const pairing = { read: () => open, spend: () => (open = undefined) }; + const answer = async (_token, request) => { + await new Promise((resolve) => setTimeout(resolve, 5)); + return request.name; + }; + const results = await Promise.allSettled([ + pairWithToken(pairing, { name: "Claude Code", relay_nonce: "a", proof: "p" }, 0, answer), + pairWithToken(pairing, { name: "Cursor", relay_nonce: "b", proof: "p" }, 0, answer), + ]); + assert.deepEqual(results.map((result) => result.status), ["fulfilled", "rejected"]); + assert.equal(results[0].value, "Claude Code"); + assert.match(results[1].reason.message, /already used or replaced/); + await assert.rejects(pairWithToken(pairing, { name: "Cursor", relay_nonce: "c", proof: "p" }, 0, answer), /No pairing is open/); +}); diff --git a/internal/webapp/package.json b/internal/webapp/package.json new file mode 100644 index 000000000..e986b24bb --- /dev/null +++ b/internal/webapp/package.json @@ -0,0 +1,4 @@ +{ + "private": true, + "type": "module" +} diff --git a/internal/webapp/public/app.js b/internal/webapp/public/app.js new file mode 100644 index 000000000..5cc7849e1 --- /dev/null +++ b/internal/webapp/public/app.js @@ -0,0 +1,931 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Strings from the network reach the DOM through textContent only. +import { NODE_SHORT_TITLE, NODE_TITLE, classify, createMachine, lockRefusal, parseLabels, parseOffer, parseServer, agentCallTarget, agentPrompt, pairWithToken, relayInstallCommand, relayServerConfig, withPairedAgent, retryDelayMs, shouldRefreshBeforeJoin, signInUrl, takeFragmentOffer, takeSignInReturn } from "./model.js"; + +// The provider's answer to a sign-in arrives in the query; strip it as the token below. +let signInReturn = takeSignInReturn(location.search); +if (signInReturn !== undefined) history.replaceState(history.state, "", location.pathname + location.hash); + +// Read before the first await. +let fragment = takeFragment(); + +/** Reads and strips the fragment: replaceState rewrites this history entry, so the address bar, Back and an install no longer carry its token. */ +function takeFragment() { + const hash = location.hash; + if (hash !== "") history.replaceState(history.state, "", location.pathname + location.search); + return hash; +} + +const STATE_DIR = "app"; +const LOCK_NAME = "agentmesh-app"; +const PREFS_KEY = "agentmesh-app.prefs"; +const AGENTS_KEY = "agentmesh-app.agents"; +const PAIRING_KEY = "agentmesh-app.pairing"; +const SIGN_IN_KEY = "agentmesh-app.sign-in"; +const SIGN_IN_TIMEOUT_MS = 15_000; +const PAIRING_TTL_MS = 10 * 60_000; +// The relay's page script probes a closed relay every 2 min only; an agent restarts in less. +const RELAY_WAKE_MS = 5_000; +const POLL_MS = 3_000; +// The page may be served under a prefix, so its own files resolve from its address. +const APP_URL = new URL(".", location.href).href; +// A phone has no local agent to serve. +const AGENT_CAPABLE = matchMedia("(any-pointer: fine)").matches; +const serverInput = /** @type {HTMLInputElement} */ (document.getElementById("server-input")); + +/** @type {any} */ +let sdk; +/** @type {any} */ +let mesh; +/** @type {any} */ +let session; +/** @type {AbortController | undefined} */ +let agentTools; +/** @type {Promise | undefined} */ +let agentBridge; +// Every call from a paired agent runs here, signed with its key. +/** @type {{ tool: string, agent: string, target: string, at: number }[]} */ +let agentCalls = []; +let agentCallCount = 0; +/** @type {any} */ +let agentVerifier; +/** @type {ReturnType | undefined} */ +let pairingTimer; +/** @type {boolean | undefined} */ +let storagePersisted; +// The mesh's sign-in provider, once /info names one and its discovery document loads. +/** @type {{ server: string, host: string, authorizationEndpoint: string, tokenEndpoint: string, clientId: string, audience: string } | undefined} */ +let signIn; +/** @type {AbortController | undefined} */ +let signInLookup; +/** @type {string | undefined} */ +let signInError; +let selectedTab = "dashboard"; + +const machine = createMachine({ kind: "boot" }, { enter, leave, changed }); +/** @param {import("./model.js").AppEvent} event */ +const dispatch = (event) => machine.dispatch(event); + +/** @param {import("./model.js").AppState} state @param {AbortSignal} signal */ +function enter(state, signal) { + /** @param {import("./model.js").AppEvent} event */ + const send = (event) => { + if (!signal.aborted) dispatch(event); + }; + switch (state.kind) { + case "boot": + return boot(state.steal === true, send); + // Only the welcome and rejoin views offer Sign in, so only they ask the provider. + // Not awaited: the machine waits for an effect before it leaves a view, and a silent provider must not hold a join. + case "welcome": + return void lookUpSignIn(); + case "stopped": + return void (state.refused && lookUpSignIn()); + case "enrolling": + return enroll(state.offer, signal, send); + case "joining": + return join(state.attempt, signal, send); + case "online": + return poll(signal); + case "reconnecting": + return wait(retryDelayMs(state.attempt), signal).then(() => send({ type: "retry" })); + case "forgetting": + return forget(state.keepIdentity, send); + } +} + +/** @param {import("./model.js").AppState} prev @param {import("./model.js").AppState} next */ +async function leave(prev, next) { + signInLookup?.abort(); + if (prev.kind === "online") { + const closing = session; + session = undefined; + syncAgentTools(); + await closing?.close(); + } + if (!("peerId" in next)) mesh = undefined; +} + +/** @param {boolean} steal @param {(event: import("./model.js").AppEvent) => void} send */ +async function boot(steal, send) { + if (!isSecureContext) return send({ type: "blocked", why: "insecure" }); + if (!(await holdLock(steal))) return send({ type: "blocked", why: "elsewhere" }); + // zod in the bundle probes eval with new Function, which this page's CSP + // refuses; jitless is zod's own setting, kept where z.config() keeps it. + globalThis.__zod_globalConfig = { ...globalThis.__zod_globalConfig, jitless: true }; + try { + sdk ??= await import("./sdk/index.js"); + } catch (err) { + console.error("[agentmesh-app] the SDK bundle did not load", err); + return send({ type: "blocked", why: "bundle" }); + } + let loaded; + try { + loaded = await sdk.AgentMesh.load({ stateDir: STATE_DIR }); + } catch (err) { + if (classify(err) !== "notEnrolled") return send({ type: "blocked", why: "storage", detail: messageOf(err) }); + } + mesh = loaded; + if (loaded !== undefined) { + keepStorage(); + // The saved credential names its control plane, so the lock follows it, and a link is checked against it below. + writePrefs({ keyKept: true, server: loaded.credential.controlPlaneUrl }); + } + let offer = linkOffer(fragment); + fragment = ""; + if (signInReturn !== undefined) { + const returned = signInReturn; + signInReturn = undefined; + try { + offer = await finishSignIn(returned); + } catch (err) { + signInError = messageOf(err); + } + } + send({ type: "booted", peerId: loaded?.peerId, online: readPrefs().online, offer }); +} + +function holdLock(steal) { + return new Promise((resolve) => { + navigator.locks + .request(LOCK_NAME, steal ? { steal: true } : { ifAvailable: true }, (lock) => { + resolve(lock !== null); + // Held for the life of the page, unless another window steals it. + return lock === null ? undefined : new Promise(() => {}); + }) + .catch(() => dispatch({ type: "stolen" })); + }); +} + +/** @param {import("./model.js").Offer} offer @param {AbortSignal} signal @param {(event: import("./model.js").AppEvent) => void} send */ +async function enroll(offer, signal, send) { + // An offer taken while the device was not yet locked, such as during a cancelled sign-in, is checked again here. + const refused = lockRefusal(offer.server, readPrefs().server); + if (refused !== undefined) return send({ type: "failed", failure: "refused", message: refused }); + const parsed = parseLabels(readPrefs().labels); + if ("error" in parsed) return send({ type: "failed", failure: "refused", message: `${parsed.error} Fix the labels, then join again.` }); + try { + // enroll() resumes a still-valid saved credential and ignores the token. + await sdk.AgentMesh.forget(STATE_DIR, { keepIdentity: true }); + const enrolled = await sdk.AgentMesh.enroll({ + controlPlaneUrl: offer.server, + stateDir: STATE_DIR, + ...("token" in offer ? { bootstrapToken: offer.token } : { jwt: offer.jwt }), + labels: parsed.labels, + signal, + }); + // The SDK saves the credential even after Cancel once the control plane has answered, so the lock follows it, + // and a cancelled view shows the fixed address and Reset. + writePrefs({ keyKept: true, server: offer.server }); + render(machine.state); + if (signal.aborted) return; + mesh = enrolled; + writePrefs({ online: true }); + send({ type: "enrolled", peerId: enrolled.peerId }); + } catch (err) { + send({ type: "failed", failure: classify(err), message: messageOf(err) }); + } +} + +/** + * A join link's offer. A link with only #server=… fills in the mesh address, so that mesh's Sign in shows. + * @param {string} hash @returns {import("./model.js").Offer | undefined} + */ +function linkOffer(hash) { + const taken = takeFragmentOffer(hash, readPrefs().server); + if (taken === undefined) return undefined; + if ("error" in taken) showOfferError(taken.error); + if ("server" in taken) serverInput.value = taken.server; + if (!("offer" in taken)) return undefined; + // A failed join keeps the link's mesh in the field, for the next token. + serverInput.value = taken.offer.server; + return taken.offer; +} + +/** The mesh this device belongs to, or else the valid address in the field. */ +function currentServer() { + const parsed = parseServer(readPrefs().server ?? serverInput.value); + return "server" in parsed ? parsed.server : undefined; +} + +/** Asks the current mesh for its sign-in provider; a new address or leaving the view cancels the last ask. */ +function lookUpSignIn() { + signInLookup?.abort(); + signInLookup = new AbortController(); + signIn = undefined; + const server = currentServer(); + return server === undefined ? undefined : findSignIn(server, signInLookup.signal); +} + +/** + * Shows Sign in when the control plane names a provider whose discovery document this page can read. + * Asked again on every entry, so a provider the operator changed or removed is not offered. + * @param {string} server @param {AbortSignal} signal + */ +async function findSignIn(server, signal) { + /** @type {typeof signIn} */ + let found; + try { + const info = await new sdk.ControlPlaneClient({ url: server }).info(signal); + if (info.oidcIssuer === "") return; + // Bounded as the token request is, so a provider that stops answering is no longer offered. + const res = await fetch(`${info.oidcIssuer.replace(/\/$/, "")}/.well-known/openid-configuration`, { signal: AbortSignal.any([signal, AbortSignal.timeout(SIGN_IN_TIMEOUT_MS)]) }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const discovery = await res.json(); + // OIDC Discovery 1.0 section 4.3: the document must name the issuer that was asked. + if (discovery.issuer !== info.oidcIssuer || typeof discovery.authorization_endpoint !== "string" || typeof discovery.token_endpoint !== "string") { + throw new Error("the discovery document does not name this issuer's endpoints"); + } + found = { + server, + host: new URL(info.oidcIssuer).host, + authorizationEndpoint: discovery.authorization_endpoint, + tokenEndpoint: discovery.token_endpoint, + clientId: info.clientId, + audience: info.audience, + }; + } catch (err) { + if (signal.aborted) return; + // Most often the provider does not allow this origin (CORS); enrollment tokens still work. + console.warn("[agentmesh-app] Sign in is not offered: the sign-in provider did not answer this page", err); + } finally { + if (!signal.aborted) { + signIn = found; + render(machine.state); + } + } +} + +/** 32 random bytes, base64url. */ +const randomText = () => base64url(crypto.getRandomValues(new Uint8Array(32))); + +/** @param {Uint8Array} bytes */ +function base64url(bytes) { + return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} + +/** Leaves for the provider's sign-in page; the PKCE verifier waits in this tab's storage. */ +async function startSignIn() { + if (signIn === undefined) return; + keepStorage(); + const verifier = randomText(); + const state = randomText(); + const challenge = base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)))); + try { + sessionStorage.setItem(SIGN_IN_KEY, JSON.stringify({ state, verifier, server: signIn.server, tokenEndpoint: signIn.tokenEndpoint, clientId: signIn.clientId })); + } catch (err) { + signInError = `This browser did not keep the sign-in: ${messageOf(err)}`; + return render(machine.state); + } + location.assign(signInUrl(signIn, APP_URL, state, challenge)); +} + +/** + * Trades the provider's code for an ID token, only for a sign-in this tab started. + * @param {{ code: string, state: string } | { error: string, state: string }} returned @returns {Promise} + */ +async function finishSignIn(returned) { + let pending; + try { + pending = JSON.parse(sessionStorage.getItem(SIGN_IN_KEY) ?? "null"); + sessionStorage.removeItem(SIGN_IN_KEY); + } catch { + pending = null; + } + if (pending?.state !== returned.state) throw new Error("This sign-in did not start in this tab. Press Sign in again."); + // A failed sign-in comes back to the same mesh, so Sign in shows again. + serverInput.value = pending.server; + if ("error" in returned) throw new Error(`The sign-in failed: ${returned.error}`); + let res; + try { + // Bounded, because boot waits for it before it reports booted. + res = await fetch(pending.tokenEndpoint, { + method: "POST", + body: new URLSearchParams({ grant_type: "authorization_code", code: returned.code, redirect_uri: APP_URL, client_id: pending.clientId, code_verifier: pending.verifier }), + signal: AbortSignal.timeout(SIGN_IN_TIMEOUT_MS), + }); + } catch (err) { + console.warn("[agentmesh-app] the sign-in provider's token endpoint did not answer", err); + throw new Error("The sign-in provider did not answer this page. Press Sign in again, or join with a token."); + } + const body = await res.json().catch(() => ({})); + if (!res.ok || typeof body.id_token !== "string") throw new Error(`The sign-in provider refused the code (HTTP ${res.status}${body.error ? `, ${body.error}` : ""}).`); + return { server: pending.server, jwt: body.id_token }; +} + +/** @param {number} attempt @param {AbortSignal} signal @param {(event: import("./model.js").AppEvent) => void} send */ +async function join(attempt, signal, send) { + try { + if (shouldRefreshBeforeJoin(mesh.credential.expiration, Date.now(), attempt)) { + try { + await mesh.refresh(); + } catch (err) { + // The control plane did not answer: the saved credential may still join. + if (classify(err) !== "transient") throw err; + console.warn("[agentmesh-app] refresh failed; joining with the saved credential", err); + } + } + signal.throwIfAborted(); + const joined = await mesh.join({ signal }); + if (signal.aborted) return void (await joined.close()); + session = joined; + syncAgentTools(); + send({ type: "joined", stats: statsOf(joined) }); + } catch (err) { + send({ type: "failed", failure: classify(err), message: messageOf(err) }); + } +} + +/** @param {AbortSignal} signal */ +async function poll(signal) { + while (!signal.aborted) { + if (document.visibilityState === "visible") report(); + await wait(POLL_MS, signal); + } +} + +function report() { + if (session !== undefined) dispatch({ type: "stats", stats: statsOf(session), at: Date.now() }); +} + +/** @param {boolean} keepIdentity @param {(event: import("./model.js").AppEvent) => void} send */ +async function forget(keepIdentity, send) { + try { + await sdk.AgentMesh.forget(STATE_DIR, { keepIdentity }); + // The mesh stays with the key: only a new identity may join another mesh. + if (!keepIdentity) writePrefs({ keyKept: false, server: undefined }); + mesh = undefined; + signInError = undefined; + writeAgents([]); + setPairing(false); + send({ type: "forgotten", keepIdentity }); + } catch (err) { + send({ type: "failed", failure: classify(err), message: messageOf(err) }); + } +} + +/** @returns {import("./model.js").Stats} */ +function statsOf(joined) { + return { peers: joined.node.getPeers().length, routers: joined.routers.length, expires: joined.mesh.credential.expiration }; +} + +function wait(ms, signal) { + return new Promise((resolve) => { + const done = () => { + clearTimeout(timer); + signal.removeEventListener("abort", done); + resolve(undefined); + }; + const timer = setTimeout(done, ms); + signal.addEventListener("abort", done); + }); +} + +function messageOf(err) { + return err instanceof Error ? err.message : String(err); +} + +function keepStorage() { + navigator.storage?.persist?.().then( + (granted) => { + storagePersisted = granted; + render(machine.state); + }, + () => {}, + ); +} + +/** + * keyKept: this browser holds a key from an earlier enrollment, which the welcome view offers to reset. + * server: the control plane that key belongs to. + * @returns {{ labels: string, online: boolean, agent: boolean, keyKept: boolean, server: string | undefined }} + */ +function readPrefs() { + try { + const saved = JSON.parse(localStorage.getItem(PREFS_KEY) ?? "{}"); + return { + labels: typeof saved.labels === "string" ? saved.labels : "", + online: saved.online !== false, + agent: saved.agent === true, + keyKept: saved.keyKept === true, + server: typeof saved.server === "string" ? saved.server : undefined, + }; + } catch { + return { labels: "", online: true, agent: false, keyKept: false, server: undefined }; + } +} + +/** @param {Partial<{ labels: string, online: boolean, agent: boolean, keyKept: boolean, server: string | undefined }>} patch */ +function writePrefs(patch) { + try { + localStorage.setItem(PREFS_KEY, JSON.stringify({ ...readPrefs(), ...patch })); + } catch (err) { + console.warn("[agentmesh-app] preferences not saved", err); + } +} + +/** @typedef {{ key_id: string, name: string, key: string, paired_time: string }} PairedAgent */ + +/** The agents paired with this page. Only their signed calls run. @returns {PairedAgent[]} */ +function readAgents() { + try { + const saved = JSON.parse(localStorage.getItem(AGENTS_KEY) ?? "[]"); + return Array.isArray(saved) ? saved : []; + } catch { + return []; + } +} + +/** @param {PairedAgent[]} agents */ +function writeAgents(agents) { + try { + localStorage.setItem(AGENTS_KEY, JSON.stringify(agents)); + } catch (err) { + console.warn("[agentmesh-app] paired agents not saved", err); + } +} + +/** The open pairing and its single-use token, kept for this tab across reloads. @returns {{ token: string, expires: number } | undefined} */ +function readPairing() { + try { + const saved = JSON.parse(sessionStorage.getItem(PAIRING_KEY) ?? "null"); + return typeof saved?.token === "string" && typeof saved.expires === "number" ? saved : undefined; + } catch { + return undefined; + } +} + +/** 128 random bits, in hex so an agent copies it without surprises. */ +const newPairingToken = () => Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join(""); + +/** Opens a pairing with a fresh token, or closes it. */ +function setPairing(/** @type {boolean} */ open) { + try { + if (open) sessionStorage.setItem(PAIRING_KEY, JSON.stringify({ token: newPairingToken(), expires: Date.now() + PAIRING_TTL_MS })); + else sessionStorage.removeItem(PAIRING_KEY); + } catch (err) { + console.warn("[agentmesh-app] pairing not saved", err); + } + renewPairingOnExpiry(); +} + +/** Replaces an unused token when it expires, so the prompt on screen always works. */ +function renewPairingOnExpiry() { + clearTimeout(pairingTimer); + const pairing = readPairing(); + if (pairing === undefined) return; + pairingTimer = setTimeout(() => { + setPairing(true); + render(machine.state); + }, Math.max(0, pairing.expires - Date.now())); +} + +/** @param {string} text */ +const toolFailure = (text) => ({ isError: true, content: [{ type: "text", text }] }); + +/** Answers a relay that proves it holds the open pairing's token, and trusts its key from then on. @param {Record} input */ +async function pairAgent(input) { + try { + const { response, agent } = await pairWithToken({ read: readPairing, spend: () => setPairing(false) }, input, Date.now(), sdk.answerPairing); + writeAgents(withPairedAgent(readAgents(), agent)); + console.info(`[agentmesh-app] paired the local agent "${agent.name}"`); + render(machine.state); + return { content: [{ type: "text", text: JSON.stringify(response) }] }; + } catch (err) { + console.warn(`[agentmesh-app] refused to pair a local agent: ${messageOf(err)}`); + return toolFailure(messageOf(err)); + } +} + +/** Offers the node's tools to a local agent while it is connected and the node is online. */ +function syncAgentTools() { + if (!(AGENT_CAPABLE && readPrefs().agent && session !== undefined)) { + agentTools?.abort(); + agentTools = undefined; + return; + } + if (agentTools !== undefined) return; + const controller = (agentTools = new AbortController()); + const joined = session; + agentVerifier ??= new sdk.CallVerifier(readAgents); + if (readAgents().length === 0 && readPairing() === undefined) setPairing(true); + const modelContext = () => /** @type {any} */ (document).modelContext; + const log = { + /** @param {string} tool @param {{ name: string }} agent @param {Record} args */ + called: (tool, agent, args) => agentCalled(tool, agent.name, args), + /** @param {string} tool @param {string} reason */ + refused: (tool, reason) => console.warn(`[agentmesh-app] refused a call to ${tool}: ${reason}`), + }; + const pairTool = { + name: sdk.PAIR_TOOL, + description: "Pairs this agent with the Agent Mesh node in the browser, using the single-use token from the page's prompt. Call it once; the agent then stays paired.", + inputSchema: { type: "object", properties: { token: { type: "string", description: "The token from the prompt." } }, required: ["token"] }, + execute: (/** @type {any} */ input) => pairAgent(input ?? {}), + }; + loadAgentBridge() + .then(async () => { + await modelContext().registerTool(pairTool, { signal: controller.signal }); + await sdk.registerWebMCPTools(modelContext(), sdk.meshTools(joined), agentVerifier, log, controller.signal); + // The page script reconnects on this message, sent as its parent window: the page itself. + const wake = setInterval(() => window.postMessage({ type: "webmcp.connect" }, location.origin), RELAY_WAKE_MS); + controller.signal.addEventListener("abort", () => clearInterval(wake), { once: true }); + }) + .catch((err) => { + if (!controller.signal.aborted) console.warn("[agentmesh-app] the tools were not offered to a local agent", err); + }); +} + +/** @param {string} tool @param {string} agent @param {Record} input */ +function agentCalled(tool, agent, input) { + const target = agentCallTarget(tool, input); + agentCallCount++; + agentCalls = [{ tool, agent, target, at: Date.now() }, ...agentCalls].slice(0, 5); + console.info(`[agentmesh-app] the local agent "${agent}" called ${tool} ${target}`.trimEnd()); + render(machine.state); +} + +/** Loads the WebMCP polyfill, for browsers without WebMCP, and the relay's page script. Neither loads before the agent is connected. */ +function loadAgentBridge() { + agentBridge ??= import("./sdk/webmcp-polyfill.js").then(() => { + // The relay script reads this; without its embed frame, the page itself is the "parent" it serves. + /** @type {any} */ (globalThis).__WEBMCP_RELAY_CONFIG = { hostOrigin: location.origin, hostTitle: document.title, hostUrl: location.origin + location.pathname }; + const script = document.createElement("script"); + script.src = "./sdk/webmcp-relay.js"; + document.head.append(script); + }); + return agentBridge; +} + +/** @param {import("./model.js").AppState} prev @param {import("./model.js").AppEvent} event @param {import("./model.js").AppState} next */ +function changed(prev, event, next) { + // Any enrollment, by token, link or sign-in, replaces an earlier sign-in error. + if (next.kind === "enrolling") signInError = undefined; + if (prev.kind !== next.kind) { + const why = event.type === "failed" || event.type === "lost" ? `: ${event.message}` : ""; + console.info(`[agentmesh-app] ${prev.kind} --${event.type}--> ${next.kind}${why}`); + } + render(next); +} + +/** @param {number} unixSeconds */ +function clock(unixSeconds) { + return new Date(unixSeconds * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); +} + +const $ = (id) => /** @type {HTMLElement} */ (document.getElementById(id)); + +const BLOCKED = { + insecure: "Open this page over https. Put agentmesh-webapp behind an https proxy, Gateway or tunnel.", + elsewhere: "Agent Mesh is open in another tab or window.", + bundle: "This server was built without the app. Rebuild it with make all.", + storage: "This browser does not let the page keep its identity. Leave private browsing and open the link again.", +}; + +/** @param {import("./model.js").AppState} s */ +function render(s) { + const enrolled = "peerId" in s; + // Before enrollment the welcome view is the whole app, labels included. + const tab = enrolled ? selectedTab : "dashboard"; + + for (const name of ["dashboard", "config"]) { + $(`tab-${name}`).hidden = name !== tab; + } + $("nav").hidden = !enrolled; + $("nav").dataset.kind = s.kind; + for (const button of document.querySelectorAll("#nav button")) { + button.toggleAttribute("aria-current", button.dataset.tab === tab); + } + $("tab-dashboard").dataset.kind = s.kind; + $("bar-status").hidden = !enrolled; + $("bar-status").dataset.kind = s.kind; + $("bar-status-text").textContent = NODE_SHORT_TITLE[s.kind] ?? ""; + + $("view-boot").hidden = s.kind !== "boot"; + $("view-blocked").hidden = s.kind !== "blocked"; + if (s.kind === "blocked") { + $("blocked-message").textContent = s.why === "storage" && s.detail ? `${BLOCKED.storage} (${s.detail})` : BLOCKED[s.why]; + $("use-here").hidden = s.why !== "elsewhere"; + $("blocked-icon").setAttribute("href", s.why === "elsewhere" ? "#i-windows" : "#i-alert"); + } + + // A refused device rejoins with a new token, keeping its key and the labels on record. + const rejoin = s.kind === "stopped" && s.refused === true; + $("view-welcome").hidden = s.kind !== "welcome" && s.kind !== "enrolling" && !rejoin; + $("welcome-title").textContent = rejoin ? "Rejoin the mesh" : "Welcome to Agent Mesh"; + $("welcome-text").textContent = + rejoin ? `${signIn ? "Sign in again, paste" : "Paste"} a new enrollment link or token, or clear this device's identity.` + : signIn ? "Sign in with your account, or join with the enrollment link or token the mesh's operator gave you." + : "Enter the mesh's address, then join with the enrollment link or token its operator gave you."; + const locked = readPrefs().server; + if (locked !== undefined) serverInput.value = locked; + serverInput.readOnly = locked !== undefined; + $("sign-in-block").hidden = signIn === undefined || s.kind === "enrolling"; + $("sign-in-label").textContent = signIn ? `Sign in with ${signIn.host}` : ""; + $("sign-in-error").hidden = signInError === undefined; + $("sign-in-error").textContent = signInError ?? ""; + $("labels-field").hidden = rejoin; + $("labels-hint").hidden = rejoin; + // A banned key cannot rejoin, so the rejoin view keeps the way out the dashboard has. + $("rejoin-unenroll").hidden = !rejoin; + $("welcome-reset").hidden = s.kind !== "welcome" || !readPrefs().keyKept; + const enrolling = s.kind === "enrolling"; + $("offer-input").toggleAttribute("disabled", enrolling); + serverInput.toggleAttribute("disabled", enrolling); + $("join-button").toggleAttribute("disabled", enrolling); + $("join-label").textContent = enrolling ? "Joining…" : "Join with token"; + $("cancel-enroll").hidden = !enrolling; + + $("view-node").hidden = !enrolled || rejoin; + if (enrolled) renderNode(s); + + const status = + s.kind === "enrolling" + ? `Enrolling with ${new URL(s.offer.server).host}… If this mesh needs approval, an operator approves this device in the console.` + : "status" in s + ? s.status + : undefined; + $("status").hidden = status === undefined; + $("status").classList.toggle("error", s.kind === "stopped" && s.refused === true); + $("status-text").textContent = status ?? ""; + + const offer = (s.kind === "welcome" || s.kind === "stopped") && s.offer !== undefined ? s.offer : undefined; + const dialog = /** @type {HTMLDialogElement} */ ($("join-dialog")); + if (offer !== undefined) { + $("join-server").textContent = offer.server; + $("join-token").textContent = `${offer.token.slice(0, 12)}…`; + if (!dialog.open) { + dialog.showModal(); + // Opened by a page load, not a tap: focusing Cancel would draw its keyboard focus ring. + dialog.focus(); + } + } else if (dialog.open) { + dialog.close(); + } + + const labels = /** @type {HTMLInputElement} */ ($("labels")); + if (document.activeElement !== labels) labels.value = readPrefs().labels; + labels.toggleAttribute("disabled", enrolling); + $("labels-line").hidden = !enrolled; + $("labels-line").textContent = `Labels: ${readPrefs().labels.trim() || "none"}. To change them, unenroll with Reset device identity, then join again.`; + $("storage-line").textContent = + storagePersisted === undefined + ? "" + : storagePersisted + ? "Storage: kept by the browser." + : "Storage: the browser may clear it. Install the app (Add to Home Screen) to keep this device's identity."; + const agent = AGENT_CAPABLE && readPrefs().agent; + $("agent-card").hidden = !AGENT_CAPABLE; + $("agent-toggle-label").textContent = agent ? "Disconnect local agent" : "Connect a local agent"; + $("agent-toggle").classList.toggle("primary", !agent); + $("agent-toggle").classList.toggle("secondary", agent); + const paired = agent ? readAgents() : []; + const pairing = agent ? readPairing() : undefined; + $("agent-paired").hidden = paired.length === 0; + $("agent-paired").replaceChildren(...paired.map((known) => { + const item = document.createElement("li"); + const label = document.createElement("span"); + label.textContent = `${known.name}, paired ${new Date(known.paired_time).toLocaleString()}`; + const forget = document.createElement("button"); + forget.className = "btn quiet"; + forget.type = "button"; + forget.dataset.keyId = known.key_id; + forget.textContent = "Forget"; + forget.setAttribute("aria-label", `Forget ${known.name}`); + item.append(label, forget); + return item; + })); + $("agent-pair-another").hidden = !agent || pairing !== undefined; + $("agent-pair-another").textContent = paired.length === 0 ? "Pair an agent" : "Pair another agent"; + $("agent-setup").hidden = pairing === undefined; + $("agent-prompt").textContent = pairing === undefined ? "" : agentPrompt(APP_URL, pairing.token, clock(Math.floor(pairing.expires / 1000))); + $("agent-install").textContent = relayInstallCommand(APP_URL); + $("agent-config").textContent = relayServerConfig(location.origin); + const used = agent && agentCallCount > 0; + const lastCall = used ? `last call ${agentCalls[0].tool} at ${clock(Math.floor(agentCalls[0].at / 1000))}` : ""; + $("agent-status").hidden = !agent; + $("agent-status").textContent = + s.kind !== "online" ? "The tools are offered while the node is running." + : used ? `${agentCalls[0].agent}: ${lastCall}, ${agentCallCount} ${agentCallCount === 1 ? "call" : "calls"} so far.` + : pairing !== undefined ? "Waiting for your agent. Paste the prompt into it and follow the instructions." + : "Waiting for a call from a paired agent."; + $("agent-calls").hidden = !used; + $("agent-calls").replaceChildren(...agentCalls.map((call) => { + const item = document.createElement("li"); + item.textContent = `${new Date(call.at).toLocaleTimeString()} ${call.agent}: ${call.tool} ${call.target}`.trimEnd(); + return item; + })); + $("agent-line").hidden = !used; + $("agent-line-text").textContent = used ? `Local agent ${agentCalls[0].agent} connected, ${lastCall}` : ""; + $("credential-line").hidden = s.kind !== "online"; + if (s.kind === "online") { + $("credential-line").textContent = `Credential renews automatically; valid until ${clock(s.stats.expires)}.`; + } +} + +/** @param {Extract} s */ +function renderNode(s) { + const online = s.kind === "online"; + $("node-dot").dataset.kind = s.kind; + $("node-title").textContent = NODE_TITLE[s.kind]; + const server = readPrefs().server; + $("mesh-host").textContent = server === undefined ? "" : new URL(server).host; + $("stat-peers").textContent = online ? String(s.stats.peers) : "–"; + $("stat-routers").textContent = online ? String(s.stats.routers) : "–"; + $("node-id").textContent = s.peerId; + $("start").hidden = s.kind !== "stopped"; + $("stop").hidden = s.kind === "stopped"; + $("stop").toggleAttribute("disabled", s.kind === "forgetting"); + $("unenroll").toggleAttribute("disabled", s.kind === "forgetting"); +} + +// The nav's tab buttons. +for (const button of document.querySelectorAll("[data-tab]")) { + button.addEventListener("click", () => { + selectedTab = /** @type {HTMLElement} */ (button).dataset.tab ?? "dashboard"; + render(machine.state); + }); +} + +$("use-here").addEventListener("click", () => dispatch({ type: "useHere" })); + +for (const button of document.querySelectorAll("[data-copy]")) { + const label = button.getAttribute("aria-label") ?? ""; + const icon = /** @type {SVGUseElement} */ (button.querySelector("use")); + /** @type {ReturnType | undefined} */ + let reset; + /** @param {boolean} copied */ + const show = (copied) => { + button.classList.toggle("done", copied); + button.setAttribute("aria-label", copied ? "Copied" : label); + icon.setAttribute("href", copied ? "#i-check" : "#i-copy"); + }; + button.addEventListener("click", async () => { + const source = $(/** @type {HTMLElement} */ (button).dataset.copy ?? ""); + clearTimeout(reset); + try { + await navigator.clipboard.writeText(source.textContent ?? ""); + } catch (err) { + // Selected, so the person can copy it by hand. + console.warn("[agentmesh-app] copy to the clipboard failed", err); + show(false); + getSelection()?.selectAllChildren(source); + return; + } + show(true); + reset = setTimeout(() => show(false), 1600); + }); +} + +/** @param {string | undefined} message */ +function showOfferError(message) { + $("offer-error").hidden = message === undefined; + $("offer-error").textContent = message ?? ""; +} + +serverInput.addEventListener("change", () => { + const parsed = parseServer(serverInput.value); + $("server-error").hidden = !("error" in parsed) || serverInput.value.trim() === ""; + $("server-error").textContent = "error" in parsed ? parsed.error : ""; + lookUpSignIn(); + render(machine.state); +}); + +$("manual-form").addEventListener("submit", (event) => { + event.preventDefault(); + const input = /** @type {HTMLInputElement} */ ($("offer-input")); + const parsed = parseOffer(input.value, serverInput.value, readPrefs().server, location.origin); + showOfferError("error" in parsed ? parsed.error : undefined); + if ("offer" in parsed) { + input.value = ""; + dispatch({ type: "offer", offer: parsed.offer }); + } +}); +$("cancel-enroll").addEventListener("click", () => dispatch({ type: "cancel" })); +$("sign-in").addEventListener("click", () => { + signInError = undefined; + startSignIn().catch((err) => { + signInError = messageOf(err); + render(machine.state); + }); +}); + +$("join-cancel").addEventListener("click", () => dispatch({ type: "dismiss" })); +$("join-confirm").addEventListener("click", () => { + keepStorage(); + dispatch({ type: "confirm" }); +}); +$("join-dialog").addEventListener("cancel", (event) => { + event.preventDefault(); + dispatch({ type: "dismiss" }); +}); + +$("start").addEventListener("click", () => { + writePrefs({ online: true }); + dispatch({ type: "start" }); +}); +$("stop").addEventListener("click", () => { + writePrefs({ online: false }); + dispatch({ type: "stop" }); +}); + +const unenrollDialog = /** @type {HTMLDialogElement} */ ($("unenroll-dialog")); +$("unenroll").addEventListener("click", () => unenrollDialog.showModal()); +$("rejoin-unenroll").addEventListener("click", () => unenrollDialog.showModal()); +$("welcome-reset").addEventListener("click", () => dispatch({ type: "unenroll", keepIdentity: false })); +$("unenroll-cancel").addEventListener("click", () => unenrollDialog.close()); +$("unenroll-reset").addEventListener("click", () => { + unenrollDialog.close(); + dispatch({ type: "unenroll", keepIdentity: false }); +}); +$("unenroll-confirm").addEventListener("click", () => { + unenrollDialog.close(); + dispatch({ type: "unenroll", keepIdentity: true }); +}); + +$("agent-toggle").addEventListener("click", () => { + const agent = !readPrefs().agent; + writePrefs({ agent }); + if (!agent) { + agentCalls = []; + agentCallCount = 0; + setPairing(false); + } + syncAgentTools(); + render(machine.state); +}); + +$("agent-pair-another").addEventListener("click", () => { + setPairing(true); + render(machine.state); +}); + +$("agent-paired").addEventListener("click", (event) => { + const keyId = /** @type {HTMLElement} */ (event.target).closest("button")?.dataset.keyId; + if (keyId === undefined) return; + writeAgents(readAgents().filter((known) => known.key_id !== keyId)); + console.info("[agentmesh-app] forgot a paired local agent"); + render(machine.state); +}); + +$("labels").addEventListener("input", (event) => { + const text = /** @type {HTMLInputElement} */ (event.target).value; + const parsed = parseLabels(text); + $("labels-error").hidden = !("error" in parsed); + $("labels-error").textContent = "error" in parsed ? parsed.error : ""; + writePrefs({ labels: text }); +}); + +// An installed app receives a scanned link as a fragment-only navigation. +addEventListener("hashchange", () => { + const hash = takeFragment(); + if (hash === "") return; + if (machine.state.kind === "boot" || machine.state.kind === "blocked") return void (fragment = hash); + const offer = linkOffer(hash); + if (offer !== undefined) dispatch({ type: "offer", offer }); + else if (machine.state.kind === "welcome") { + lookUpSignIn(); + render(machine.state); + } +}); +renewPairingOnExpiry(); + +document.addEventListener("visibilitychange", () => { + if (document.visibilityState !== "visible") return; + if (machine.state.kind === "online") { + // A frozen page's relay check is overdue; run the SDK's own recovery now. + session?.keepRelay().catch(() => {}); + report(); + } + if (machine.state.kind === "reconnecting") dispatch({ type: "retry" }); +}); +addEventListener("online", () => { + if (machine.state.kind === "reconnecting") dispatch({ type: "retry" }); +}); +addEventListener("pagehide", () => { + if (machine.state.kind === "online") dispatch({ type: "lost", message: "The page was closed; rejoining." }); +}); + +navigator.storage?.persisted?.().then( + (persisted) => { + storagePersisted = persisted; + render(machine.state); + }, + () => {}, +); + +Object.defineProperty(window, "agentmeshApp", { value: Object.freeze({ get state() { return machine.state; } }) }); + +render(machine.state); diff --git a/internal/webapp/public/apple-touch-icon.png b/internal/webapp/public/apple-touch-icon.png new file mode 100644 index 000000000..983b66765 Binary files /dev/null and b/internal/webapp/public/apple-touch-icon.png differ diff --git a/internal/webapp/public/favicon.png b/internal/webapp/public/favicon.png new file mode 100644 index 000000000..f0c23553f Binary files /dev/null and b/internal/webapp/public/favicon.png differ diff --git a/internal/webapp/public/icon-192.png b/internal/webapp/public/icon-192.png new file mode 100644 index 000000000..ed14f231c Binary files /dev/null and b/internal/webapp/public/icon-192.png differ diff --git a/internal/webapp/public/icon-512.png b/internal/webapp/public/icon-512.png new file mode 100644 index 000000000..cbb2f9d41 Binary files /dev/null and b/internal/webapp/public/icon-512.png differ diff --git a/internal/webapp/public/index.html b/internal/webapp/public/index.html new file mode 100644 index 000000000..8ac3c4726 --- /dev/null +++ b/internal/webapp/public/index.html @@ -0,0 +1,215 @@ + + + + + + + + + + Agent Mesh Connect + + + + + + + + + + +
+

Agent Mesh Connect

+ +
+ +
+
+
+ + + + + + + + +
+ + +
+ + + + +

Join this mesh?

+
+
Control plane
+
Enrollment token
+
+

Enrollment codes admit a limited number of devices for a limited time. The labels from the welcome screen are attested now.

+
+ + +
+
+ + +

Unenroll Node

+

Unenroll disconnects this device from the mesh and deletes its credentials. The Node ID is kept, so re-enrolling brings back the same node.

+

Reset device identity also deletes the key behind the Node ID, so the next enrollment looks like a device the mesh has never seen.

+
+ + + +
+
+ + diff --git a/internal/webapp/public/manifest.json b/internal/webapp/public/manifest.json new file mode 100644 index 000000000..86ad33fc5 --- /dev/null +++ b/internal/webapp/public/manifest.json @@ -0,0 +1,15 @@ +{ + "name": "Agent Mesh Connect", + "short_name": "Agent Mesh", + "id": "./", + "start_url": "./", + "scope": "./", + "display": "standalone", + "launch_handler": { "client_mode": "navigate-existing" }, + "background_color": "#f5f5f7", + "theme_color": "#f5f5f7", + "icons": [ + { "src": "icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "icon-512.png", "sizes": "512x512", "type": "image/png" } + ] +} diff --git a/internal/webapp/public/model.js b/internal/webapp/public/model.js new file mode 100644 index 000000000..a34185339 --- /dev/null +++ b/internal/webapp/public/model.js @@ -0,0 +1,569 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * An enrollment token, or the ID token a sign-in returned, for the control plane at server. + * The token is memory only: never persisted, never logged. + * @typedef {{ server: string, token: string } | { server: string, jwt: string }} Offer + */ + +/** + * expires is the credential's expiry in unix seconds. + * @typedef {{ peers: number, routers: number, expires: number }} Stats + */ + +/** + * @typedef {"insecure" | "elsewhere" | "bundle" | "storage"} BlockedWhy + */ + +/** + * @typedef {{ kind: "boot", steal?: boolean } + * | { kind: "blocked", why: BlockedWhy, detail?: string } + * | { kind: "welcome", offer?: Offer, status?: string } + * | { kind: "enrolling", offer: Offer } + * | { kind: "stopped", peerId: string, refused?: boolean, offer?: Offer, status?: string } + * | { kind: "joining", peerId: string, attempt: number, offer?: Offer } + * | { kind: "online", peerId: string, stats: Stats, emptySince?: number, status?: string } + * | { kind: "reconnecting", peerId: string, attempt: number, offer?: Offer, status: string } + * | { kind: "forgetting", peerId?: string, keepIdentity: boolean } + * } AppState + */ + +/** + * @typedef {"transient" | "refused" | "banned" | "notEnrolled" | "aborted"} Failure + */ + +/** + * @typedef {{ type: "blocked", why: BlockedWhy, detail?: string } + * | { type: "booted", peerId?: string, online: boolean, offer?: Offer } + * | { type: "useHere" } + * | { type: "offer", offer: Offer } + * | { type: "dismiss" } | { type: "confirm" } | { type: "cancel" } + * | { type: "enrolled", peerId: string } + * | { type: "start" } | { type: "stop" } + * | { type: "joined", stats: Stats } + * | { type: "failed", failure: Failure, message: string } + * | { type: "stats", stats: Stats, at: number } + * | { type: "lost", message: string } + * | { type: "retry" } + * | { type: "unenroll", keepIdentity: boolean } + * | { type: "forgotten", keepIdentity: boolean } + * | { type: "stolen" } + * } AppEvent + */ + +const ALREADY_ENROLLED = "This device is already enrolled; the enrollment code was not used."; + +// session.routers drops a router only after the SDK's own redials (2 + 4 + 8 s, +// ROUTER_REDIAL_BACKOFFS_MS); waiting as long again lets its catalog top-up finish. +export const ROUTER_LOSS_GRACE_MS = 14_000; + +/** + * Returns state itself for an event that does not apply, so no effect runs: + * that is how a join that finishes after Stop, or a second click, is dropped. + * @param {AppState} state + * @param {AppEvent} event + * @returns {AppState} + */ +export function reduce(state, event) { + if (event.type === "stolen") return { kind: "blocked", why: "elsewhere" }; + + switch (state.kind) { + case "boot": + if (event.type === "blocked") return { kind: "blocked", why: event.why, detail: event.detail }; + if (event.type === "booted") { + // The person pressed Sign in on this page, so the ID token joins without a second confirmation. + if (event.offer !== undefined && "jwt" in event.offer) return { kind: "enrolling", offer: event.offer }; + if (event.peerId === undefined) return { kind: "welcome", offer: event.offer }; + // A scanned code is intent to be on the mesh; the offer rides along in + // case the control plane refuses the saved credential. + if (event.online || event.offer) return { kind: "joining", peerId: event.peerId, attempt: 1, offer: event.offer }; + return { kind: "stopped", peerId: event.peerId }; + } + return state; + + case "blocked": + return state.why === "elsewhere" && event.type === "useHere" ? { kind: "boot", steal: true } : state; + + case "welcome": + if (event.type === "offer") return { kind: "welcome", offer: event.offer }; + if (event.type === "dismiss" && state.offer) return { kind: "welcome" }; + if (event.type === "confirm" && state.offer) return { kind: "enrolling", offer: state.offer }; + // A key kept from an earlier enrollment may be banned, so the welcome view can still reset it. + if (event.type === "unenroll" && !event.keepIdentity) return { kind: "forgetting", keepIdentity: false }; + return state; + + case "enrolling": + if (event.type === "enrolled") return { kind: "joining", peerId: event.peerId, attempt: 1 }; + if (event.type === "failed" && event.failure !== "aborted") return { kind: "welcome", status: `Enrollment failed: ${event.message}` }; + if (event.type === "cancel") return { kind: "welcome", status: "Enrollment cancelled." }; + return state; + + case "stopped": + if (event.type === "start") return { kind: "joining", peerId: state.peerId, attempt: 1 }; + // Only a refused device takes a new code: the rejoin that keeps the Node ID. + if (event.type === "offer") return state.refused ? { ...state, offer: event.offer } : { ...state, status: ALREADY_ENROLLED }; + if (event.type === "dismiss" && state.offer) return { ...state, offer: undefined }; + if (event.type === "confirm" && state.offer) return { kind: "enrolling", offer: state.offer }; + if (event.type === "unenroll") return forgetting(state, event); + return state; + + case "joining": + if (event.type === "joined") + return { kind: "online", peerId: state.peerId, stats: event.stats, status: state.offer ? ALREADY_ENROLLED : undefined }; + if (event.type === "failed") { + if (event.failure === "aborted") return state; + if (event.failure === "transient") + return { kind: "reconnecting", peerId: state.peerId, attempt: state.attempt, offer: state.offer, status: event.message }; + return { kind: "stopped", peerId: state.peerId, refused: true, offer: state.offer, status: refusal(event) }; + } + if (event.type === "stop") return { kind: "stopped", peerId: state.peerId }; + if (event.type === "offer") return { ...state, offer: event.offer }; + if (event.type === "unenroll") return forgetting(state, event); + return state; + + case "online": + if (event.type === "stats") { + if (event.stats.routers > 0) return { ...state, stats: event.stats, emptySince: undefined }; + const emptySince = state.emptySince ?? event.at; + if (event.at - emptySince >= ROUTER_LOSS_GRACE_MS) + return { kind: "reconnecting", peerId: state.peerId, attempt: 1, status: "No router holds this device any more." }; + return { ...state, stats: event.stats, emptySince }; + } + if (event.type === "lost") return { kind: "reconnecting", peerId: state.peerId, attempt: 1, status: event.message }; + if (event.type === "stop") return { kind: "stopped", peerId: state.peerId }; + if (event.type === "offer") return { ...state, status: ALREADY_ENROLLED }; + if (event.type === "unenroll") return forgetting(state, event); + return state; + + case "reconnecting": + if (event.type === "retry") return { kind: "joining", peerId: state.peerId, attempt: state.attempt + 1, offer: state.offer }; + if (event.type === "stop") return { kind: "stopped", peerId: state.peerId }; + if (event.type === "offer") return { ...state, offer: event.offer }; + if (event.type === "unenroll") return forgetting(state, event); + return state; + + case "forgetting": + if (event.type === "forgotten") return { kind: "welcome", status: event.keepIdentity ? "Unenrolled; the Node ID is kept." : "Device identity reset." }; + if (event.type === "failed" && event.failure !== "aborted") { + const status = `Could not unenroll: ${event.message}`; + return state.peerId === undefined ? { kind: "welcome", status } : { kind: "stopped", peerId: state.peerId, status }; + } + return state; + } + return state; +} + +/** @param {{ peerId: string }} state @param {{ keepIdentity: boolean }} event @returns {AppState} */ +function forgetting(state, event) { + return { kind: "forgetting", peerId: state.peerId, keepIdentity: event.keepIdentity }; +} + +/** @param {{ failure: Failure, message: string }} event */ +function refusal(event) { + return event.failure === "banned" + ? `This device is banned from the mesh (${event.message}).` + : `The mesh no longer accepts this device (${event.message}). Rejoin below; the Node ID stays the same.`; +} + +/** + * A new kind's effect starts only after the old one, aborted, settled and + * leave() returned, so a refresh still landing cannot save a forgotten credential. + * @param {AppState} initial + * @param {{ + * enter: (state: AppState, signal: AbortSignal) => Promise | void, + * leave: (prev: AppState, next: AppState) => Promise | void, + * changed: (prev: AppState, event: AppEvent, next: AppState) => void, + * }} hooks + */ +export function createMachine(initial, { enter, leave, changed }) { + let state = initial; + let controller = new AbortController(); + /** @type {Promise} */ + let running = Promise.resolve(); + let transitions = Promise.resolve(); + /** @param {AppState} next @param {AbortSignal} signal */ + const start = (next, signal) => { + running = Promise.resolve() + .then(() => enter(next, signal)) + .catch((err) => console.error(`[agentmesh-app] ${next.kind} effect failed`, err)); + }; + start(initial, controller.signal); + + return { + get state() { + return state; + }, + /** @param {AppEvent} event */ + dispatch(event) { + const prev = state; + const next = reduce(prev, event); + if (next === prev) return; + state = next; + if (next.kind !== prev.kind) { + controller.abort(); + const { signal } = (controller = new AbortController()); + transitions = transitions.then(async () => { + await running; + try { + await leave(prev, next); + } catch (err) { + console.error(`[agentmesh-app] leaving ${prev.kind} failed`, err); + } + if (!signal.aborted) start(next, signal); + }); + } + changed(prev, event, next); + }, + }; +} + +/** + * The control plane's base URL: https, or http to this computer, because whoever answers it becomes this + * device's trust root. Plain http is narrower than api.ValidateControlPlaneTransport: only the loopback + * hosts the page's CSP can name. + * @param {string} text + * @returns {{ server: string } | { error: string }} + */ +export function parseServer(text) { + const trimmed = text.trim(); + if (trimmed === "") return { error: "Enter the mesh address, for example https://mesh.example.com." }; + let url; + try { + url = new URL(trimmed); + } catch { + return { error: "The mesh address is not a valid URL." }; + } + const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1"; + if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) { + return { error: "The mesh address must start with https:// (http:// only for this computer)." }; + } + if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") { + return { error: "The mesh address is the control plane's address only, with no user name, query or fragment." }; + } + return { server: url.origin + url.pathname.replace(/\/+$/, "") }; +} + +/** + * The offer in a join link's fragment, #server=…&token=…, which never reaches a server. + * Without server= the link joins the mesh this device belongs to; with server= alone it names the mesh. + * @param {string} hash + * @param {string | undefined} lockedServer the control plane this device's identity belongs to + * @returns {{ offer: Offer } | { server: string } | { error: string } | undefined} undefined when the fragment names neither + */ +export function takeFragmentOffer(hash, lockedServer) { + const params = new URLSearchParams(hash.replace(/^#/, "")); + const server = params.get("server"); + if (!params.get("token")?.trim() && server !== null) return serverFor(server, lockedServer); + return fragmentOffer(params, lockedServer ?? "", lockedServer); +} + +/** @param {URLSearchParams} params @param {string} serverText @param {string | undefined} lockedServer */ +function fragmentOffer(params, serverText, lockedServer) { + const token = params.get("token")?.trim(); + return token ? offerFor(params.get("server") ?? serverText, token, lockedServer) : undefined; +} + +/** + * One identity per page origin: the browser keeps one key here, so a device joins one mesh until its identity is reset. + * @param {string} serverText @param {string | undefined} lockedServer + * @returns {{ server: string } | { error: string }} + */ +function serverFor(serverText, lockedServer) { + const parsed = parseServer(serverText); + if ("error" in parsed) return parsed; + const refused = lockRefusal(parsed.server, lockedServer); + return refused === undefined ? parsed : { error: refused }; +} + +/** + * Why an offer for server cannot join a device whose identity belongs to lockedServer, or undefined when it can. + * @param {string} server @param {string | undefined} lockedServer + */ +export function lockRefusal(server, lockedServer) { + if (lockedServer === undefined || server === lockedServer) return undefined; + return `This device belongs to the mesh at ${new URL(lockedServer).host}. Reset device identity to join another mesh.`; +} + +/** @param {string} serverText @param {string} token @param {string | undefined} lockedServer @returns {{ offer: Offer } | { error: string }} */ +function offerFor(serverText, token, lockedServer) { + const found = serverFor(serverText, lockedServer); + return "error" in found ? found : { offer: { server: found.server, token } }; +} + +/** + * What the provider sent back to the page after a sign-in, from the address's query. + * Anyone can craft this address, so nothing in it is trusted before state matches the sign-in this tab started. + * @param {string} search + * @returns {{ code: string, state: string } | { error: string, state: string } | undefined} + */ +export function takeSignInReturn(search) { + const params = new URLSearchParams(search); + const state = params.get("state") ?? ""; + const error = params.get("error"); + if (error !== null) return { error: params.get("error_description") || error, state }; + const code = params.get("code"); + return code && state ? { code, state } : undefined; +} + +/** + * The provider's sign-in page: the authorization code flow with PKCE, back to the page itself. + * @param {{ authorizationEndpoint: string, clientId: string, audience: string }} provider + * @param {string} appUrl the page's own address, which the provider must list as a redirect URI + * @param {string} state @param {string} challenge + */ +export function signInUrl(provider, appUrl, state, challenge) { + const url = new URL(provider.authorizationEndpoint); + const params = { response_type: "code", client_id: provider.clientId, redirect_uri: appUrl, scope: "openid email profile", state, code_challenge: challenge, code_challenge_method: "S256" }; + for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value); + if (provider.audience !== "") url.searchParams.set("audience", provider.audience); + return url.href; +} + +/** + * What the person pasted: a mesh://enroll code (api.EnrollURI), a link to this page with #server=…&token=…, + * or a bare token for the mesh address they entered. + * @param {string} text + * @param {string} serverText the mesh address field + * @param {string | undefined} lockedServer the control plane this device's identity belongs to + * @param {string} origin this page's origin + * @returns {{ offer: Offer } | { error: string }} + */ +export function parseOffer(text, serverText, lockedServer, origin) { + const trimmed = text.trim(); + if (trimmed === "") return { error: "Paste the enrollment link, code or token." }; + const serverOrLocked = lockedServer ?? serverText; + if (/^(mesh|https?):\/\//i.test(trimmed)) { + let url; + try { + url = new URL(trimmed); + } catch { + return { error: "That link is not a valid URL." }; + } + if (url.protocol === "mesh:") { + const token = url.searchParams.get("token")?.trim(); + if (url.host !== "enroll" || !token) return { error: "That code is not a mesh://enroll?server=…&token=… enrollment code." }; + return offerFor(url.searchParams.get("server") ?? "", token, lockedServer); + } + // Another page's storage holds another identity, so its link opens there. + if (url.origin !== origin) return { error: `This link is for the page at ${url.host}. Open the link itself.` }; + return fragmentOffer(new URLSearchParams(url.hash.replace(/^#/, "")), serverOrLocked, lockedServer) ?? { error: "The link carries no token." }; + } + if (/\s|:\/\//.test(trimmed)) return { error: "Paste an enrollment link, a mesh://enroll code or a token." }; + return offerFor(serverOrLocked, trimmed, lockedServer); +} + +/** + * Only the shape is checked here; api.ValidateLabels on the control plane judges the rest. + * @param {string} text + * @returns {{ labels: Record } | { error: string }} + */ +export function parseLabels(text) { + /** @type {Record} */ + const labels = {}; + for (const part of text.split(",")) { + const pair = part.trim(); + if (pair === "") continue; + const eq = pair.indexOf("="); + const key = pair.slice(0, eq).trim(); + const value = pair.slice(eq + 1).trim(); + if (eq < 0 || key === "" || value === "") return { error: `Label "${pair}" is not key=value.` }; + if (Object.hasOwn(labels, key)) return { error: `Label "${key}" is set twice.` }; + labels[key] = value; + } + return { labels }; +} + +/** + * Matches err.name and err.status only, so this module needs no SDK import. + * @param {unknown} err + * @returns {Failure} + */ +export function classify(err) { + const { name, status } = /** @type {{ name?: unknown, status?: unknown }} */ (err ?? {}); + switch (name) { + case "NotEnrolledError": + return "notEnrolled"; + case "AbortError": + return "aborted"; + case "EnrollmentRejectedError": + case "CredentialRetiredError": + return "refused"; + case "ControlPlaneError": + if (status === 403) return "banned"; + if (status === 400 || status === 401) return "refused"; + return "transient"; + } + return "transient"; +} + +/** + * Refresh when the credential lapses, and once on attempt 2, because only /refresh + * says the mesh forgot this device. Not on every retry: each refresh spends the last biscuit. + * @param {number} expires + * @param {number} nowMs + * @param {number} attempt + */ +export function shouldRefreshBeforeJoin(expires, nowMs, attempt) { + return attempt === 2 || expires * 1000 - nowMs < 5 * 60_000; +} + +/** + * @param {number} attempt + */ +export function retryDelayMs(attempt) { + return Math.min(60_000, 2_000 * 2 ** (attempt - 1)); +} + +/** Where the page serves the relay, relative to the page: one file with its dependencies, which sdk/js bundles. */ +export const RELAY_FILE = "sdk/agentmesh-relay.mjs"; +const RELAY_DIRS = [".local", "share", "agentmesh", "webapp-relay"]; +/** Where the relay is saved once, so an agent start runs that copy and fetches nothing. One relay serves one page per computer. */ +export const RELAY_SCRIPT = ["~", ...RELAY_DIRS, "relay.mjs"].join("/"); +/** The relay's argument the agent replaces with its own name, which the page shows in the call log. */ +export const AGENT_NAME_PLACEHOLDER = "YOUR NAME"; + +/** + * Saves, or updates, the relay this page serves. Node itself downloads it, so the command needs nothing but + * Node on any system; no "!", which bash expands. + * @param {string} appUrl the page's own address, ending in "/" + */ +export function relayInstallCommand(appUrl) { + const script = [ + `const p=require('path'),f=require('fs'),d=p.join(require('os').homedir(),${RELAY_DIRS.map((dir) => `'${dir}'`).join(",")});`, + `fetch('${appUrl}${RELAY_FILE}').then(r=>r.ok?r.arrayBuffer():Promise.reject(new Error('HTTP '+r.status)))`, + `.then(b=>{f.mkdirSync(d,{recursive:true});f.writeFileSync(p.join(d,'relay.mjs'),Buffer.from(b))})`, + ].join(""); + return `node -e "${script}"`; +} + +/** The saved relay's MCP server: a program and its arguments, paired with this app's origin only. */ +export function relayServer(origin) { + return { + command: "node", + args: [RELAY_SCRIPT, "--widget-origin", origin, "--agent-name", AGENT_NAME_PLACEHOLDER], + }; +} + +/** The relay's MCP server in the mcpServers form most agents' configuration files take. */ +export function relayServerConfig(origin) { + return JSON.stringify({ mcpServers: { "agentmesh-webapp": relayServer(origin) } }, null, 2); +} + +/** + * What a person pastes into any MCP agent so it installs the relay with their approval, pairs it with this page and checks it. + * @param {string} appUrl the page's own address, ending in "/" @param {string} token single-use pairing token @param {string} until when the token expires, as the page shows it + */ +export function agentPrompt(appUrl, token, until) { + const server = relayServer(new URL(appUrl).origin); + const command = [server.command, ...server.args.map((arg) => (arg.includes(" ") ? `"${arg}"` : arg))].join(" "); + return [ + `Connect yourself to my Agent Mesh node. It runs in my browser at ${appUrl} and offers its tools to agents on this computer through a local relay.`, + "Show me steps 1 and 2 together and ask me once to approve them. Then do every step without asking again. Keep your messages short: say only what you need from me, and the result at the end.", + "", + `1. Save the relay, one JavaScript file from ${appUrl}${RELAY_FILE} that needs Node.js 22 or later, as ${RELAY_SCRIPT} with this command:`, + ` ${relayInstallCommand(appUrl)}`, + `2. Add a local stdio MCP server named "agentmesh-webapp" that runs this command. Write ~ as the absolute path of my home folder, and replace ${AGENT_NAME_PLACEHOLDER} with your product name, such as Claude Code or Cursor:`, + ` ${command}`, + " If my default node is older than 22, run it with npx -y node@22 in place of node.", + " If you cannot change your MCP configuration yourself, tell me exactly what to add and where, and stop until I say it is done.", + "3. If you load new MCP servers only when you start, tell me to restart you and come back to this conversation, and stop until I do.", + `4. Call pair_agent from agentmesh-webapp with the token ${token}. It works once, until ${until}. If pair_agent is not listed yet, wait 10 seconds and list your tools again.`, + "5. Call get_mesh_info from agentmesh-webapp and show me its peer_id. It must match the Node ID my browser shows.", + "", + "Then use find_remote_tools, describe_remote_tool and call_remote_tool from agentmesh-webapp to use tools on my mesh. Your calls run as my node, and only while that browser tab stays open.", + ].join("\n"); +} + +/** + * The pair call the page checks with the open pairing's token, or why the page refuses it before any crypto. + * @param {{ token: string, expires: number } | undefined} pairing the open pairing; a used token leaves none + * @param {Record} input @param {number} nowMs + * @returns {{ token: string, request: { name: string, relay_nonce: string, proof: string } } | { refused: string }} + */ +export function pairingRequest(pairing, input, nowMs) { + if (pairing === undefined) return { refused: "No pairing is open on the page. Press Pair another agent and paste the new prompt." }; + if (pairing.expires <= nowMs) return { refused: "The pairing token expired. Copy a fresh prompt from the page." }; + const { name, relay_nonce, proof } = input; + if (typeof name !== "string" || typeof relay_nonce !== "string" || typeof proof !== "string") { + return { refused: "This relay cannot pair. Download the relay and add the MCP server with the commands from the page's prompt." }; + } + return { token: pairing.token, request: { name, relay_nonce, proof } }; +} + +/** + * Pairs one agent through the open pairing: answer proves the request, then the token is spent in the same + * synchronous step as the check that no other request spent it meanwhile, so one token never pairs two agents. + * @template T + * @param {{ read(): { token: string, expires: number } | undefined, spend(): void }} pairing + * @param {Record} input @param {number} nowMs + * @param {(token: string, request: { name: string, relay_nonce: string, proof: string }) => Promise} answer + * @returns {Promise} + */ +export async function pairWithToken(pairing, input, nowMs, answer) { + const checked = pairingRequest(pairing.read(), input, nowMs); + if ("refused" in checked) throw new Error(checked.refused); + const answered = await answer(checked.token, checked.request); + if (pairing.read()?.token !== checked.token) throw new Error("The pairing token was already used or replaced. Copy a fresh prompt from the page."); + pairing.spend(); + return answered; +} + +/** + * The paired agents after one more pairs: pairing again under a name replaces that agent's key. + * @template {{ name: string }} A @param {A[]} agents @param {A} agent + */ +export function withPairedAgent(agents, agent) { + return [...agents.filter((known) => known.name !== agent.name), agent]; +} + +/** + * What a local agent's tool call aims at, for the page's call log. Never the call's + * arguments, which may carry the agent's data. + * @param {string} tool + * @param {Record} input + */ +export function agentCallTarget(tool, input) { + /** @param {unknown} value */ + const text = (value) => (typeof value === "string" ? value.trim() : ""); + const peerId = text(input.peer_id); + const on = peerId === "" ? "" : `on ${peerId.length > 16 ? `${peerId.slice(0, 8)}…${peerId.slice(-4)}` : peerId}`; + switch (tool) { + case "call_remote_tool": + case "describe_remote_tool": + return [text(input.tool_name), on].filter(Boolean).join(" "); + case "find_remote_tools": + return [text(input.tool_name) || text(input.service_name), on].filter(Boolean).join(" "); + case "discover_remote_services": + return [text(input.type), text(input.name)].filter(Boolean).join(" "); + default: + return ""; + } +} + +export const NODE_TITLE = { + stopped: "Node is Stopped", + joining: "Node is Starting…", + online: "Node is Running", + reconnecting: "Reconnecting…", + forgetting: "Unenrolling…", +}; + +export const NODE_SHORT_TITLE = { + stopped: "Stopped", + joining: "Starting", + online: "Running", + reconnecting: "Reconnecting", + forgetting: "Unenrolling", +}; diff --git a/internal/webapp/public/style.css b/internal/webapp/public/style.css new file mode 100644 index 000000000..4246a6d66 --- /dev/null +++ b/internal/webapp/public/style.css @@ -0,0 +1,467 @@ +:root { + --font: -apple-system, BlinkMacSystemFont, system-ui, "Segoe UI Variable Text", "Segoe UI", Roboto, "Helvetica Neue", sans-serif; + --mono: ui-monospace, "SF Mono", "Cascadia Mono", "Roboto Mono", Menlo, Consolas, monospace; + --bg: #f5f5f7; + --surface: #ffffff; + --surface-2: #f0f0f3; + --surface-3: #e3e3e8; + --hairline: rgba(0, 0, 0, 0.08); + --field-border: #8f8f96; + --text: #1d1d1f; + --text-2: #5a5a62; + --text-3: #6b6b73; + --accent: #4b52d1; + --accent-fill: #4b52d1; + --accent-soft: rgba(75, 82, 209, 0.12); + --on-accent: #ffffff; + --ok: #1f9d55; + --warn: #c98200; + --danger: #c4000f; + --danger-fill: #c4000f; + --danger-soft: rgba(196, 0, 15, 0.08); + --idle: #b4b4bb; + --track: rgba(0, 0, 0, 0.07); + --shadow: 0 1px 2px rgba(0, 0, 0, 0.04), 0 10px 30px -14px rgba(0, 0, 0, 0.12); + --shadow-lg: 0 30px 80px -20px rgba(0, 0, 0, 0.28), 0 2px 8px rgba(0, 0, 0, 0.06); + --scrim: rgba(18, 18, 22, 0.3); + --bar: rgba(250, 250, 252, 0.8); + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #0d0d0f; + --surface: #17171a; + --surface-2: #212125; + --surface-3: #303036; + --hairline: rgba(255, 255, 255, 0.08); + --field-border: #6c6c75; + --text: #f4f4f6; + --text-2: #a7a7b0; + --text-3: #8d8d96; + --accent: #9096ff; + --accent-fill: #555ce0; + --accent-soft: rgba(144, 150, 255, 0.16); + --ok: #34c472; + --warn: #f0b03c; + --danger: #ff6b63; + --danger-fill: #c8333a; + --danger-soft: rgba(255, 107, 99, 0.12); + --idle: #4a4a52; + --track: rgba(255, 255, 255, 0.07); + --shadow: inset 0 1px 0 rgba(255, 255, 255, 0.03), 0 12px 32px -16px rgba(0, 0, 0, 0.7); + --shadow-lg: 0 30px 80px -20px rgba(0, 0, 0, 0.8), inset 0 1px 0 rgba(255, 255, 255, 0.05); + --scrim: rgba(0, 0, 0, 0.55); + --bar: rgba(20, 20, 23, 0.8); + color-scheme: dark; + } +} + +/* Base */ +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; background: var(--bg); } +body { + margin: 0; + min-height: 100dvh; + background: var(--bg); + color: var(--text); + font: 15px/1.5 var(--font); + -webkit-font-smoothing: antialiased; + padding-bottom: calc(76px + env(safe-area-inset-bottom)); +} +[hidden] { display: none !important; } +h1, h2, h3, p, dl, dd { margin: 0; } +h1, h2, h3 { text-wrap: balance; } +.sprite { display: none; } +.icon { + width: 20px; height: 20px; flex: none; + fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; +} +.mono { font-family: var(--mono); } + +/* Header */ +.app-bar { + display: flex; align-items: center; gap: 12px; + max-width: 600px; margin: 0 auto; + padding: calc(env(safe-area-inset-top) + 14px) 20px 6px; + min-height: 60px; +} +/* Inside the Android app the native action bar is the header. */ +.brand { display: flex; align-items: center; gap: 10px; } +.brand-mark { + width: 28px; height: 28px; border-radius: 8px; + display: grid; place-items: center; + background: var(--text); color: var(--bg); +} +.brand-mark .icon { width: 18px; height: 18px; stroke-width: 2; } +.app-bar h1 { font-size: 17px; font-weight: 600; letter-spacing: -0.012em; } +.bar-status { + --c: var(--idle); + margin-left: auto; display: none; align-items: center; gap: 8px; + height: 32px; padding: 0 12px 0 10px; border-radius: 999px; + font-size: 13px; font-weight: 500; color: var(--text-2); + background: var(--surface); border: 1px solid var(--hairline); +} +.bar-status .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--c); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c) 18%, transparent); } +.bar-status[data-kind="online"] { --c: var(--ok); } +.bar-status[data-kind="joining"] { --c: var(--accent); } +.bar-status[data-kind="reconnecting"] { --c: var(--warn); } + +/* Layout: the status line sits under the hero on a node, under the form on the welcome view. */ +main { max-width: 600px; margin: 0 auto; padding: 10px 16px 24px; } +section:not([hidden]) { animation: rise 0.28s cubic-bezier(0.2, 0.8, 0.2, 1); } +#tab-dashboard { + display: grid; gap: 12px; grid-template-columns: minmax(0, 1fr); + grid-template-areas: "main" "status" "details"; +} +#tab-dashboard:is([data-kind="welcome"], [data-kind="enrolling"]) { grid-template-areas: "main" "details" "status"; } +#view-node, #view-welcome { display: contents; } +#view-boot, #view-blocked, .hero, .welcome-intro { grid-area: main; } +.details, .welcome-card { grid-area: details; } +#status { grid-area: status; } +.details { display: grid; gap: 12px; } + +/* Card */ +.card { + background: var(--surface); + border: 1px solid var(--hairline); + border-radius: 18px; + box-shadow: var(--shadow); + padding: 20px; +} +.card h3 { font-size: 16px; font-weight: 600; letter-spacing: -0.01em; } +.help { font-size: 13px; line-height: 1.5; color: var(--text-2); } + +/* Buttons */ +.btn { + font: inherit; font-size: 15px; font-weight: 600; letter-spacing: -0.005em; + display: inline-flex; align-items: center; justify-content: center; gap: 8px; + min-height: 48px; padding: 0 20px; border-radius: 12px; + border: 1px solid transparent; background: none; color: var(--text); + cursor: pointer; -webkit-tap-highlight-color: transparent; + transition: background-color 0.2s, color 0.2s, box-shadow 0.2s, transform 0.12s; +} +.btn:active:not(:disabled) { transform: scale(0.985); } +.btn:disabled { opacity: 0.45; cursor: default; } +.btn .icon { width: 18px; height: 18px; } +.btn.primary { background: var(--accent-fill); color: var(--on-accent); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.14), inset 0 1px 0 rgba(255, 255, 255, 0.14); } +.btn.secondary { background: var(--surface-2); border-color: var(--hairline); } +.btn.danger { background: var(--danger-fill); color: #fff; } +.btn.danger-soft { background: var(--danger-soft); color: var(--danger); } +/* A touch screen keeps :hover on the last tapped spot, where the next view's button may sit. */ +@media (hover: hover) { + .btn.primary:hover:not(:disabled) { background: color-mix(in srgb, var(--accent-fill) 88%, #000); } + .btn.secondary:hover:not(:disabled) { background: var(--surface-3); } + .btn.danger:hover { background: color-mix(in srgb, var(--danger-fill) 88%, #000); } +} +.btn.quiet { min-height: 44px; padding: 0 14px; color: var(--text-2); font-weight: 500; } +.btn.wide { width: 100%; } +.link { + font: inherit; color: var(--accent); background: none; border: 0; padding: 0; cursor: pointer; + text-decoration: underline; text-decoration-color: color-mix(in srgb, var(--accent) 40%, transparent); text-underline-offset: 3px; +} +.icon-btn { + width: 44px; height: 44px; margin: -10px -10px -10px 0; + display: grid; place-items: center; border: 0; border-radius: 12px; + background: none; color: var(--text-3); cursor: pointer; +} +@media (hover: hover) { .icon-btn:hover { background: var(--surface-2); color: var(--text); } } +.icon-btn .icon { width: 18px; height: 18px; } +.icon-btn.done { color: var(--ok); } +/* Negative margins keep the 44px hit area from growing the line of text around it. */ +.icon-btn.inline { display: inline-grid; vertical-align: middle; margin: -12px -13px -12px 0; } +:is(button, input, a):focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } + +/* Fields */ +.field { display: block; } +.field > span { display: block; font-size: 13px; font-weight: 500; color: var(--text-2); margin: 0 0 6px 2px; } +.field input { + width: 100%; min-height: 48px; padding: 12px 14px; + font: 14px/1.4 var(--mono); color: var(--text); + background: var(--surface); border: 1px solid var(--field-border); border-radius: 12px; + transition: border-color 0.15s, box-shadow 0.15s; +} +.field input::placeholder { color: var(--text-3); } +.field input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 4px var(--accent-soft); } +.field input:disabled { background: var(--surface-2); color: var(--text-2); border-color: var(--hairline); } +.field-error { font-size: 13px; color: var(--danger); margin: 8px 2px 0; } + +/* Status hero */ +.hero { text-align: center; padding: 30px 20px 20px; } +.orb { + --c: var(--idle); + position: relative; width: 152px; height: 152px; margin: 0 auto 22px; + display: grid; place-items: center; color: var(--c); + transition: color 0.6s; +} +.orb[data-kind="online"] { --c: var(--ok); } +.orb:is([data-kind="joining"], [data-kind="idle"]) { --c: var(--accent); } +.orb[data-kind="reconnecting"] { --c: var(--warn); } +.orb::before { + content: ""; position: absolute; inset: -6%; border-radius: 50%; + background: radial-gradient(closest-side, color-mix(in srgb, var(--c) 30%, transparent), transparent); + opacity: 0; transition: opacity 0.8s; +} +.orb[data-kind="online"]::before { opacity: 1; animation: breathe 5s ease-in-out infinite; } +.orb[data-kind="reconnecting"]::before { opacity: 0.55; } +.orb .ripple { position: absolute; inset: 0; border-radius: 50%; border: 1.5px solid var(--c); opacity: 0; } +.orb[data-kind="online"] .ripple { animation: ripple 4s cubic-bezier(0.2, 0.6, 0.3, 1) infinite; } +.orb[data-kind="online"] .ripple.r2 { animation-delay: 2s; } +.ring { position: absolute; inset: 0; width: 100%; height: 100%; transform: rotate(-90deg); overflow: visible; } +.ring circle { fill: none; stroke-width: 3; } +.ring .track { stroke: var(--track); } +.ring .arc { + stroke: var(--c); stroke-linecap: round; + stroke-dasharray: 351.9 351.9; stroke-dashoffset: 0; + transform-box: fill-box; transform-origin: center; + transition: stroke 0.6s, stroke-dasharray 0.6s, opacity 0.4s; +} +.orb[data-kind="joining"] .arc { stroke-dasharray: 80 271.9; animation: spin 1.2s linear infinite; } +.orb[data-kind="reconnecting"] .arc { stroke-dasharray: 56 295.9; animation: spin 2.4s linear infinite; } +.orb:is([data-kind="stopped"], [data-kind="idle"]) .arc { opacity: 0; } +.orb-core { + position: relative; width: 104px; height: 104px; border-radius: 50%; + display: grid; place-items: center; + background: var(--surface); + box-shadow: 0 0 0 1px var(--hairline), 0 10px 24px -12px color-mix(in srgb, var(--c) 70%, transparent); + transition: box-shadow 0.6s; +} +.orb-core .icon { width: 40px; height: 40px; stroke-width: 1.6; } +.orb[data-kind="stopped"] .orb-core { box-shadow: 0 0 0 1px var(--hairline); color: var(--text-3); } +.node-title { font-size: 26px; font-weight: 600; letter-spacing: -0.022em; line-height: 1.2; } +.mesh-line { margin-top: 8px; font-size: 15px; color: var(--text-3); overflow-wrap: anywhere; } +#mesh-host { color: var(--text); font-weight: 500; } +.hero .actions { display: flex; gap: 10px; margin-top: 24px; } +.hero .actions .btn { flex: 1; } + +/* Status line */ +.status-line { + display: flex; gap: 10px; align-items: flex-start; + padding: 12px 14px; border-radius: 14px; + background: var(--surface-2); color: var(--text-2); + font-size: 14px; overflow-wrap: anywhere; +} +.status-line .icon { width: 18px; height: 18px; margin-top: 1px; color: var(--text-3); } +.status-line .i-alert { display: none; } +.status-line.error { background: var(--danger-soft); color: var(--danger); } +.status-line.error .icon { color: inherit; } +.status-line.error .i-info { display: none; } +.status-line.error .i-alert { display: block; } + +/* Stats, Node ID and the danger zone */ +.stats { display: grid; grid-template-columns: 1fr 1fr; padding: 0; } +.stat { display: flex; flex-direction: column; gap: 6px; padding: 16px 18px 18px; } +.stat + .stat { border-left: 1px solid var(--hairline); } +.stat-head { display: flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 13px; font-weight: 500; } +.stat-head .icon { width: 18px; height: 18px; color: var(--text-3); } +.stat-value { font-size: 28px; font-weight: 600; letter-spacing: -0.02em; line-height: 1.1; font-variant-numeric: tabular-nums; } +.node-id .head { display: flex; align-items: center; justify-content: space-between; min-height: 24px; } +.node-id h3 { font-size: 13px; font-weight: 500; color: var(--text-2); letter-spacing: 0; } +#node-id { margin-top: 8px; font-size: 13.5px; line-height: 1.6; word-break: break-all; user-select: all; } +.danger-zone h3 { font-size: 13px; font-weight: 600; letter-spacing: 0; color: var(--danger); } +.danger-zone .help { margin-top: 4px; } +.danger-zone .btn { width: 100%; margin-top: 16px; color: var(--danger); } + +/* Welcome */ +.welcome-intro { text-align: center; padding: 18px 8px 8px; } +.welcome-intro .orb { width: 112px; height: 112px; margin-bottom: 20px; } +.welcome-intro .orb-core { width: 80px; height: 80px; } +.welcome-intro .orb-core .icon { width: 32px; height: 32px; } +.welcome-intro h2 { font-size: 28px; font-weight: 600; letter-spacing: -0.024em; line-height: 1.15; } +.welcome-intro p { margin: 10px auto 0; max-width: 34ch; color: var(--text-2); } +.welcome-card form { display: grid; gap: 14px; } +.welcome-card .sign-in .or { margin: 14px 0; font-size: 13px; color: var(--text-3); text-align: center; } +.welcome-card .field-error { margin-top: -6px; } +.welcome-card form .hint { margin-top: -6px; text-align: left; } +#cancel-enroll { width: 100%; margin-top: 6px; } +.hint { margin-top: 16px; font-size: 13px; color: var(--text-3); text-align: center; } + +/* Boot and blocked */ +.boot { min-height: calc(100dvh - 220px); display: grid; place-items: center; } +.spinner { width: 28px; height: 28px; border-radius: 50%; border: 2.5px solid var(--track); border-top-color: var(--text-2); animation: spin 0.9s linear infinite; } +.blocked { text-align: center; max-width: 420px; justify-self: center; padding: 12vh 8px 0; } +.tile { + width: 56px; height: 56px; margin: 0 auto 20px; border-radius: 16px; + display: grid; place-items: center; + background: var(--surface); border: 1px solid var(--hairline); box-shadow: var(--shadow); color: var(--text-2); +} +.tile .icon { width: 26px; height: 26px; } +#blocked-message { font-size: 17px; line-height: 1.45; letter-spacing: -0.01em; overflow-wrap: anywhere; } +#use-here { margin-top: 24px; min-width: 180px; } + +/* Config */ +.badge { display: inline-block; margin-top: 18px; padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 500; color: var(--text-2); background: var(--surface-2); border: 1px solid var(--hairline); } +.config-grid { display: grid; gap: 12px; } +.config-grid .card > .help { margin-top: 4px; } +.config-grid .field { margin-top: 16px; } +.note-box { margin-top: 14px; padding: 12px 14px; border-radius: 12px; background: var(--surface-2); font-size: 13px; color: var(--text-2); } +.agent-toggle { margin-top: 14px; } +.paired-list { margin-top: 10px; padding: 0; list-style: none; font-size: 13px; } +.paired-list li { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +.agent-status { margin-top: 12px; font-size: 13px; color: var(--text-2); } +.call-log { margin-top: 6px; padding: 0; list-style: none; font-size: 12px; overflow-wrap: anywhere; } +.call-log li + li { margin-top: 4px; } +.agent-line { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 8px; font-size: 13px; font-weight: 500; color: var(--ok); } +.agent-line .icon { width: 16px; height: 16px; } +#agent-setup .head { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +#agent-setup p + p { margin-top: 8px; } +.manual { margin-top: 10px; } +.manual summary { cursor: pointer; font-weight: 500; color: var(--text); } +.manual .head { margin-top: 10px; } +.prompt { margin-top: 8px; max-height: 16em; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; line-height: 1.5; color: var(--text); } +.rows { margin-top: 10px; } +.rows p { padding: 12px 0; font-size: 14px; color: var(--text-2); } +.rows p:empty { display: none; } +.rows p + p { border-top: 1px solid var(--hairline); } +.rows p:last-child { padding-bottom: 0; } +.footer { margin-top: 28px; text-align: center; font-size: 12px; color: var(--text-3); } + +/* Navigation: a bottom tab bar on a phone */ +.navigation-bar { + --c: transparent; + position: fixed; left: 0; right: 0; bottom: 0; z-index: 5; + display: flex; padding: 0 8px env(safe-area-inset-bottom); + background: var(--bar); border-top: 1px solid var(--hairline); + -webkit-backdrop-filter: saturate(180%) blur(20px); backdrop-filter: saturate(180%) blur(20px); +} +.navigation-bar button { + position: relative; flex: 1; + display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; + min-height: 58px; padding: 0; border: 0; background: none; cursor: pointer; + font: 500 11px/1.1 var(--font); letter-spacing: 0.01em; color: var(--text-3); + -webkit-tap-highlight-color: transparent; +} +.navigation-bar button[aria-current] { color: var(--accent); font-weight: 650; } +.navigation-bar button[aria-current] .icon { stroke-width: 2; } +.navigation-bar .icon { width: 23px; height: 23px; } +.nav-icon { position: relative; display: grid; } +.nav-dot { position: absolute; top: -1px; right: -4px; width: 8px; height: 8px; border-radius: 50%; background: var(--c); box-shadow: 0 0 0 2px var(--surface); display: none; } +.navigation-bar[data-kind="online"] { --c: var(--ok); } +.navigation-bar[data-kind="joining"] { --c: var(--accent); } +.navigation-bar[data-kind="reconnecting"] { --c: var(--warn); } +.navigation-bar:is([data-kind="online"], [data-kind="joining"], [data-kind="reconnecting"]) .nav-dot { display: block; } + +/* Dialogs */ +dialog { + border: 1px solid var(--hairline); border-radius: 22px; + background: var(--surface); color: var(--text); + padding: 26px; width: min(480px, calc(100vw - 32px)); + box-shadow: var(--shadow-lg); +} +dialog:focus { outline: none; } +dialog::backdrop { background: var(--scrim); -webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px); } +dialog[open] { animation: pop 0.24s cubic-bezier(0.2, 0.8, 0.2, 1); } +dialog h2 { font-size: 20px; font-weight: 600; letter-spacing: -0.016em; line-height: 1.25; } +dialog > p { margin-top: 10px; color: var(--text-2); overflow-wrap: anywhere; } +.kv { margin-top: 18px; border-radius: 14px; background: var(--surface-2); border: 1px solid var(--hairline); } +.kv > div { padding: 12px 14px; } +.kv > div + div { border-top: 1px solid var(--hairline); } +.kv dt { font-size: 12px; font-weight: 500; color: var(--text-3); } +.kv dd { margin-top: 2px; font-weight: 500; overflow-wrap: anywhere; } +.kv dd.mono { font-size: 14px; } +dialog .note { margin-top: 14px; font-size: 13px; color: var(--text-3); } +.dialog-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 24px; } + +/* Phone: dialogs become bottom sheets */ +@media (max-width: 719px) { + dialog { + width: 100%; max-width: 100%; margin: auto 0 0; max-height: 92dvh; + border-radius: 26px 26px 0 0; border-bottom: 0; + padding: 10px 20px calc(16px + env(safe-area-inset-bottom)); + } + dialog::before { content: ""; display: block; width: 36px; height: 5px; margin: 0 auto 20px; border-radius: 3px; background: var(--surface-3); } + dialog[open] { animation: sheet 0.34s cubic-bezier(0.2, 0.8, 0.2, 1); } + .dialog-actions { flex-direction: column-reverse; gap: 8px; } + .dialog-actions .btn { width: 100%; } +} + +/* Tablet and desktop: a top bar with a segmented control. */ +@media (min-width: 720px) { + body { padding-bottom: 48px; } + .app-bar { + position: sticky; top: 0; z-index: 5; + max-width: none; min-height: 64px; margin: 0; + padding: 0 max(32px, calc((100vw - 600px) / 2)); + background: var(--bar); border-bottom: 1px solid var(--hairline); + -webkit-backdrop-filter: saturate(180%) blur(20px); backdrop-filter: saturate(180%) blur(20px); + } + .navigation-bar { + top: 14px; bottom: auto; left: auto; right: max(32px, calc((100vw - 600px) / 2)); + z-index: 6; gap: 2px; padding: 3px; height: 36px; + background: var(--surface-2); border: 1px solid var(--hairline); border-radius: 11px; + -webkit-backdrop-filter: none; backdrop-filter: none; + } + .navigation-bar button { + flex: none; flex-direction: row; min-height: 0; height: 28px; padding: 0 18px; + border-radius: 8px; font-size: 13px; font-weight: 500; letter-spacing: 0; color: var(--text-2); + transition: background-color 0.2s, color 0.2s, box-shadow 0.2s; + } + /* The visible pill is 28px; the hit area reaches 44px. */ + .navigation-bar button::after { content: ""; position: absolute; inset: -8px 0; } + .navigation-bar button:hover { color: var(--text); } + .navigation-bar button[aria-current] { color: var(--text); font-weight: 600; background: var(--surface); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08), 0 0 0 1px var(--hairline); } + .navigation-bar .nav-icon { display: none; } + main { max-width: 664px; padding: 40px 32px 32px; } + .hero { padding: 40px 32px 32px; } + .hero .actions { justify-content: center; } + .hero .actions .btn { flex: 0 1 220px; } + .welcome-intro { padding-top: 24px; } + .dialog-actions .btn { min-width: 96px; padding: 0 18px; white-space: nowrap; } + .danger-zone .btn { width: auto; } + #unenroll-reset { order: -1; margin-right: auto; } +} + +@media (min-width: 960px) { + main { max-width: 1080px; padding: 56px 32px 32px; } + .app-bar { padding-inline: max(32px, calc((100vw - 1016px) / 2)); } + .navigation-bar { right: max(32px, calc((100vw - 1016px) / 2)); } + #tab-dashboard { + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + column-gap: 24px; row-gap: 16px; align-items: start; + grid-template-areas: "main details" "status details"; + } + #view-boot, #view-blocked { grid-column: 1 / -1; } + .hero { padding: 48px 40px 40px; } + .orb { width: 196px; height: 196px; margin-bottom: 28px; } + .orb-core { width: 132px; height: 132px; } + .orb-core .icon { width: 50px; height: 50px; } + .node-title { font-size: 32px; } + .details { gap: 16px; } + .stat { padding: 22px 24px 24px; gap: 10px; } + .stat-value { font-size: 36px; } + .node-id, .danger-zone { padding: 22px 24px; } + #node-id { font-size: 15px; } + + /* Welcome: the intro on the left, the join form on the right, centred vertically. */ + #tab-dashboard:is([data-kind="welcome"], [data-kind="enrolling"]) { + grid-template-areas: "main details" ". status"; + column-gap: 72px; align-content: center; align-items: center; + min-height: calc(100dvh - 184px); + } + #tab-dashboard:is([data-kind="welcome"], [data-kind="enrolling"]) #status { align-self: start; } + .welcome-intro { text-align: left; padding: 0; } + .welcome-intro .orb { margin: 0 0 28px; } + .welcome-intro h2 { font-size: 36px; } + .welcome-intro p { margin-left: 0; font-size: 17px; max-width: 36ch; } + .welcome-card { padding: 28px; } + + .config-grid { grid-template-columns: 1fr 1fr; gap: 24px; align-items: start; } + .config-grid .card { padding: 26px; } +} + +/* Wide desktop: the segmented control moves to the centre and the status pill appears. */ +@media (min-width: 1100px) { + .navigation-bar { left: 50%; right: auto; transform: translateX(-50%); } + .bar-status { display: flex; } +} + +/* Motion */ +@keyframes spin { to { transform: rotate(360deg); } } +@keyframes breathe { 0%, 100% { transform: scale(0.94); opacity: 0.7; } 50% { transform: scale(1.06); opacity: 1; } } +@keyframes ripple { 0% { transform: scale(1); opacity: 0.32; } 100% { transform: scale(1.24); opacity: 0; } } +@keyframes rise { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } } +@keyframes pop { from { opacity: 0; transform: scale(0.97); } to { opacity: 1; transform: none; } } +@keyframes sheet { from { transform: translateY(100%); } to { transform: none; } } +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation: none !important; transition: none !important; } +} diff --git a/sdk/js/README.md b/sdk/js/README.md index b38aff8c0..9f9faf05c 100644 --- a/sdk/js/README.md +++ b/sdk/js/README.md @@ -234,6 +234,12 @@ not put them on a command line. `labels` are attested at enrollment; `join({ egressRequireLabels })` is the floor every peer the session calls must attest, all of it, held for the session. +`AgentMesh.forget(stateDir, { keepIdentity })` deletes the saved credential, +and the identity too unless `keepIdentity` is set, so the next `enroll` spends +its token instead of resuming. Close the sessions joined from that state +first. `AgentMesh.load({ stateDir })` resumes without a token and throws +`NotEnrolledError` when there is nothing to resume. + A plaintext `http://` control plane is accepted only on loopback. Pass `allowInsecure: true` for a network you trust. diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.json index 050d995fc..9f7292b6f 100644 --- a/sdk/js/package-lock.json +++ b/sdk/js/package-lock.json @@ -39,8 +39,10 @@ "devDependencies": { "@a2a-js/sdk": "^1.3.0", "@bufbuild/protoc-gen-es": "^2.16.0", + "@mcp-b/webmcp-local-relay": "6.2.0", "@types/express": "^5.0.6", "@types/node": "^26.6.4", + "@w3c/webmcp-polyfill": "0.1.1", "esbuild": "^0.28.2", "express": "^5.2.1", "typescript": "^7.0.2" @@ -1175,6 +1177,36 @@ "uint8arrays": "^6.0.0" } }, + "node_modules/@mcp-b/webmcp-local-relay": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/@mcp-b/webmcp-local-relay/-/webmcp-local-relay-6.2.0.tgz", + "integrity": "sha512-CUkbdcDqkLuHB+yF0IKkkmR3K0ccfZL4/h/qhgC0MgWXKsW5R21NtIsW9aTz1B2l5clirFT1RHayhKXsRbFIPA==", + "dev": true, + "dependencies": { + "@modelcontextprotocol/core": "2.4.0", + "@modelcontextprotocol/server": "2.4.0", + "ws": "^8.22.1", + "zod": "4.6.7" + }, + "bin": { + "webmcp-local-relay": "dist/cli.mjs" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz", + "integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==", + "dev": true, + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.32.2", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz", @@ -1215,6 +1247,19 @@ } } }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz", + "integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==", + "dev": true, + "dependencies": { + "@modelcontextprotocol/core": "2.4.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@multiformats/dns": { "version": "1.0.15", "resolved": "https://registry.npmjs.org/@multiformats/dns/-/dns-1.0.15.tgz", @@ -1997,6 +2042,15 @@ "typescript": "*" } }, + "node_modules/@w3c/webmcp-polyfill": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@w3c/webmcp-polyfill/-/webmcp-polyfill-0.1.1.tgz", + "integrity": "sha512-oIVCnVLd8pEvf8dPoU1j5SizqMi01LDeg4He0gfDRr34Krq64FA8J6CBELFKVfrmF0C3OfXehFVAgDRFqQZ8LQ==", + "dev": true, + "dependencies": { + "webmcp-types": "^0.1.11" + } + }, "node_modules/abort-error": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/abort-error/-/abort-error-1.0.2.tgz", @@ -3867,6 +3921,12 @@ "tslib": "^2.8.1" } }, + "node_modules/webmcp-types": { + "version": "0.1.11", + "resolved": "https://registry.npmjs.org/webmcp-types/-/webmcp-types-0.1.11.tgz", + "integrity": "sha512-eMbboj2UcDVEJ0bdLsKJNRnvcVrAzesVnK5A4R+b9zbPiM6kuGPXQNTWlMlWq1FWr0L2BWZ3iA6e8fr3TN7gVw==", + "dev": true + }, "node_modules/wherearewe": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/wherearewe/-/wherearewe-2.0.1.tgz", @@ -3901,9 +3961,9 @@ "license": "ISC" }, "node_modules/ws": { - "version": "8.21.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", - "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", "engines": { "node": ">=10.0.0" }, diff --git a/sdk/js/package.json b/sdk/js/package.json index 0cc377c16..f36acac9e 100644 --- a/sdk/js/package.json +++ b/sdk/js/package.json @@ -39,9 +39,12 @@ "build": "tsc -p tsconfig.build.json", "examples": "tsc -p tsconfig.examples.json", "typecheck": "tsc -p tsconfig.json --noEmit", - "pretest": "tsc -p tsconfig.test.json", + "pretest": "tsc -p tsconfig.test.json && tsc -p tsconfig.webapp-test.json", "test": "node --test 'build/**/*.test.js'", - "bundle:browser": "node scripts/bundle-browser.mjs" + "bundle:browser": "node scripts/bundle-browser.mjs", + "bundle:app": "node scripts/bundle-browser.mjs webapp/index.mjs ../../internal/webapp/public/sdk --minify --no-sourcemap && npm run bundle:app-agent", + "bundle:app-agent": "esbuild @w3c/webmcp-polyfill/auto --bundle --format=esm --minify --outfile=../../internal/webapp/public/sdk/webmcp-polyfill.js && cp node_modules/@mcp-b/webmcp-local-relay/dist/browser/widget.js ../../internal/webapp/public/sdk/webmcp-relay.js && npm run bundle:app-relay", + "bundle:app-relay": "esbuild webapp/relay.ts --bundle --platform=node --format=esm --target=node22 --banner:js=\"import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);\" --outfile=../../internal/webapp/public/sdk/agentmesh-relay.mjs" }, "dependencies": { "@biscuit-auth/biscuit-wasm": "^0.6.0", @@ -71,8 +74,10 @@ "devDependencies": { "@a2a-js/sdk": "^1.3.0", "@bufbuild/protoc-gen-es": "^2.16.0", + "@mcp-b/webmcp-local-relay": "6.2.0", "@types/express": "^5.0.6", "@types/node": "^26.6.4", + "@w3c/webmcp-polyfill": "0.1.1", "esbuild": "^0.28.2", "express": "^5.2.1", "typescript": "^7.0.2" diff --git a/sdk/js/scripts/bundle-browser.mjs b/sdk/js/scripts/bundle-browser.mjs index 1d95020c2..21739845d 100644 --- a/sdk/js/scripts/bundle-browser.mjs +++ b/sdk/js/scripts/bundle-browser.mjs @@ -20,9 +20,9 @@ // the file beside the bundle and instantiates it. Bundling dist/index.js // this way also proves that nothing in the browser graph reaches for Node. // -// node scripts/bundle-browser.mjs [entry] [outdir] +// node scripts/bundle-browser.mjs [entry] [outdir] [--minify] [--no-sourcemap] // -// Defaults: dist/index.js into build/browser. +// Defaults: dist/index.js into build/browser, unminified, with a source map. import * as esbuild from "esbuild"; import { readFile } from "node:fs/promises"; @@ -30,7 +30,9 @@ import { basename, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; const here = dirname(fileURLToPath(import.meta.url)); -const [entry = join(here, "..", "dist", "index.js"), outdir = join(here, "..", "build", "browser")] = process.argv.slice(2); +const args = process.argv.slice(2); +const flags = new Set(args.filter((a) => a.startsWith("--"))); +const [entry = join(here, "..", "dist", "index.js"), outdir = join(here, "..", "build", "browser")] = args.filter((a) => !a.startsWith("--")); /** import * as wasm from "./x.wasm" as WebAssembly ESM integration would resolve it. */ const wasmModules = { @@ -74,7 +76,8 @@ const result = await esbuild.build({ outdir, entryNames: "[name]", assetNames: "[name]", - sourcemap: true, + sourcemap: !flags.has("--no-sourcemap"), + minify: flags.has("--minify"), plugins: [wasmModules], metafile: true, logLevel: "warning", diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.ts index 3d32b898f..caebdbc61 100644 --- a/sdk/js/src/index.ts +++ b/sdk/js/src/index.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -export { AgentMesh, CredentialRetiredError, type AgentMeshOptions, type ControlPlaneSync, type EnrollOptions, type JwtSource } from "./mesh.ts"; +export { AgentMesh, CredentialRetiredError, NotEnrolledError, type AgentMeshOptions, type ControlPlaneSync, type EnrollOptions, type JwtSource } from "./mesh.ts"; export { Identity, canonicalPeerId, peerIdFromPublicKey, libp2pPublicKey, verifyEd25519 } from "./identity.ts"; export { ControlPlaneClient, diff --git a/sdk/js/src/mcp-server.ts b/sdk/js/src/mcp-server.ts index b4e540ee6..7119fe548 100644 --- a/sdk/js/src/mcp-server.ts +++ b/sdk/js/src/mcp-server.ts @@ -164,21 +164,29 @@ async function fanOut

(peers: P[], signal: AbortSignal, fn: (p return results; } +/** One caller tool: what an MCP client lists, and what a call runs. */ +export interface MeshTool { + name: string; + description: string; + inputSchema: z.ZodRawShape; + run(args: Record, extra: { signal: AbortSignal }): Promise; +} + /** The same five caller tools as agentmesh-node; an SDK member hosts no services. */ -export function createMeshMCPServer(ready: Session | Promise, version: string): McpServer { - const server = new McpServer({ name: "agentmesh", version }, { instructions: - "Use find_remote_tools, then describe_remote_tool to learn the input schema, then call_remote_tool. " + - "Calls use this SDK member's identity and mesh policy. This stdio server exposes no local HTTP proxy, inference endpoint or hosted services.", - }); +export function meshTools(ready: Session | Promise): MeshTool[] { + const list: MeshTool[] = []; + const add = (name: string, config: { description: string; inputSchema: S }, run: (args: z.infer>, extra: { signal: AbortSignal }) => Promise) => { + list.push({ name, ...config, run: run as MeshTool["run"] }); + }; - server.registerTool("get_mesh_info", { description: "Get information about the mesh network", inputSchema: {} }, async (_args, extra) => { + add("get_mesh_info", { description: "Get information about the mesh network", inputSchema: {} }, async (_args, extra) => { const signal = AbortSignal.any([extra.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]); const s = await withSignal(ready, signal); const routers = s.routers.filter((r) => s.isHeldRouter(r.peerId)).map((r) => r.peerId).sort(); return text({ peer_id: s.peerId, connected_peers: s.node.getPeers().map((p) => p.toString()).sort(), attached_routers: routers, router_peer_id: routers[0] ?? "" }); }); - server.registerTool("discover_remote_services", { + add("discover_remote_services", { description: "Discover remote services by type and optional name. Returns peer_id, srv_name and srv_description. This SDK member has no local_proxy_url; inference and A2A services require an SDK client or an agentmesh-node HTTP proxy.", inputSchema: { type: z.string().describe("Required. One of: mcp, inference, a2a."), @@ -217,7 +225,7 @@ export function createMeshMCPServer(ready: Session | Promise, version: return text(rows.slice(offset, offset + limit)); }); - server.registerTool("find_remote_tools", { + add("find_remote_tools", { description: "Discover MCP tools available on hosted services across the mesh. Optionally narrow by peer_id, service_name, or exact tool_name. intent is accepted but ignored, as in agentmesh-node.", inputSchema: { intent: z.string().optional().describe("Natural-language description of what the caller is looking for. Reserved for future semantic ranking; currently accepted but ignored."), @@ -273,7 +281,7 @@ export function createMeshMCPServer(ready: Session | Promise, version: return text(rows.filter((row) => !args.tool_name || !row.error).sort((a, b) => a.peer_id.localeCompare(b.peer_id) || (a.tool_name ?? "").localeCompare(b.tool_name ?? ""))); }); - server.registerTool("describe_remote_tool", { + add("describe_remote_tool", { description: "Return the description, input schema, and output schema for a specific MCP tool on a specific peer.", inputSchema: { peer_id: z.string().describe("Peer ID of the node hosting the server. Required."), @@ -287,7 +295,7 @@ export function createMeshMCPServer(ready: Session | Promise, version: return text({ peer_id: peer, tool_name: args.tool_name, description: tool.description ?? "", input_schema: tool.inputSchema, ...(tool.outputSchema ? { output_schema: tool.outputSchema } : {}) }); }); - server.registerTool("call_remote_tool", { + add("call_remote_tool", { description: "Call an MCP tool on a remote agent", inputSchema: { peer_id: z.string().describe("The Peer ID of the target agent"), @@ -302,5 +310,16 @@ export function createMeshMCPServer(ready: Session | Promise, version: return call(s, peer, target.service, target.tool, args.arguments ?? {}, { signal: open, requiredLabels: requiredLabels(args.required_labels ?? "") }, { signal: extra.signal, timeout: CALL_TIMEOUT_MS, resetTimeoutOnProgress: true }); }); + return list; +} + +export function createMeshMCPServer(ready: Session | Promise, version: string): McpServer { + const server = new McpServer({ name: "agentmesh", version }, { instructions: + "Use find_remote_tools, then describe_remote_tool to learn the input schema, then call_remote_tool. " + + "Calls use this SDK member's identity and mesh policy. This stdio server exposes no local HTTP proxy, inference endpoint or hosted services.", + }); + for (const tool of meshTools(ready)) { + server.registerTool(tool.name, { description: tool.description, inputSchema: tool.inputSchema }, (args, extra) => tool.run(args, extra)); + } return server; } diff --git a/sdk/js/src/mesh.test.ts b/sdk/js/src/mesh.test.ts index 8dc8b1564..da374c763 100644 --- a/sdk/js/src/mesh.test.ts +++ b/sdk/js/src/mesh.test.ts @@ -15,7 +15,7 @@ import { create, fromBinary, toBinary } from "@bufbuild/protobuf"; import { timestampFromMs } from "@bufbuild/protobuf/wkt"; import assert from "node:assert/strict"; -import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { cp as copyDir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; @@ -32,7 +32,7 @@ import { TokenRefreshResponseSchema, } from "./gen/agentmesh_pb.ts"; import { Identity } from "./identity.ts"; -import { AgentMesh, CredentialRetiredError } from "./mesh.ts"; +import { AgentMesh, CredentialRetiredError, NotEnrolledError } from "./mesh.ts"; const cpKey = Identity.generate(); const text = (s: string) => new TextEncoder().encode(s); @@ -45,9 +45,9 @@ function proto(bytes: Uint8Array): Response { function fakeControlPlane( keysOk = true, opts: { strictRefresh?: boolean; refreshDelayMs?: number; rejectNextRefresh?: boolean } = {}, -): { fetch: typeof fetch; issued: number; lastRefreshJwt: string; keys: Identity[]; keysOk: boolean } { - // keys is what /keys serves and signs with; a test rotates by replacing it. - const state = { issued: 0, lastRefreshJwt: "", keys: [cpKey], keysOk }; +): { fetch: typeof fetch; issued: number; lastRefreshJwt: string; keys: Identity[]; keysOk: boolean; onKeys: (() => Promise) | undefined } { + // keys is what /keys serves and signs with; a test rotates by replacing it. onKeys runs when /keys is asked. + const state = { issued: 0, lastRefreshJwt: "", keys: [cpKey], keysOk, onKeys: undefined as (() => Promise) | undefined }; const current = () => (state.keys[state.keys.length - 1] as Identity).publicKeyRaw; const signedKeys = () => { const unsigned = create(KeysResponseSchema, { publicKeys: state.keys.map((k) => k.publicKeyRaw), signTime: timestampFromMs(Date.now()) }); @@ -117,6 +117,7 @@ function fakeControlPlane( ); } case "GET /keys": + await state.onKeys?.(); return state.keysOk ? proto(toBinary(KeysResponseSchema, signedKeys())) : new Response("boom", { status: 500 }); default: return new Response(`no route for ${req.method} ${path}`, { status: 404 }); @@ -142,9 +143,35 @@ function fakeControlPlane( set keysOk(ok: boolean) { state.keysOk = ok; }, + get onKeys() { + return state.onKeys; + }, + set onKeys(hook: (() => Promise) | undefined) { + state.onKeys = hook; + }, }; } +test("refresh saves the new biscuit before it asks for /keys, so a process stopped in between can still refresh", async () => { + const dir = await mkdtemp(join(tmpdir(), "agentmesh-sdk-")); + try { + const cp = fakeControlPlane(true, { strictRefresh: true }); + const stateDir = join(dir, "state"); + const stopped = join(dir, "stopped"); + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, bootstrapToken: "sbt_secret", fetch: cp.fetch }); + // What a process stopped while /keys is asked leaves on disk. + cp.onKeys = () => copyDir(stateDir, stopped, { recursive: true }); + await mesh.refresh(); + cp.onKeys = undefined; + + const restarted = await AgentMesh.load({ stateDir: stopped, fetch: cp.fetch }); + await restarted.refresh(); + assert.deepEqual(restarted.credential.biscuit, text("biscuit-3")); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + test("enroll persists identity and credential, load resumes them, refresh rotates", async () => { const dir = await mkdtemp(join(tmpdir(), "agentmesh-sdk-")); try { @@ -248,9 +275,46 @@ test("enroll resumes only a credential the control plane still vouches for", asy test("load needs both the identity and the credential", async () => { const dir = await mkdtemp(join(tmpdir(), "agentmesh-sdk-")); try { - await assert.rejects(AgentMesh.load({ stateDir: dir }), /no identity/); + await assert.rejects(AgentMesh.load({ stateDir: dir }), (err: Error) => err instanceof NotEnrolledError && /no identity/.test(err.message)); await writeFile(join(dir, "identity.key"), Identity.generate().toLibp2pPrivateKey()); - await assert.rejects(AgentMesh.load({ stateDir: dir }), /no credential/); + await assert.rejects(AgentMesh.load({ stateDir: dir }), (err: Error) => err.name === "NotEnrolledError" && /no credential/.test(err.message)); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("forget keeps the identity when asked, so the next enroll presents the same peer", async () => { + const dir = await mkdtemp(join(tmpdir(), "agentmesh-sdk-")); + try { + const cp = fakeControlPlane(); + const stateDir = join(dir, "state"); + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, bootstrapToken: "sbt_secret", fetch: cp.fetch }); + + await AgentMesh.forget(stateDir, { keepIdentity: true }); + await assert.rejects(AgentMesh.load({ stateDir }), NotEnrolledError); + await assert.rejects(AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, fetch: cp.fetch }), /no credential to resume/); + const again = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, bootstrapToken: "sbt_secret", fetch: cp.fetch }); + assert.equal(again.peerId, mesh.peerId); + assert.equal(cp.issued, 2); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("forget without keepIdentity removes both; forgetting an empty state directory is not an error", async () => { + const dir = await mkdtemp(join(tmpdir(), "agentmesh-sdk-")); + try { + const cp = fakeControlPlane(); + const stateDir = join(dir, "state"); + await AgentMesh.forget(stateDir); + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, bootstrapToken: "sbt_secret", fetch: cp.fetch }); + + await AgentMesh.forget(stateDir); + await assert.rejects(AgentMesh.load({ stateDir }), /no identity/); + await assert.rejects(stat(join(stateDir, "identity.key")), { code: "ENOENT" }); + await assert.rejects(stat(join(stateDir, "credential.json")), { code: "ENOENT" }); + const fresh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir, bootstrapToken: "sbt_secret", fetch: cp.fetch }); + assert.notEqual(fresh.peerId, mesh.peerId); } finally { await rm(dir, { recursive: true, force: true }); } diff --git a/sdk/js/src/mesh.ts b/sdk/js/src/mesh.ts index 7567bd000..98f216299 100644 --- a/sdk/js/src/mesh.ts +++ b/sdk/js/src/mesh.ts @@ -52,6 +52,18 @@ export class CredentialRetiredError extends Error { } } +/** + * The state directory holds no enrolled member: no identity, or an identity + * whose credential was never saved or was forgotten. enroll() with a token + * is the way out. + */ +export class NotEnrolledError extends Error { + constructor(message: string) { + super(message); + this.name = "NotEnrolledError"; + } +} + /** * The saved credential with the control plane's current keys adopted, or * undefined when the control plane vouches for none of the keys it trusts. A @@ -200,8 +212,8 @@ export class AgentMesh { * under a key that retired while the member was off cannot be verified or * refreshed, so the member enrolls again with the token given, or throws * CredentialRetiredError without one. Otherwise exactly one of - * bootstrapToken, bootstrapTokenPath, jwt or jwtPath must be given. Delete - * the state directory to enroll afresh, for instance with other labels. + * bootstrapToken, bootstrapTokenPath, jwt or jwtPath must be given. + * forget() without keepIdentity to enroll afresh, for instance with other labels. */ static async enroll(options: EnrollOptions): Promise { const state = options.stateDir !== undefined ? openState(options.stateDir) : undefined; @@ -279,7 +291,8 @@ export class AgentMesh { /** * Resumes a member from a state directory written by an earlier enroll(), * for a process that must never hold an enrollment token. The control - * plane URL comes from the saved credential. + * plane URL comes from the saved credential. Throws NotEnrolledError when + * there is nothing to resume. */ static async load( options: Omit & { @@ -291,11 +304,11 @@ export class AgentMesh { const state = openState(options.stateDir); const identity = options.identity ?? (await loadIdentity(state)); if (!identity) { - throw new Error(`no identity in ${options.stateDir}; enroll first`); + throw new NotEnrolledError(`no identity in ${options.stateDir}; enroll first`); } const credential = await loadCredential(state); if (credential === undefined) { - throw new Error(`no credential in ${options.stateDir}; enroll first`); + throw new NotEnrolledError(`no credential in ${options.stateDir}; enroll first`); } return new AgentMesh( identity, @@ -306,10 +319,23 @@ export class AgentMesh { ); } + /** + * Deletes the credential enroll() saved in stateDir, and the identity key too + * unless keepIdentity. Local only; close the sessions joined from this state + * first, because a session saves its credential when it refreshes. + */ + static async forget(stateDir: string, options: { keepIdentity?: boolean } = {}): Promise { + const state = openState(stateDir); + await state.remove(CREDENTIAL_FILE); + if (options.keepIdentity !== true) { + await state.remove(IDENTITY_FILE); + } + } + /** * Trades the current biscuit for a fresh one and persists it. The control * plane redeems only the last biscuit it issued, so a lost refresh result - * means re-enrolling; persisting before returning keeps that rare. + * means re-enrolling; persisting as soon as /refresh answers, before /keys, keeps that rare. * Concurrent calls wait for each other. A refresh whose signal has * aborted by the time its turn comes does not start. */ @@ -347,19 +373,16 @@ export class AgentMesh { biscuit: this.#credential.biscuit, ...(jwt !== undefined ? { jwt } : {}), }); + // Saved before /keys: the old biscuit is spent, so a process that stops in between must already hold the new one. + this.#credential = withCredentialMethods({ ...this.#credential, biscuit: result.biscuit, expiration: result.expiration }); + await this.save(); let controlPlaneKeys = this.#credential.controlPlaneKeys; try { controlPlaneKeys = await this.controlPlane.keys(controlPlaneKeys); } catch { // Keep the previous set; a failed /keys sync must not cost the new biscuit. } - this.#credential = withCredentialMethods({ - ...this.#credential, - biscuit: result.biscuit, - expiration: result.expiration, - controlPlaneKeys, - issuedUnderKeys: controlPlaneKeys, - }); + this.#credential = withCredentialMethods({ ...this.#credential, controlPlaneKeys, issuedUnderKeys: controlPlaneKeys }); await this.save(); return this.#credential; } diff --git a/sdk/js/src/platform/state.browser.ts b/sdk/js/src/platform/state.browser.ts index fd2bb90bc..0864d1cc4 100644 --- a/sdk/js/src/platform/state.browser.ts +++ b/sdk/js/src/platform/state.browser.ts @@ -49,6 +49,10 @@ export function openState(location: string): StateStore { const tx = (await open()).transaction(STORE, "readwrite"); await request(tx.objectStore(STORE).put(new Uint8Array(data), name)); }, + async remove(name) { + const tx = (await open()).transaction(STORE, "readwrite"); + await request(tx.objectStore(STORE).delete(name)); + }, }; } diff --git a/sdk/js/src/platform/state.ts b/sdk/js/src/platform/state.ts index 49df0c485..420168daf 100644 --- a/sdk/js/src/platform/state.ts +++ b/sdk/js/src/platform/state.ts @@ -15,7 +15,7 @@ // State on Node: a directory, one file per name, owner-only, written to a // temporary name and renamed into place. Where a token file is read from. -import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import type { StateStore } from "./types.ts"; @@ -39,6 +39,9 @@ export function openState(location: string): StateStore { await writeFile(tmp, data, { mode: 0o600 }); await rename(tmp, path); }, + async remove(name) { + await rm(join(location, name), { force: true }); + }, }; } diff --git a/sdk/js/src/platform/types.ts b/sdk/js/src/platform/types.ts index 4118e0b7a..33c01d487 100644 --- a/sdk/js/src/platform/types.ts +++ b/sdk/js/src/platform/types.ts @@ -22,4 +22,6 @@ export interface StateStore { read(name: string): Promise; /** Writes the bytes under a name so that a reader sees the old or the new value, never a mix. */ write(name: string, data: Uint8Array): Promise; + /** Deletes the bytes under a name; deleting a name never written is not an error. */ + remove(name: string): Promise; } diff --git a/sdk/js/src/session.test.ts b/sdk/js/src/session.test.ts index 9f3633b40..ff1630bc6 100644 --- a/sdk/js/src/session.test.ts +++ b/sdk/js/src/session.test.ts @@ -547,6 +547,78 @@ test("a member announces where it is reached under its peer key and withdraws it } }); +test("close waits for a pull in flight, so nothing saves the state after it", async () => { + const stateDir = await mkdtemp(join(tmpdir(), "agentmesh-session-")); + const base = fakeControlPlane([routerAddr]); + let infoCalls = 0; + let release!: () => void; + const released = new Promise((resolve) => (release = resolve)); + let pullStarted!: () => void; + const pulling = new Promise((resolve) => (pullStarted = resolve)); + // The first /info is join's own pull; the second is the session's, held until released. + const gated: typeof fetch = (async (input: Parameters[0], init?: RequestInit) => { + if (new URL(new Request(input, init).url).pathname === "/info" && ++infoCalls === 2) { + pullStarted(); + await released; + } + return base(input, init); + }) as typeof fetch; + try { + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", stateDir, fetch: gated }); + const session = await mesh.join({ refreshLeadMs: 0, reserveRelay: false, controlPlaneSyncIntervalMs: 10 }); + await pulling; + let closed = false; + const closing = session.close().then(() => (closed = true)); + await Promise.race([closing, new Promise((resolve) => setTimeout(resolve, 200))]); + assert.equal(closed, false, "close() returned while the pull it started was still going to save"); + release(); + await closing; + + await AgentMesh.forget(stateDir); + await assert.rejects(AgentMesh.load({ stateDir }), /no identity/); + } finally { + release(); + await rm(stateDir, { recursive: true, force: true }); + } +}); + +test("close waits for a credential refresh in flight, so nothing saves the state after it", async () => { + const stateDir = await mkdtemp(join(tmpdir(), "agentmesh-session-")); + const base = fakeControlPlane([routerAddr]); + let release!: () => void; + const released = new Promise((resolve) => (release = resolve)); + let refreshStarted!: () => void; + const refreshing = new Promise((resolve) => (refreshStarted = resolve)); + const gated: typeof fetch = (async (input: Parameters[0], init?: RequestInit) => { + const req = new Request(input, init); + if (req.method === "POST" && new URL(req.url).pathname === "/refresh") { + const { peerId } = fromBinary(TokenRefreshRequestSchema, new Uint8Array(await req.arrayBuffer())); + refreshStarted(); + await released; + return proto(toBinary(TokenRefreshResponseSchema, create(TokenRefreshResponseSchema, { biscuitToken: mint(peerId, ROLE_NODE), expireTime: timestampFromMs(Date.now() + 7200_000) }))); + } + return base(input, init); + }) as typeof fetch; + try { + const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt", stateDir, fetch: gated }); + // A lead longer than the credential's hour makes the first refresh due at once. + const session = await mesh.join({ refreshLeadMs: 2 * 3600_000, reserveRelay: false, controlPlaneSyncIntervalMs: 600_000 }); + await refreshing; + let closed = false; + const closing = session.close().then(() => (closed = true)); + await Promise.race([closing, new Promise((resolve) => setTimeout(resolve, 200))]); + assert.equal(closed, false, "close() returned while the refresh it started was still going to save"); + release(); + await closing; + + await AgentMesh.forget(stateDir); + await assert.rejects(AgentMesh.load({ stateDir }), /no identity/); + } finally { + release(); + await rm(stateDir, { recursive: true, force: true }); + } +}); + test("a resumed member adopts a rotated key before admitting routers", async () => { // The control plane rotated its signing key while this member was not // running: the routers already hold credentials under the new key, and diff --git a/sdk/js/src/session.ts b/sdk/js/src/session.ts index 54c04377f..9ee55abec 100644 --- a/sdk/js/src/session.ts +++ b/sdk/js/src/session.ts @@ -244,6 +244,7 @@ export class MeshSession { /** The addresses of the record last announced under this member's peer key. */ #announced: string[] = []; #syncing: Promise | undefined; + #refreshing: Promise | undefined; #keepingRelay: Promise | undefined; #keepRelayPending = false; readonly #heldRouterIds: Set; @@ -984,9 +985,12 @@ export class MeshSession { * never sees leaves it refusing relay circuits to this member once the * old one lapses, with every connection still open. */ - async #refreshCredential(): Promise { - await this.mesh.refresh(); - await this.#readmitRouters(); + #refreshCredential(): Promise { + this.#refreshing = (async () => { + await this.mesh.refresh(); + await this.#readmitRouters(); + })(); + return this.#refreshing; } /** @@ -1261,6 +1265,9 @@ export class MeshSession { if (!this.#isTaskView) { await this.node.stop(); } + // A refresh or pull in flight saves the credential when it lands; once + // close() returns, nothing this session started writes the state again. + await Promise.allSettled([this.#refreshing, this.#syncing]); } } diff --git a/sdk/js/tsconfig.json b/sdk/js/tsconfig.json index 6169c834d..add52ded0 100644 --- a/sdk/js/tsconfig.json +++ b/sdk/js/tsconfig.json @@ -15,5 +15,5 @@ "skipLibCheck": true, "noEmit": true }, - "include": ["src/**/*.ts"] + "include": ["src/**/*.ts", "webapp/**/*.ts"] } diff --git a/sdk/js/tsconfig.webapp-test.json b/sdk/js/tsconfig.webapp-test.json new file mode 100644 index 000000000..0cade57a7 --- /dev/null +++ b/sdk/js/tsconfig.webapp-test.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "outDir": "build/webapp-test", + "rootDir": "." + }, + "include": ["webapp/**/*.test.ts"] +} diff --git a/sdk/js/webapp/index.mjs b/sdk/js/webapp/index.mjs new file mode 100644 index 000000000..20978301a --- /dev/null +++ b/sdk/js/webapp/index.mjs @@ -0,0 +1,20 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The web app's SDK bundle: the published SDK as built for browsers, plus the +// WebMCP code that only the web app uses and npm does not ship. +export * from "../dist/index.js"; +export { meshTools } from "../dist/mcp-server.js"; +export { registerWebMCPTools } from "./webmcp.ts"; +export { CallVerifier, PAIR_TOOL, answerPairing } from "./pairing.ts"; diff --git a/sdk/js/webapp/pairing.test.ts b/sdk/js/webapp/pairing.test.ts new file mode 100644 index 000000000..2bd71d0f0 --- /dev/null +++ b/sdk/js/webapp/pairing.test.ts @@ -0,0 +1,86 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { CALL_FIELD, CALL_WINDOW_MS, CallVerifier, answerPairing, randomToken, signCall, startPairing, type PairedAgent } from "./pairing.ts"; + +async function pair(name = "Claude Code"): Promise<{ relay: { key_id: string; key: string }; agent: PairedAgent }> { + const token = randomToken(); + const pairing = await startPairing(token, name); + const { response, agent } = await answerPairing(token, pairing.request); + return { relay: await pairing.finish(response), agent }; +} + +test("pairing gives the relay and the page the same key under the page's key ID", async () => { + const { relay, agent } = await pair("Cursor"); + assert.equal(relay.key_id, agent.key_id); + assert.equal(relay.key, agent.key); + assert.equal(agent.name, "Cursor"); +}); + +test("the page refuses a pairing request made with another token", async () => { + const pairing = await startPairing(randomToken(), "Claude Code"); + await assert.rejects(answerPairing(randomToken(), pairing.request), /pairing token is wrong, expired or already used/); +}); + +test("the relay refuses an answer from a page without the token", async () => { + const pairing = await startPairing(randomToken(), "Claude Code"); + const other = randomToken(); + const { response } = await answerPairing(other, (await startPairing(other, "Claude Code")).request); + await assert.rejects(pairing.finish(response), /did not prove it holds the pairing token/); +}); + +test("the page accepts a signed call once and hands back the arguments the relay signed", async () => { + const { relay, agent } = await pair(); + const verifier = new CallVerifier(() => [agent]); + const input = await signCall(relay, "call_remote_tool", { peer_id: "12D3KooW", tool: "add" }); + + const { agent: caller, args } = await verifier.verify("call_remote_tool", input); + assert.equal(caller.name, "Claude Code"); + assert.deepEqual(args, { peer_id: "12D3KooW", tool: "add" }); + await assert.rejects(verifier.verify("call_remote_tool", input), /replayed or delayed/); +}); + +test("two copies of one signed call sent together run once", async () => { + const { relay, agent } = await pair(); + const verifier = new CallVerifier(() => [agent]); + const input = await signCall(relay, "call_remote_tool", { peer_id: "12D3KooW", tool: "transfer" }); + + const results = await Promise.allSettled([verifier.verify("call_remote_tool", input), verifier.verify("call_remote_tool", input)]); + + assert.deepEqual(results.map((result) => result.status).sort(), ["fulfilled", "rejected"]); +}); + +test("the page rejects calls that are unsigned, unpaired, stale, altered or aimed at another tool", async () => { + const { relay, agent } = await pair(); + const verifier = new CallVerifier(() => [agent]); + const signed = async () => (await signCall(relay, "get_mesh_info", { a: 1 }))[CALL_FIELD]; + + await assert.rejects(verifier.verify("get_mesh_info", { a: 1 }), /only from a paired agent/); + await assert.rejects(new CallVerifier(() => []).verify("get_mesh_info", { [CALL_FIELD]: await signed() }), /no longer paired/); + await assert.rejects(verifier.verify("get_mesh_info", { [CALL_FIELD]: await signed() }, Date.now() + CALL_WINDOW_MS + 1_000), /replayed or delayed/); + await assert.rejects(verifier.verify("get_mesh_info", { [CALL_FIELD]: { ...(await signed()), body: '{"a":2}' } }), /wrong signature/); + await assert.rejects(verifier.verify("call_remote_tool", { [CALL_FIELD]: await signed() }), /wrong signature/); +}); + +test("a page reload does not run a call again: a new verifier refuses calls signed before it started", async () => { + const { relay, agent } = await pair(); + const page = new CallVerifier(() => [agent]); + const input = await signCall(relay, "call_remote_tool", { peer_id: "12D3KooW", tool: "transfer" }); + await page.verify("call_remote_tool", input); + + const reloaded = new CallVerifier(() => [agent], input[CALL_FIELD].call_unix_ms + 1); + await assert.rejects(reloaded.verify("call_remote_tool", input), /replayed or delayed/); +}); diff --git a/sdk/js/webapp/pairing.ts b/sdk/js/webapp/pairing.ts new file mode 100644 index 000000000..643fe67dd --- /dev/null +++ b/sdk/js/webapp/pairing.ts @@ -0,0 +1,158 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// A page that offers tools through the WebMCP local relay accepts calls only from +// a relay it paired with: any program on the computer can reach the relay's port. +// WebCrypto only, so the page and the relay launcher share this file. + +/** The tool a page offers so an agent can pair its relay with a token from the page. */ +export const PAIR_TOOL = "pair_agent"; +/** The argument a paired relay puts in place of a call's arguments. */ +export const CALL_FIELD = "_agentmesh"; +/** How far a call's clock may be from the page's. The page remembers nonces for twice this, while a call can still pass. */ +export const CALL_WINDOW_MS = 60_000; + +/** A call signed by a paired relay. The arguments travel as the exact text the relay signed. */ +export interface SignedCall { key_id: string; call_unix_ms: number; nonce: string; body: string; mac: string } +/** The relay's half of pairing, sent as the pair tool's arguments. */ +export interface PairRequest { name: string; relay_nonce: string; proof: string } +/** The page's answer, returned as the pair tool's text result. */ +export interface PairResponse { key_id: string; page_nonce: string; proof: string } +/** An agent the page trusts. */ +export interface PairedAgent { key_id: string; name: string; key: string; paired_time: string } + +const encoder = new TextEncoder(); + +function base64url(bytes: Uint8Array): string { + return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} + +function fromBase64url(text: string): Uint8Array { + const binary = atob(text.replaceAll("-", "+").replaceAll("_", "/")); + return Uint8Array.from(binary, (char) => char.charCodeAt(0)); +} + +/** A random value in base64url; 16 bytes is a pairing token. */ +export function randomToken(bytes = 16): string { + return base64url(crypto.getRandomValues(new Uint8Array(bytes))); +} + +function hmacKey(secret: Uint8Array): Promise { + return crypto.subtle.importKey("raw", secret, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]); +} + +async function mac(key: CryptoKey, text: string): Promise { + return base64url(new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(text)))); +} + +async function macMatches(key: CryptoKey, text: string, expected: string): Promise { + try { + return await crypto.subtle.verify("HMAC", key, fromBase64url(expected), encoder.encode(text)); + } catch { + return false; + } +} + +async function deriveKey(token: string, relayNonce: string, pageNonce: string): Promise { + const material = await crypto.subtle.importKey("raw", encoder.encode(token), "HKDF", false, ["deriveBits"]); + const salt = encoder.encode(`${relayNonce}|${pageNonce}`); + const bits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: encoder.encode("agentmesh-webapp-relay") }, material, 256); + return new Uint8Array(bits); +} + +/** The relay side of pairing: a request that proves it holds the token, then the key from the page's answer. */ +export async function startPairing(token: string, name: string): Promise<{ + request: PairRequest; + finish(response: PairResponse): Promise<{ key_id: string; key: string }>; +}> { + const tokenKey = await hmacKey(encoder.encode(token)); + const relayNonce = randomToken(); + return { + request: { name, relay_nonce: relayNonce, proof: await mac(tokenKey, `pair|${relayNonce}|${name}`) }, + async finish(response) { + if (!(await macMatches(tokenKey, `paired|${relayNonce}|${response.page_nonce}|${response.key_id}`, response.proof))) { + throw new Error("The page did not prove it holds the pairing token. Copy a fresh prompt from the page."); + } + return { key_id: response.key_id, key: base64url(await deriveKey(token, relayNonce, response.page_nonce)) }; + }, + }; +} + +/** The page side of pairing: checks the relay's proof of the token and answers with a proof of its own. */ +export async function answerPairing(token: string, request: PairRequest): Promise<{ response: PairResponse; agent: PairedAgent }> { + const tokenKey = await hmacKey(encoder.encode(token)); + if (!(await macMatches(tokenKey, `pair|${request.relay_nonce}|${request.name}`, request.proof))) { + throw new Error("The pairing token is wrong, expired or already used. Copy a fresh prompt from the page."); + } + const pageNonce = randomToken(); + const keyId = randomToken(8); + return { + response: { key_id: keyId, page_nonce: pageNonce, proof: await mac(tokenKey, `paired|${request.relay_nonce}|${pageNonce}|${keyId}`) }, + agent: { + key_id: keyId, + name: request.name, + key: base64url(await deriveKey(token, request.relay_nonce, pageNonce)), + paired_time: new Date().toISOString(), + }, + }; +} + +// No version field: agentmesh-webapp serves the page and the relay from one build, and a saved relay +// that no longer matches fails with a wrong signature, which tells the user to download it again. +function callText(tool: string, call: Omit): string { + return `call|${tool}|${call.key_id}|${call.call_unix_ms}|${call.nonce}|${call.body}`; +} + +/** The relay side of a call: the arguments a paired relay sends in place of args. */ +export async function signCall(agent: { key_id: string; key: string }, tool: string, args: Record): Promise<{ [CALL_FIELD]: SignedCall }> { + const call = { key_id: agent.key_id, call_unix_ms: Date.now(), nonce: randomToken(), body: JSON.stringify(args) }; + return { [CALL_FIELD]: { ...call, mac: await mac(await hmacKey(fromBase64url(agent.key)), callText(tool, call)) } }; +} + +/** The page side of a call: accepts each signed call once, from a paired agent, within CALL_WINDOW_MS. */ +export class CallVerifier { + readonly #agents: () => readonly PairedAgent[]; + readonly #seen = new Map(); + // Seen nonces live in memory, so a call signed before this verifier existed may be one it already ran. + readonly #since: number; + + constructor(agents: () => readonly PairedAgent[], now = Date.now()) { + this.#agents = agents; + this.#since = now; + } + + /** Returns the caller and its arguments, or throws an Error whose message the agent sees. */ + async verify(tool: string, input: Record, now = Date.now()): Promise<{ agent: PairedAgent; args: Record }> { + const call = input[CALL_FIELD] as Partial | undefined; + if (typeof call !== "object" || call === null || typeof call.body !== "string" || typeof call.mac !== "string") { + throw new Error("This node accepts calls only from a paired agent. Press Connect a local agent on the page and paste the prompt into your agent."); + } + const agent = this.#agents().find((candidate) => candidate.key_id === call.key_id); + if (agent === undefined) throw new Error("This agent is no longer paired with the node. Copy a fresh prompt from the page."); + for (const [nonce, at] of this.#seen) if (now - at > 2 * CALL_WINDOW_MS) this.#seen.delete(nonce); + if (typeof call.call_unix_ms !== "number" || call.call_unix_ms < this.#since || Math.abs(now - call.call_unix_ms) > CALL_WINDOW_MS || typeof call.nonce !== "string" || this.#seen.has(call.nonce)) { + throw new Error("Rejected a replayed or delayed call."); + } + const signed = { key_id: agent.key_id, call_unix_ms: call.call_unix_ms, nonce: call.nonce, body: call.body }; + if (!(await macMatches(await hmacKey(fromBase64url(agent.key)), callText(tool, signed), call.mac))) { + throw new Error("Rejected a call with a wrong signature. If the mesh was updated, download the relay again with the command from the page's prompt."); + } + // Checked again after the await and spent in the same step, so two copies sent together run once. + if (this.#seen.has(call.nonce)) throw new Error("Rejected a replayed or delayed call."); + this.#seen.set(call.nonce, now); + const args: unknown = JSON.parse(call.body); + if (typeof args !== "object" || args === null || Array.isArray(args)) throw new Error("A signed call's arguments must be an object."); + return { agent, args: args as Record }; + } +} diff --git a/sdk/js/webapp/relay.ts b/sdk/js/webapp/relay.ts new file mode 100644 index 000000000..f2083077b --- /dev/null +++ b/sdk/js/webapp/relay.ts @@ -0,0 +1,123 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The WebMCP local relay, paired with one Agent Mesh web app: upstream's relay and +// MCP server, with every call signed by a key only this agent and the page hold. +// Bundled as one ESM file, whose banner gives its CommonJS dependencies a require (sdk/js/package.json). +import { chmod, mkdir, readFile, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { LocalRelayMcpServer, RelayBridgeServer, parseCliOptions, type RelayBridgeServerOptions, type RelayCallToolResult, type RelayInvokeArgs } from "@mcp-b/webmcp-local-relay"; +import { PAIR_TOOL, signCall, startPairing, type PairResponse } from "./pairing.ts"; + +const log = (line: string) => process.stderr.write(`[agentmesh-webapp-relay] ${line}\n`); +const failure = (text: string): RelayCallToolResult => { + log(`refused: ${text}`); + return { isError: true, content: [{ type: "text", text }] }; +}; + +/** The key this agent shares with one page, in a file only its user reads. */ +class KeyStore { + readonly #dir: string; + readonly #file: string; + + constructor(origin: string, name: string) { + // Percent-encoding keeps distinct names distinct; "*" is the one character it keeps that Windows refuses. + const safe = (text: string) => encodeURIComponent(text).replaceAll("*", "%2A"); + this.#dir = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "agentmesh", "webapp-relay", safe(new URL(origin).host)); + this.#file = join(this.#dir, `${safe(name)}.json`); + } + + async load(): Promise<{ key_id: string; key: string } | undefined> { + try { + return JSON.parse(await readFile(this.#file, "utf8")) as { key_id: string; key: string }; + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw err; + } + } + + async save(key: { key_id: string; key: string }): Promise { + await mkdir(this.#dir, { recursive: true, mode: 0o700 }); + // writeFile's mode applies only to a new file, so an existing one is narrowed before the key lands in it. + await chmod(this.#file, 0o600).catch((err: NodeJS.ErrnoException) => { + if (err.code !== "ENOENT") throw err; + }); + await writeFile(this.#file, JSON.stringify(key), { mode: 0o600 }); + log(`paired; key ${key.key_id} saved to ${this.#file}`); + } +} + +/** Pairs on the pair tool and signs every other call, so the page can tell this agent from any other program. */ +class SigningBridge extends RelayBridgeServer { + readonly #name: string; + readonly #keys: KeyStore; + + constructor(options: RelayBridgeServerOptions, name: string, keys: KeyStore) { + super(options); + this.#name = name; + this.#keys = keys; + } + + override async invokeTool(toolName: string, args: RelayInvokeArgs, options?: { signal?: AbortSignal }): Promise { + if (toolName === PAIR_TOOL) return this.#pair(args, options); + const key = await this.#keys.load(); + if (key === undefined) return failure(`This relay is not paired yet. Call ${PAIR_TOOL} with the token from the Agent Mesh page's Local agent card.`); + return super.invokeTool(toolName, await signCall(key, toolName, args), options); + } + + async #pair(args: RelayInvokeArgs, options?: { signal?: AbortSignal }): Promise { + const token = typeof args.token === "string" ? args.token.trim() : ""; + if (token === "") return failure(`${PAIR_TOOL} needs the token from the prompt.`); + const pairing = await startPairing(token, this.#name); + const result = await super.invokeTool(PAIR_TOOL, { ...pairing.request }, options); + if (result.isError) { + log(`the page refused to pair: ${result.content.find((part) => part.type === "text")?.text ?? ""}`); + return result; + } + const text = result.content.find((part) => part.type === "text")?.text ?? ""; + try { + await this.#keys.save(await pairing.finish(JSON.parse(text) as PairResponse)); + } catch (err) { + return failure(err instanceof Error ? err.message : String(err)); + } + return { content: [{ type: "text", text: `Paired with the Agent Mesh page as "${this.#name}". Its tools now run as that node.` }] }; + } +} + +const argv = process.argv.slice(2); +const rest: string[] = []; +let name = ""; +for (let i = 0; i < argv.length; i++) { + const arg = argv[i] ?? ""; + if (arg === "--agent-name") name = argv[++i] ?? ""; + else if (arg.startsWith("--agent-name=")) name = arg.slice("--agent-name=".length); + else rest.push(arg); +} +name = name.trim(); +const options = parseCliOptions(rest); +const origin = options.allowedOrigins.length === 1 ? options.allowedOrigins[0] : undefined; +if (name === "" || origin === undefined || origin === "*") { + log("usage: agentmesh-webapp-relay --widget-origin --agent-name "); + process.exit(2); +} + +const relay = new LocalRelayMcpServer({ bridge: new SigningBridge(options, name, new KeyStore(origin, name)), serverName: "agentmesh-webapp" }); +await relay.start(); +await relay.startStdio(); +log(`${relay.bridge.mode} mode on 127.0.0.1:${relay.bridge.port}, for ${origin} as "${name}"`); +const shutdown = () => void relay.stop().finally(() => process.exit(0)); +process.stdin.on("end", shutdown); +process.on("SIGINT", shutdown); +process.on("SIGTERM", shutdown); diff --git a/sdk/js/webapp/webmcp.test.ts b/sdk/js/webapp/webmcp.test.ts new file mode 100644 index 000000000..0e93c5bec --- /dev/null +++ b/sdk/js/webapp/webmcp.test.ts @@ -0,0 +1,100 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { peerIdFromString } from "@libp2p/peer-id"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { Identity } from "../src/identity.ts"; +import { createMeshMCPServer, meshTools } from "../src/mcp-server.ts"; +import { CallVerifier, signCall, type PairedAgent } from "./pairing.ts"; +import { registerWebMCPTools, type CallLog, type ModelContext } from "./webmcp.ts"; + +type Registered = Parameters[0]; + +const agent: PairedAgent = { key_id: "k1", name: "Test Agent", key: Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url"), paired_time: "2026-11-23T00:00:00Z" }; + +function recorder(): CallLog & { lines: string[] } { + const lines: string[] = []; + return { lines, called: (tool, by) => { lines.push(`${by.name} called ${tool}`); }, refused: (tool) => { lines.push(`refused ${tool}`); } }; +} + +test("WebMCP offers the stdio server's five tools, with the same schemas, to signed calls only, until the signal aborts", async (t) => { + const self = Identity.generate().peerId; + const peer = Identity.generate().peerId; + const session = { + peerId: self, routers: [], isHeldRouter: () => false, + node: { getPeers: () => [peerIdFromString(peer)] }, + async discover() { return []; }, + async openMCP(): Promise { throw new Error("no remote peers in this test"); }, + }; + const registered: Registered[] = []; + const signals: AbortSignal[] = []; + const modelContext: ModelContext = { registerTool(tool, options) { registered.push(tool); signals.push(options.signal); } }; + const controller = new AbortController(); + const log = recorder(); + + await registerWebMCPTools(modelContext, meshTools(session), new CallVerifier(() => [agent]), log, controller.signal); + + const [a, b] = InMemoryTransport.createLinkedPair(); + const stdio = createMeshMCPServer(session, "1"); + const client = new Client({ name: "test", version: "1" }); + await stdio.connect(a); + await client.connect(b); + t.after(async () => { await client.close(); }); + const listed = (await client.listTools()).tools; + assert.deepEqual( + registered.map((tool) => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema })), + listed.map((tool) => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema })), + ); + assert.equal(registered.length, 5); + assert.ok(signals.every((signal) => signal === controller.signal), "every registration ends with the caller's signal"); + + const info = registered.find((tool) => tool.name === "get_mesh_info")!; + const unsigned = await info.execute({}); + assert.deepEqual(unsigned, { isError: true, content: [{ type: "text", text: "This node accepts calls only from a paired agent. Press Connect a local agent on the page and paste the prompt into your agent." }] }); + const result = await info.execute(await signCall(agent, "get_mesh_info", {})); + assert.deepEqual(JSON.parse((result.content[0] as { text: string }).text), { peer_id: self, connected_peers: [peer], attached_routers: [], router_peer_id: "" }); + const invalid = await registered.find((tool) => tool.name === "call_remote_tool")!.execute(await signCall(agent, "call_remote_tool", { tool_name: "mcp://calc/add" })); + assert.equal(invalid.isError, true, "input that fails the schema is a tool error, not a call"); + assert.deepEqual(log.lines, ["refused get_mesh_info", "Test Agent called get_mesh_info", "Test Agent called call_remote_tool"]); + + controller.abort(); + assert.equal((await info.execute(await signCall(agent, "get_mesh_info", {}))).isError, true, "a tool held past the abort no longer reaches the session"); +}); + +test("an agent's cancel stops that call on the mesh", async () => { + let reached = () => {}; + const reachedMesh = new Promise((resolve) => { reached = resolve; }); + const session = { + peerId: Identity.generate().peerId, routers: [], isHeldRouter: () => false, + node: { getPeers: () => [] }, + async discover() { return []; }, + openMCP(_peer: string, _service: string, options: { signal?: AbortSignal }): Promise { + reached(); + return new Promise((_resolve, reject) => { options.signal?.addEventListener("abort", () => { reject(options.signal?.reason); }, { once: true }); }); + }, + }; + const registered: Registered[] = []; + await registerWebMCPTools({ registerTool(tool) { registered.push(tool); } }, meshTools(session), new CallVerifier(() => [agent]), recorder(), new AbortController().signal); + const cancel = new AbortController(); + + const input = await signCall(agent, "describe_remote_tool", { peer_id: Identity.generate().peerId, tool_name: "mcp://calc/add" }); + const pending = registered.find((tool) => tool.name === "describe_remote_tool")!.execute(input, { signal: cancel.signal }); + await reachedMesh; + cancel.abort(new Error("the agent cancelled")); + + assert.deepEqual((await pending).content, [{ type: "text", text: "the agent cancelled" }]); +}); diff --git a/sdk/js/webapp/webmcp.ts b/sdk/js/webapp/webmcp.ts new file mode 100644 index 000000000..9c3ff98d5 --- /dev/null +++ b/sdk/js/webapp/webmcp.ts @@ -0,0 +1,70 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// WebMCP gives the web app's tools to an agent on the same computer through the +// local relay. Any program there can reach the relay, so a call runs only when a +// paired agent signed it. Built into the page's bundle only; npm does not ship it. +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import * as z from "zod"; +import type { MeshTool } from "../src/mcp-server.ts"; +import type { CallVerifier, PairedAgent } from "./pairing.ts"; + +/** The part of document.modelContext this module uses. */ +export interface ModelContext { + registerTool(tool: { + name: string; + description: string; + inputSchema: object; + execute(input: Record, options?: { signal: AbortSignal }): Promise; + }, options: { signal: AbortSignal }): unknown; +} + +/** What the page records about the calls: each one it ran, and each one it refused. */ +export interface CallLog { + called(tool: string, agent: PairedAgent, args: Record): void; + refused(tool: string, reason: string): void; +} + +const failure = (text: string): CallToolResult => ({ isError: true, content: [{ type: "text", text }] }); +const messageOf = (err: unknown) => (err instanceof Error ? err.message : String(err)); + +/** Registers the tools with modelContext until signal aborts, which also cancels their calls. */ +export async function registerWebMCPTools(modelContext: ModelContext, tools: MeshTool[], verifier: CallVerifier, log: CallLog, signal: AbortSignal): Promise { + for (const tool of tools) { + signal.throwIfAborted(); + const schema = z.object(tool.inputSchema); + await modelContext.registerTool({ + name: tool.name, + description: tool.description, + // The JSON Schema the stdio server lists for the same tool. + inputSchema: z.toJSONSchema(schema, { target: "draft-7", io: "input" }), + // The agent cancels one call through options; signal withdraws every tool. + async execute(input, options) { + let call; + try { + call = await verifier.verify(tool.name, input); + } catch (err) { + log.refused(tool.name, messageOf(err)); + return failure(messageOf(err)); + } + log.called(tool.name, call.agent, call.args); + try { + return await tool.run(schema.parse(call.args), { signal: options === undefined ? signal : AbortSignal.any([signal, options.signal]) }); + } catch (err) { + return failure(messageOf(err)); + } + }, + }, { signal }); + } +} diff --git a/sdk/python/src/agent_mesh/mesh.py b/sdk/python/src/agent_mesh/mesh.py index 392fed4a2..7ec1394da 100644 --- a/sdk/python/src/agent_mesh/mesh.py +++ b/sdk/python/src/agent_mesh/mesh.py @@ -246,7 +246,7 @@ def load( def refresh(self) -> MeshCredential: """Trades the current biscuit for a fresh one and persists it. The control plane redeems only the last biscuit it issued, so a lost refresh result - means re-enrolling; persisting before returning keeps that rare.""" + means re-enrolling; persisting as soon as /refresh answers, before /keys, keeps that rare.""" with self._lock: fresh_jwt: Optional[str] = None if self._jwt_source is not None: @@ -257,18 +257,15 @@ def refresh(self) -> MeshCredential: except Exception: # noqa: BLE001 - fall back to session-only refresh if token source is unavailable pass result = self.control_plane.refresh(self.identity, self._credential.biscuit, jwt=fresh_jwt) + # Saved before /keys: the old biscuit is spent, so a process that stops in between must already hold the new one. + self._credential = replace(self._credential, biscuit=result.biscuit, expiration=result.expiration) + self.save() control_plane_keys = self._credential.control_plane_keys try: control_plane_keys = self.control_plane.keys(control_plane_keys) except Exception: # noqa: BLE001 - a failed /keys sync must not cost the new biscuit pass - self._credential = replace( - self._credential, - biscuit=result.biscuit, - expiration=result.expiration, - control_plane_keys=control_plane_keys, - issued_under_keys=list(control_plane_keys), - ) + self._credential = replace(self._credential, control_plane_keys=control_plane_keys, issued_under_keys=list(control_plane_keys)) self.save() return self._credential diff --git a/sdk/python/tests/test_mesh.py b/sdk/python/tests/test_mesh.py index b80f35672..4c7301cb8 100644 --- a/sdk/python/tests/test_mesh.py +++ b/sdk/python/tests/test_mesh.py @@ -14,6 +14,7 @@ import base64 import json +import shutil import stat import threading import time @@ -55,8 +56,9 @@ def __init__(self, keys_ok=True, strict_refresh=False, refresh_delay=0.0): self.refresh_delay = refresh_delay self.last_biscuit = b"" self.last_refresh_jwt = "" - # What /keys serves and signs with; a test rotates by replacing it. + # What /keys serves and signs with; a test rotates by replacing it. on_keys runs when /keys is asked. self.keys = [CP_KEY] + self.on_keys = None self._lock = threading.Lock() def _issue(self, biscuit): @@ -101,6 +103,8 @@ def transport(self, method, url, headers, body): biscuit = self._issue(token_bytes) return 200, pb.TokenRefreshResponse(biscuit_token=biscuit, expire_time=_ts_s(int(time.time()) + 7200)).SerializeToString() if (method, path) == ("GET", "/keys"): + if self.on_keys is not None: + self.on_keys() return (200, self._signed_keys().SerializeToString()) if self.keys_ok else (500, b"boom") return 404, f"no route for {method} {path}".encode() @@ -211,6 +215,23 @@ def test_enroll_without_state_dir_keeps_enrollment_key_when_keys_fails(): assert mesh.credential.biscuit == b"biscuit-2" +def test_refresh_saves_the_new_biscuit_before_it_asks_for_keys(tmp_path): + """The control plane spends the old biscuit when it answers /refresh, so a + process stopped before the save could never refresh again.""" + cp = FakeControlPlane(strict_refresh=True) + state = tmp_path / "state" + stopped = tmp_path / "stopped" + mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt_secret", state_dir=state, transport=cp.transport) + # What a process stopped while /keys is asked leaves on disk. + cp.on_keys = lambda: shutil.copytree(state, stopped) + mesh.refresh() + cp.on_keys = None + + restarted = AgentMesh.load(stopped, transport=cp.transport) + restarted.refresh() + assert restarted.credential.biscuit == b"biscuit-3" + + def test_concurrent_refreshes_run_one_after_the_other(tmp_path): """A session refreshes the credential from one worker thread and pulls from the control plane, which may refresh too, from another. The control diff --git a/site/content/docs/_index.md b/site/content/docs/_index.md index 3937dc4d4..9593e3299 100644 --- a/site/content/docs/_index.md +++ b/site/content/docs/_index.md @@ -45,7 +45,7 @@ Two rules apply to every mesh: - [Use cases](use-cases/) are worked examples of things built on top of the mesh. - [Preview](preview/) covers features that work today but whose interfaces - may still change: sandboxed agents and the mobile app. + may still change: sandboxed agents, the mobile app and the web app. - [Contributing](contributing/) covers building, testing and changing Agent Mesh itself. diff --git a/site/content/docs/concepts/architecture.md b/site/content/docs/concepts/architecture.md index c73e4136c..83dd5a747 100644 --- a/site/content/docs/concepts/architecture.md +++ b/site/content/docs/concepts/architecture.md @@ -151,17 +151,22 @@ the caller's credential must also satisfy. ## Packaging -The same three programs ship in several forms: +The programs ship in several forms: - **Binaries** for Linux, macOS and Windows, from the releases page or the install script. - **Container images**: `ghcr.io/google/agentmesh-control-plane`, - `agentmesh-router`, `agentmesh-node`, `agentmesh-console` and `agentmesh-one`. -- **`agentmesh-one`**, a single binary that runs the control plane, a router and - the console in one process on one port, for laptops, Cloud Run and small + `agentmesh-router`, `agentmesh-node`, `agentmesh-console`, `agentmesh-webapp` + and `agentmesh-one`. +- **`agentmesh-one`**, a single binary that runs the control plane, a router + and the console in one process on one port, for laptops, Cloud Run and small meshes. - **Helm charts**: `agentmesh` deploys the control plane, router, console and PostgreSQL. `agentmesh-node` deploys a node beside a service container. + `agentmesh-webapp` deploys the web app. The web console (`agentmesh-console`) is a separate program that talks to the -control plane's admin API. It is not required to run a mesh. +control plane's admin API. It is not required to run a mesh. The web app +(`agentmesh-webapp`) is a separate program too. It serves the page that puts a +browser on a mesh, and it is tied to no mesh: the person using the page enters +the control plane's address. diff --git a/site/content/docs/contributing/_index.md b/site/content/docs/contributing/_index.md index 26ffdee18..2d678f031 100644 --- a/site/content/docs/contributing/_index.md +++ b/site/content/docs/contributing/_index.md @@ -18,10 +18,10 @@ in the repository has the details. | Path | Contents | |---|---| -| `cmd/` | One directory per binary: `agentmesh-node`, `agentmesh-control-plane`, `agentmesh-router`, `agentmesh-one`, `agentmesh-console`, `mcp-client`, `agentmesh-bench`, and smaller tools. | +| `cmd/` | One directory per binary: `agentmesh-node`, `agentmesh-control-plane`, `agentmesh-router`, `agentmesh-one`, `agentmesh-console`, `agentmesh-webapp`, `mcp-client`, `agentmesh-bench`, and smaller tools. | | `api/` | The wire contract: `agentmesh.proto` and its generated code, plus the Go types for the JSON admin API and the validation and Datalog helpers both sides share. | | `internal/` | Implementation, one package per component (`node`, `controlplane`, `router`, `standalone`, `console`, `identity`, `storage`, ...). | -| `charts/` | The `agentmesh` and `agentmesh-node` Helm charts. | +| `charts/` | The `agentmesh`, `agentmesh-node` and `agentmesh-webapp` Helm charts. | | `tests/integration/` | Go tests that start several components in one process. | | `tests/e2e/` | Bats tests that drive the built binaries and containers. | | `development/` | The kind environment and example services. | diff --git a/site/content/docs/preview/_index.md b/site/content/docs/preview/_index.md index ef1b01bf6..4c18fce0a 100644 --- a/site/content/docs/preview/_index.md +++ b/site/content/docs/preview/_index.md @@ -17,6 +17,8 @@ you find. identity, and how an agent serves. - [Agent Mesh Connect](mobile/): the Android and iOS app that turns a phone into a node. +- [Agent Mesh Connect web app](webapp/): the page `agentmesh-webapp` serves, + which puts a browser on a mesh and lets a local agent use it. Everything outside this section (the node, the routers, the control plane, identity, policy and the deployment guides) is the stable core. diff --git a/site/content/docs/preview/webapp.md b/site/content/docs/preview/webapp.md new file mode 100644 index 000000000..806549a4c --- /dev/null +++ b/site/content/docs/preview/webapp.md @@ -0,0 +1,320 @@ +--- +title: "Agent Mesh Connect (web)" +linkTitle: "Agent Mesh Connect web app" +weight: 4 +--- + +{{% alert title="Preview" color="warning" %}} +The Agent Mesh Connect web app is a page that `agentmesh-webapp` serves. It +puts the browser on a mesh as a member and needs no install. It does not offer +services. +{{% /alert %}} + +The web app runs the [JavaScript SDK](../../guides/native-sdks/) in a browser +page. It belongs to no mesh: you enter the address of the mesh's control +plane, or open a join link that carries it. The page enrolls with an enrollment token, or with the account you sign +in with when the mesh has a sign-in provider. It keeps its key and credential +in the browser's storage, and joins the mesh through the router over a secure +WebSocket or WebTransport. A browser enrolled this way is a member like any +other. It has a key, a credential and a peer ID, which the app calls the +**Node ID**. + +## Join the mesh from a browser + +You need a mesh, `agentmesh-webapp` and a current browser. A browser on +another machine must reach both the mesh and the page over `https`, because a +page served over plain `http` from another machine is not a secure context +and cannot hold a key. On one computer, `http://127.0.0.1` works for both. + +1. Start a mesh. For a browser on another machine, give it a public `https` + address. With `agentmesh-one`, a Cloudflare quick tunnel needs no account: + + ```bash + agentmesh-one --data-dir ~/agentmesh-one --tunnel cloudflare --tunnel-install + ``` + + Expect: the banner shows the mesh's address on its **API URL** line, and a + `mesh://enroll?server=…&token=…` code under the QR code. + +2. Start the web app: + + ```bash + agentmesh-webapp + ``` + + Expect: `Agent Mesh web app listening on 127.0.0.1:8082`. + +3. For a browser on another machine, put the page behind `https`, for example + with a second quick tunnel: + + ```bash + cloudflared tunnel --url http://127.0.0.1:8082 + ``` + + Expect: cloudflared prints the page's `https://….trycloudflare.com` address. + +4. Open the page's address in the browser. + + Expect: the welcome screen, with **Mesh address** and **Enrollment link, + code or token**. + +5. Paste the `mesh://enroll` code into **Enrollment link, code or token** and + tap **Join with token**. The code carries the mesh's address and a + single-use token. Or enter the **API URL** in **Mesh address** and paste + a token: the banner's **Join Token** admits any number of devices, and + `agentmesh-one token create --data-dir ~/agentmesh-one --server ` + mints a single-use one. + + Expect: a dialog that names the mesh's address. Tap **Join**. + + Expect: the dashboard shows **Node is Running**, the **Node ID** and the + number of **Routers** that hold a relay slot for the browser. + +A link of the form `#server=&token=` joins +the same way. The values travel after the `#`, which browsers never send to a +server, and the page removes them from the address bar before it does +anything else. A link with `#server=` alone fills in **Mesh +address**, so the mesh's **Sign in** shows at once. + +A browser belongs to one mesh at a time. Once it has joined, **Mesh address** +is fixed, and the page refuses a code or link for another mesh. **Reset +device identity** frees it. + +Every browser gets its own Node ID. The key lives in the storage of the +browser that enrolled, and browsers do not share it. + +## What the screens show + +Before the browser enrolls, the app shows only the welcome view: **Mesh +address**, **Sign in** when that mesh has a sign-in provider, the field for +the enrollment link, code or token, and the optional **Labels** the control +plane attests at enrollment. +The tabs appear once the browser has enrolled. + +| Tab | What it shows | +| --- | --- | +| **Dashboard** | **Node is Running** or **Node is Stopped**, the mesh's address, **Connected Peers**, **Routers**, the **Node ID**, and **Start** and **Stop**. **Unenroll / Clear Identity** is at the bottom. | +| **Config** | **Device**: the labels this browser enrolled with, whether the browser keeps the storage, and until when the current credential is valid. On a computer, **Local agent** connects an agent on that computer. The version is at the bottom. | + +**Routers** counts the routers that hold a relay slot for the browser, +because peers reach it through them. + +The node runs only while the page is open. The app remembers whether you left +it running. If you did, it rejoins on its own the next time it opens, with the +same Node ID. If you pressed **Stop**, it waits for **Start**. + +Install the app to keep its storage: in Chrome or Edge, use **Install app** in +the menu; in Safari, use **Add to Home Screen** or **Add to Dock**. Safari +deletes a site's storage after seven days without a visit, which deletes the +identity with it. The **Config** tab shows whether the browser has promised +to keep it. + +## Coming back after a day or more + +The credential lasts 24 hours, and the app renews it while it is open. A +credential that lapsed while the app was closed is renewed when the app +opens. + +The mesh also rotates its signing key every 24 hours and keeps the old key +for one more hour. A credential issued under a key that retired cannot be +renewed. So a browser that stayed closed for more than about 25 hours shows +**The mesh no longer accepts this device** and **Rejoin the mesh**. Paste a +new token or code from `agentmesh-one token create`, tap **Join with token**, then +**Join**, or tap **Sign in** again. The browser keeps its Node ID. A banned +device cannot rejoin with its key. **Unenroll / Clear Identity** on that screen resets it, and so does +**Reset device identity** on the welcome screen of a browser that kept its key. + +An operator who accepts the risk can mint tokens with `token create +--autonomous-recovery`. Browsers enrolled with such a token keep renewing after +a rotation, and a lost device then keeps renewing until an operator bans it. + +## Unenroll and reset the device identity + +**Unenroll / Clear Identity** opens a dialog with two choices: + +- **Unenroll** deletes the credential and keeps the key. The next enrollment, + with any token, brings back the same Node ID. +- **Reset device identity** also deletes the key and frees **Mesh address**. + The next enrollment looks like a device the mesh has never seen, and it can + be into another mesh. + +Both are local. The control plane keeps the node's record until an operator +revokes or bans it in the console. + +## Where the identity lives + +The key and the credential are in the browser's storage for the page's +address. Clearing the site's data in the browser deletes them. Two +consequences follow, because a Cloudflare quick tunnel gets a new address +every time it starts: + +- A new page address is a new site to the browser, so the browser enrolls + again. +- A new mesh address is another mesh to the page. The browser must **Reset + device identity**, then enroll again. + +For a page and a mesh that browsers stay with, use named tunnels or fixed +addresses. + +Only one tab or window of the app runs at a time. A second one shows **Agent +Mesh is open in another tab or window** and offers **Use here**, which takes +over and stops the first. + +## Sign in with your account + +When the control plane has a sign-in provider, the welcome screen shows +**Sign in with** and the provider's host. The browser then joins with the +account you sign in with, and needs no token. Once **Mesh address** holds the +mesh's address, the app asks that control plane's `/info` for the provider, +and shows the button only if the provider's discovery document answers the +page. + +1. Tap **Sign in with** and the provider's host. + + Expect: the provider's sign-in page. + +2. Sign in. + + Expect: the app opens again and shows **Node is Running**. + +The control plane renews the credential without a new sign-in until the +session ends. The session lasts 90 days, which `agentmesh-control-plane` +changes with `--oidc-session-ttl`. After that, or after a key rotation the +browser missed, the app shows **Rejoin the mesh** and **Sign in** again. The +browser keeps its Node ID. + +The operator sets up four things: + +- `agentmesh-one` or `agentmesh-control-plane` runs with `--issuer`, the + provider's issuer URL. +- The provider has a public client for the client ID the control plane + advertises: `--oidc-client-id`, or else the first of `--allowed-audiences`. + The client lists the page's address, such as `https://app.example.com/`, + as a redirect URI. +- The provider allows requests from the page's origin, such as + `https://app.example.com`, to its discovery and token endpoints. In Dex, + that is `web.allowedOrigins`. +- The mesh policy binds `mesh:role:node` to the people who may join, or to + `mesh:system:authenticated` for everyone the provider signs in. + +## Use the node from an agent on your computer + +On a computer, the app can offer the node to an MCP agent that runs on the same +computer, such as Claude Code or Cursor. The agent gets the five tools +`agentmesh-node` serves on `/mcp`: `get_mesh_info`, `discover_remote_services`, +`find_remote_tools`, `describe_remote_tool` and `call_remote_tool`. Its calls +use this node's identity and the mesh policy. A device whose only pointer is a +touch screen, such as a phone, does not show this option. + +The agent reaches the page through a local relay, a program that runs beside +the agent and needs Node.js 22. The web app serves the relay as one +JavaScript file at `sdk/agentmesh-relay.mjs` under the page's address. It is built on the +[WebMCP local relay](https://docs.mcp-b.ai/packages/webmcp-local-relay). You +save it once, so starting the agent runs that copy and downloads nothing. +The agent pairs with the page once, and the page then runs only calls that the +paired agent signed. + +1. Open the app on the computer, open the **Config** tab and press + **Connect a local agent**. + + Expect: the card shows a prompt for your agent, with a pairing token and + the time it expires. + +2. Copy the prompt and paste it into your agent. The prompt works with any + MCP agent. It asks the agent to: + 1. save the relay as `~/.local/share/agentmesh/webapp-relay/relay.mjs`, + with a `node -e` command that works on any system; + 2. add the relay as a local MCP server named `agentmesh-webapp`; + 3. call `pair_agent` with the token, then `get_mesh_info`. + + The agent asks you once to approve the first two steps, then works + without asking again. An agent that cannot change its configuration tells + you what to add. + +3. If the agent loads MCP servers only when it starts, restart it when it + asks. With Claude Code, quit it and run `claude --continue` to come back + to the same conversation, then ask it to go on. + + Expect: the card lists the agent by name, the agent shows a `peer_id` + equal to the app's **Node ID**, and the Dashboard shows **Local agent … + connected** with the agent's last call. + +The token works once. If nobody uses it within 10 minutes, the page replaces +it and the prompt changes. An agent that uses an old token gets **The +pairing token is wrong, expired or already used**. Copy the prompt again. + +To add the relay by hand, open **Add the relay by hand** on the card. It shows +the download command and the server in the `mcpServers` form that most agents' +configuration files take. Write `~` as your home folder's full path, because +an agent starts the server without a shell. With Claude Code, run the download +command from the card, then: + +```bash +claude mcp add agentmesh-webapp -- node ~/.local/share/agentmesh/webapp-relay/relay.mjs --widget-origin https://app.example.com --agent-name "Claude Code" +``` + +Then paste the prompt, so the agent pairs. + +If the agent's calls fail with **wrong signature** after the mesh is updated, +run the download command again and restart the agent's MCP server. + +One relay serves one page on a computer. Open the app in one browser at a +time while an agent is connected, and use one mesh at a time. + +Keep the app open with the node running while the agent uses the tools. If +the agent restarts, the open page finds the new relay within a few seconds. + +The relay keeps the key it shares with the page in +`~/.config/agentmesh/webapp-relay//.json`, which only +your user can read. The page keeps the same key in the browser's storage. A +restarted agent or a reloaded page stays paired. To pair a second agent, press +**Pair another agent**. **Forget** next to an agent deletes its key in the +page, and that agent must pair again. + +The **Local agent** card lists the last calls, which agent made each one and +what it aimed at, such as +`Claude Code: call_remote_tool mcp://calc/add on 12D3KooW…xYz`. + +The relay listens on `127.0.0.1`, and the page connects to it. `--widget-origin` +makes the relay accept only this app. A program under your own user account can +read the relay's key file and the node's key in the browser's storage, the same +as with `agentmesh-node`'s API token. A program under another user account +cannot call the tools without the key. If it takes the relay's port before your +agent does, it can still read the tool list, and read and change the results of +your calls. +Chrome may ask whether the page can reach devices on your local network; allow +it for this app. **Disconnect local agent** withdraws the tools. + +## Requirements + +- An `https` address for the page and for the mesh. On one computer, + `http://127.0.0.1` works for both, which is handy for development. +- A current Chrome, Edge, Firefox or Safari. + +## Build and deploy the app + +The app's own files are in `internal/webapp/public` and are embedded in +`agentmesh-webapp`. `make all` builds the SDK bundle they import from +`sdk/js`, which needs Node.js 22, and then the binaries: + +```bash +make all +``` + +The container image builds it too. `make build` builds the binaries only. +`agentmesh-webapp` still runs: it logs a warning, and the page tells whoever +opens it that the app is missing. + +`agentmesh-webapp` serves the page at `/` and knows no mesh. One deployment +serves any mesh. Its image is `ghcr.io/google/agentmesh-webapp`, and the +`agentmesh-webapp` Helm chart deploys it, with an optional Gateway. + +| Flag | Default | Meaning | +|---|---|---| +| `--bind-addr` | `127.0.0.1:8082` | HTTP listen address. Set `:8082` in a container. | +| `--version` | | Print the version and exit. | + +The page loads its files relative to its own address, so a proxy can serve it +under a prefix, such as `/node/`, if it strips the prefix before +`agentmesh-webapp`. Serve it over `https` for devices other than the one it +runs on. diff --git a/tests/ui/app.spec.js b/tests/ui/app.spec.js new file mode 100644 index 000000000..d53f9b9c5 --- /dev/null +++ b/tests/ui/app.spec.js @@ -0,0 +1,643 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const { test, expect, chromium } = require('@playwright/test'); +const { execFileSync } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const stack = require('./lib/agentmesh-one'); +const { startMockOIDC } = require('./lib/mock-oidc'); + +test.use({ ignoreHTTPSErrors: true }); +test.describe.configure({ mode: 'serial' }); +test.setTimeout(120_000); + +// The page comes from agentmesh-webapp, on an origin apart from every mesh it joins. +let app; +test.beforeAll(async () => { + if (!stack.missing().startsWith('bin/')) app = await stack.startWebapp(); +}); +test.afterAll(() => app?.stop()); + +/** The page with a join link for mesh: #server=…&token=…, or #server=… alone when token is null. */ +const linkTo = (mesh, token = mesh.joinToken) => + `${app.url}#server=${encodeURIComponent(mesh.publicUrl)}${token === null ? '' : `&token=${encodeURIComponent(token)}`}`; + +async function watchCSP(page) { + await page.addInitScript(() => { + window.__cspViolations = []; + document.addEventListener('securitypolicyviolation', (e) => window.__cspViolations.push(`${e.violatedDirective} ${e.blockedURI}`)); + }); +} + +async function noViolations(page) { + expect(await page.evaluate(() => window.__cspViolations)).toEqual([]); +} + +const nodeTitle = (page) => page.locator('#node-title'); +const nodeId = async (page) => (await page.locator('#node-id').textContent()).trim(); + +async function joinFromDialog(page, token) { + const dialog = page.locator('#join-dialog'); + await expect(dialog).toBeVisible(); + await expect(dialog.locator('#join-token')).toHaveText(`${token.slice(0, 12)}…`); + await dialog.getByRole('button', { name: 'Join' }).click(); + await expect(nodeTitle(page)).toHaveText('Node is Running', { timeout: 30_000 }); +} + +/** Types the mesh address the way a person does; leaving the field asks that mesh for its Sign in. */ +async function enterServer(page, url) { + await page.locator('#server-input').fill(url); + await page.locator('#server-input').blur(); +} + +async function pasteCode(page, text) { + await page.locator('#offer-input').fill(text); + await page.getByRole('button', { name: 'Join with token' }).click(); +} + +const topologies = [ + { name: 'direct', edge: false }, + { name: 'behind a TLS edge', edge: true }, +]; + +for (const topology of topologies) { + test(`a scanned link enrolls, joins and resumes after a reload (${topology.name})`, async ({ page }) => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + + const stops = []; + try { + let samOne; + if (topology.edge) { + const cert = stack.selfSignedCert('localhost'); + test.skip(cert === null, 'openssl is not installed'); + const edgePort = await stack.freePort(); + samOne = await stack.startSamOne({ externalUrl: `https://localhost:${edgePort}` }); + stops.push(() => samOne.stop()); + const edge = await stack.startTLSEdge({ host: 'localhost', origin: samOne.localUrl.replace('http://', ''), cert: cert.cert, key: cert.key, port: edgePort }); + stops.push(() => edge.stop()); + } else { + samOne = await stack.startSamOne(); + stops.push(() => samOne.stop()); + } + await watchCSP(page); + + await page.goto(linkTo(samOne)); + const historyLength = await page.evaluate(() => history.length); + await expect(page.locator('#join-server')).toHaveText(samOne.publicUrl); + expect(page.url(), 'the token stayed in the address bar').toBe(app.url); + await joinFromDialog(page, samOne.joinToken); + expect(await page.evaluate(() => history.length), 'stripping the token added a history entry').toBe(historyLength); + + const peer = await nodeId(page); + expect(peer).toMatch(/^12D3Koo/); + // The config grants the clipboard permissions. + await page.locator('#copy-id').click(); + await expect(page.locator('#copy-id')).toHaveAccessibleName('Copied'); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(peer); + await expect(page.locator('#stat-routers')).toHaveText('1'); + await expect(page.locator('#mesh-host')).toHaveText(new URL(samOne.publicUrl).host); + + // The address follows the saved credential, even when the page never saved it. + await page.evaluate(() => { + const prefs = JSON.parse(localStorage.getItem('agentmesh-app.prefs')); + delete prefs.server; + localStorage.setItem('agentmesh-app.prefs', JSON.stringify(prefs)); + }); + // The page loads again from a link for another mesh, which the lock from the credential refuses. + // A goto that changes only the fragment does not load the page again. + await page.goto('about:blank'); + await page.goto(`${app.url}#server=${encodeURIComponent('https://other.example.com')}&token=mesh_dev_x`); + await expect(nodeTitle(page)).toHaveText('Node is Running', { timeout: 30_000 }); + expect(await nodeId(page)).toBe(peer); + await expect(page.locator('#mesh-host')).toHaveText(new URL(samOne.publicUrl).host); + await expect(page.locator('#offer-error')).toHaveText(`This device belongs to the mesh at ${new URL(samOne.publicUrl).host}. Reset device identity to join another mesh.`); + await expect(page.locator('#join-dialog')).toBeHidden(); + await noViolations(page); + } finally { + for (const stop of stops.reverse()) { + await stop(); + } + } + }); +} + +test('a local agent pairs with the node through the relay, and only its signed calls run', async ({ browser }) => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + const stops = []; + const configHome = fs.mkdtempSync(path.join(os.tmpdir(), 'agentmesh-relay-keys-')); + stops.push(() => fs.rmSync(configHome, { recursive: true, force: true })); + try { + const samOne = await stack.startSamOne(); + stops.push(() => samOne.stop()); + const origin = new URL(app.url).origin; + await stack.assertRelayPortFree(); + let relay; + stops.push(() => relay?.stop()); + const tools = async () => (await relay.client.listTools()).tools.map((tool) => tool.name); + const callRaw = (name, args) => relay.client.callTool({ name, arguments: args }); + const call = async (name, args) => { + const result = await callRaw(name, args); + expect(result.isError, result.content[0].text).toBeFalsy(); + return JSON.parse(result.content[0].text); + }; + + const context = await browser.newContext({ permissions: ['local-network-access', 'clipboard-read', 'clipboard-write'] }); + stops.push(() => context.close()); + const page = await context.newPage(); + await watchCSP(page); + await page.goto(linkTo(samOne)); + await joinFromDialog(page, samOne.joinToken); + await page.getByRole('button', { name: 'Config' }).click(); + await page.getByRole('button', { name: 'Connect a local agent' }).click(); + await expect(page.locator('#agent-status')).toHaveText('Waiting for your agent. Paste the prompt into it and follow the instructions.'); + await expect(page.locator('#agent-config')).toContainText('~/.local/share/agentmesh/webapp-relay/relay.mjs'); + // The prompt's install step, run as printed with this test's home folder: Node alone saves the relay. + const install = await page.locator('#agent-install').textContent(); + execFileSync('sh', ['-c', install], { env: { ...process.env, HOME: configHome }, stdio: 'pipe' }); + const cli = path.join(configHome, '.local', 'share', 'agentmesh', 'webapp-relay', 'relay.mjs'); + relay = await stack.startAgentRelay(origin, { agentName: 'Claude Code', configHome, cli }); + await page.locator('#copy-agent-prompt').click(); + const prompt = await page.evaluate(() => navigator.clipboard.readText()); + const token = /with the token ([0-9a-f]{32})\./.exec(prompt)?.[1]; + expect(token, prompt).toBeTruthy(); + expect(prompt).toContain(install); + + await expect.poll(tools, { timeout: 20_000, message: 'the relay lists the page tools' }).toEqual(expect.arrayContaining(['pair_agent', 'get_mesh_info'])); + expect((await callRaw('get_mesh_info', {})).content[0].text).toContain('not paired yet'); + expect((await callRaw('pair_agent', { token: '0'.repeat(32) })).content[0].text).toContain('token is wrong, expired or already used'); + expect((await callRaw('pair_agent', { token })).content[0].text).toContain('Paired with the Agent Mesh page as "Claude Code"'); + await expect(page.locator('#agent-paired li')).toHaveCount(1); + await expect(page.locator('#agent-paired li')).toContainText('Claude Code, paired'); + await expect(page.locator('#agent-setup')).toBeHidden(); + const keyFile = path.join(configHome, 'agentmesh', 'webapp-relay', encodeURIComponent(new URL(origin).host), 'Claude%20Code.json'); + expect(fs.statSync(keyFile).mode & 0o777).toBe(0o600); + expect((await callRaw('pair_agent', { token })).content[0].text).toContain('No pairing is open'); + + // The page answers from its own mesh session: its peer ID and the router it holds. + const info = await call('get_mesh_info', {}); + expect(info.peer_id).toBe(await nodeId(page)); + expect(info.attached_routers).toHaveLength(1); + await expect(page.locator('#agent-status')).toContainText('Claude Code: last call get_mesh_info at'); + await expect(page.locator('#agent-status')).toContainText('1 call so far'); + await call('discover_remote_services', { type: 'a2a', name: 'agent' }); + await expect(page.locator('#agent-calls li').first()).toContainText('Claude Code: discover_remote_services a2a agent'); + await expect(page.locator('#agent-calls li').nth(1)).toContainText('Claude Code: get_mesh_info'); + await page.getByRole('button', { name: 'Dashboard' }).click(); + await expect(page.locator('#agent-line')).toContainText('Local agent Claude Code connected, last call discover_remote_services'); + await page.getByRole('button', { name: 'Config' }).click(); + + // A restarted agent stays paired, and the open page finds its relay again without a reload. + await relay.stop(); + relay = await stack.startAgentRelay(origin, { agentName: 'Claude Code', configHome, cli }); + await expect.poll(tools, { timeout: 15_000, message: 'the page reconnects to the restarted relay' }).toContain('get_mesh_info'); + expect((await call('get_mesh_info', {})).peer_id).toBe(await nodeId(page)); + // A reloaded page stays paired too. + await page.reload(); + await page.getByRole('button', { name: 'Config' }).click(); + await expect.poll(tools, { timeout: 20_000, message: 'the reloaded page offers its tools again' }).toContain('get_mesh_info'); + expect((await call('get_mesh_info', {})).peer_id).toBe(await nodeId(page)); + + // A program with the unpaired upstream relay reaches the page, but its calls are refused. + const plain = await stack.startAgentRelay(origin, { plain: true }); + stops.push(() => plain.stop()); + const plainTools = async () => (await plain.client.listTools()).tools.map((tool) => tool.name); + await expect.poll(plainTools, { timeout: 20_000, message: 'the plain relay lists the page tools' }).toContain('get_mesh_info'); + expect((await plain.client.callTool({ name: 'get_mesh_info', arguments: {} })).content[0].text).toContain('accepts calls only from a paired agent'); + + await page.getByRole('button', { name: 'Forget Claude Code' }).click(); + await expect(page.locator('#agent-paired')).toBeHidden(); + expect((await callRaw('get_mesh_info', {})).content[0].text).toContain('no longer paired'); + + await page.getByRole('button', { name: 'Disconnect local agent' }).click(); + await expect.poll(tools, { timeout: 10_000, message: 'disconnecting withdraws the tools' }).not.toContain('get_mesh_info'); + await expect(page.locator('#agent-line')).toBeHidden(); + await noViolations(page); + } finally { + for (const stop of stops.reverse()) { + await stop(); + } + } +}); + +test('Chromium can install the app without a service worker', async () => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + const samOne = await stack.startSamOne(); + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'agentmesh-app-profile-')); + // The headless shell has no install checks and reports none; full Chromium + // reports them, and only outside incognito, hence a persistent profile. + const context = await chromium.launchPersistentContext(profile, { channel: 'chromium' }); + try { + const page = context.pages()[0] ?? (await context.newPage()); + await page.goto(app.url); + await expect(page.locator('#view-welcome')).toBeVisible({ timeout: 30_000 }); + const cdp = await context.newCDPSession(page); + const { installabilityErrors } = await cdp.send('Page.getInstallabilityErrors'); + expect(installabilityErrors).toEqual([]); + } finally { + await context.close(); + fs.rmSync(profile, { recursive: true, force: true }); + await samOne.stop(); + } +}); + +test('a lapsed credential is refreshed at launch', async ({ context }) => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + // The router's own credential also lives 15 s; its default 5 min pass would present it expired. + const samOne = await stack.startSamOne({ args: ['--control-plane-biscuit-ttl', '15s', '--router-control-plane-sync-interval', '2s'] }); + try { + const page = await context.newPage(); + await watchCSP(page); + await page.goto(linkTo(samOne)); + await joinFromDialog(page, samOne.joinToken); + const peer = await nodeId(page); + const expires = await page.evaluate(() => window.agentmeshApp.state.stats.expires); + await page.close(); + + await expect.poll(() => Date.now() / 1000 > expires + 1, { timeout: 30_000 }).toBe(true); + const later = await context.newPage(); + await watchCSP(later); + await later.goto(app.url); + await expect(nodeTitle(later)).toHaveText('Node is Running', { timeout: 30_000 }); + expect(await nodeId(later)).toBe(peer); + expect(await later.evaluate(() => window.agentmeshApp.state.stats.expires)).toBeGreaterThan(expires); + await noViolations(later); + } finally { + await samOne.stop(); + } +}); + +test('a mesh that forgot this device takes a new code and keeps the Node ID', async ({ page }) => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + let samOne = await stack.startSamOne(); + try { + await watchCSP(page); + await page.goto(linkTo(samOne)); + await joinFromDialog(page, samOne.joinToken); + const peer = await nodeId(page); + + await samOne.stop(); + samOne = await stack.startSamOne({ port: samOne.port }); + await page.reload(); + await expect(page.locator('#status')).toContainText('The mesh no longer accepts this device', { timeout: 30_000 }); + await expect(page.locator('#welcome-title')).toHaveText('Rejoin the mesh'); + await expect(page.locator('#labels-field')).toBeHidden(); + // A banned key cannot rejoin, so the rejoin view keeps the way out. + await expect(page.locator('#rejoin-unenroll')).toBeVisible(); + + await pasteCode(page, samOne.joinToken); + await joinFromDialog(page, samOne.joinToken); + expect(await nodeId(page)).toBe(peer); + await noViolations(page); + } finally { + await samOne.stop(); + } +}); + +test('Sign in shows only when the provider answers the page with its own issuer, refuses a forged return, survives a silent provider, follows a provider change, and joins and rejoins with one Node ID', async ({ page, browser }) => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + const tls = stack.selfSignedCert('localhost'); + test.skip(tls === null, 'openssl is not installed'); + const stops = [() => fs.rmSync(tls.dir, { recursive: true, force: true })]; + // The control plane trusts the mock provider's certificate through SSL_CERT_FILE, the page through ignoreHTTPSErrors. + const startMesh = (issuer, port, ...extra) => + stack.startSamOne({ port, args: ['--issuer', issuer, ...extra], env: { SSL_CERT_FILE: tls.certFile } }); + // 15 s credentials, so the page renews one at once while the test watches; the router's own credential also lives 15 s. + const shortCredentials = ['--control-plane-biscuit-ttl', '15s', '--router-control-plane-sync-interval', '2s']; + const signInButton = (provider) => page.getByRole('button', { name: `Sign in with ${new URL(provider.issuer).host}` }); + try { + await watchCSP(page); + const plain = await stack.startSamOne(); + stops.push(() => plain.stop()); + await page.goto(app.url); + await expect(page.locator('#welcome-title')).toHaveText('Welcome to Agent Mesh'); + await expect(page.locator('#server-input')).toBeEditable(); + const asked = page.waitForResponse((res) => res.url() === `${plain.localUrl}/info`); + await enterServer(page, plain.localUrl); + await asked; + await expect(page.locator('#sign-in-block')).toBeHidden(); + + const closed = await startMockOIDC({ tls, cors: false }); + stops.push(() => closed.stop()); + const closedMesh = await startMesh(closed.issuer); + stops.push(() => closedMesh.stop()); + const gaveUp = page.waitForEvent('console', (msg) => msg.text().includes('Sign in is not offered')); + await enterServer(page, closedMesh.localUrl); + await gaveUp; + await expect(page.locator('#sign-in-block')).toBeHidden(); + await expect(page.locator('#offer-input')).toBeVisible(); + + const provider = await startMockOIDC({ tls }); + stops.push(() => provider.stop()); + let samOne = await startMesh(provider.issuer); + stops.push(() => samOne.stop()); + // Enrollment by sign-in needs the node role bound to the identity, as the testnets bind it. + const bindNodeRole = async () => { + const admin = { Authorization: `Bearer ${samOne.adminToken}` }; + const current = await fetch(`${samOne.localUrl}/admin/policy`, { headers: admin }); + expect(current.status, 'GET /admin/policy').toBe(200); + const policy = await current.json(); + policy.bindings = [...(policy.bindings ?? []), { role: 'mesh:role:node', members: ['mesh:system:authenticated'] }]; + const saved = await fetch(`${samOne.localUrl}/policies`, { method: 'POST', headers: { ...admin, 'Content-Type': 'application/json' }, body: JSON.stringify(policy) }); + expect(saved.status, await saved.text()).toBe(200); + }; + await bindNodeRole(); + // A page that names no mesh offers no Sign in; the mesh's address brings it. + await page.goto(app.url); + await expect(page.locator('#view-welcome')).toBeVisible(); + await expect(page.locator('#sign-in-block')).toBeHidden(); + await enterServer(page, samOne.localUrl); + await expect(signInButton(provider)).toBeVisible(); + // A link with only #server=… fills in the address, so the mesh's Sign in shows at once. + const meshPage = linkTo(samOne, null); + + // With discovery hanging, a token join still works, and any enrollment clears a sign-in error; the 10 s refusal step below pins that a hung lookup holds no join. + provider.hangDiscovery = true; + const other = await browser.newContext({ ignoreHTTPSErrors: true }); + stops.push(() => other.close()); + const fallback = await other.newPage(); + await fallback.goto(`${app.url}?code=forged&state=forged`); + await expect(fallback.locator('#sign-in-error')).toBeVisible(); + await fallback.evaluate((server) => { + location.hash = `server=${encodeURIComponent(server)}&token=mesh_not_a_token`; + }, samOne.localUrl); + await fallback.locator('#join-dialog').getByRole('button', { name: 'Join' }).click(); + await expect(fallback.locator('#status')).toContainText('Enrollment failed', { timeout: 10_000 }); + await expect(fallback.locator('#sign-in-error')).toBeHidden(); + await pasteCode(fallback, samOne.joinToken); + await joinFromDialog(fallback, samOne.joinToken); + await other.close(); + provider.hangDiscovery = false; + + // OIDC Discovery 1.0 section 4.3: a document for another issuer, or without a token endpoint, offers no Sign in. + for (const pageDiscovery of [{ issuer: 'https://elsewhere.example' }, { token_endpoint: undefined }]) { + provider.pageDiscovery = pageDiscovery; + const refused = page.waitForEvent('console', (msg) => msg.text().includes('Sign in is not offered')); + await page.goto(meshPage); + await refused; + await expect(page.locator('#sign-in-block')).toBeHidden(); + await expect(page.locator('#offer-input')).toBeVisible(); + } + provider.pageDiscovery = undefined; + + // Anyone can craft a return address, so the page shows its own words, never the provider's. + for (const forged of ['?error=access_denied&error_description=Call+this+number&state=forged', '?code=forged&state=forged']) { + await page.goto(app.url + forged); + await expect(page.locator('#sign-in-error')).toHaveText('This sign-in did not start in this tab. Press Sign in again.'); + expect(page.url(), 'the forged return stayed in the address bar').toBe(app.url); + await expect(page.locator('#welcome-title')).toHaveText('Welcome to Agent Mesh'); + } + + // A token endpoint that never answers costs the page 15 s, not the app: it shows why and offers Sign in again. + provider.hangToken = true; + await page.goto(meshPage); + await signInButton(provider).click(); + await expect(page.locator('#sign-in-error')).toHaveText('The sign-in provider did not answer this page. Press Sign in again, or join with a token.', { timeout: 30_000 }); + await expect(signInButton(provider)).toBeVisible(); + provider.hangToken = false; + + // Cancel during /register, which the SDK cannot abort: the credential is saved, so the address locks to this mesh. + let releaseRegister; + await page.route(`${samOne.localUrl}/register`, async (route) => { + await new Promise((resolve) => (releaseRegister = resolve)); + await route.continue(); + }); + await signInButton(provider).click(); + await expect.poll(() => releaseRegister !== undefined, { timeout: 30_000 }).toBe(true); + await page.locator('#cancel-enroll').click(); + await expect(page.locator('#status')).toContainText('Enrollment cancelled.'); + // A code for another mesh taken before the lock exists opens its dialog, and the join checks the lock again. + await pasteCode(page, 'mesh://enroll?server=https%3A%2F%2Fother.example.com&token=mesh_dev_x'); + await expect(page.locator('#join-dialog')).toBeVisible(); + // A provider that is slow to answer holds the view's Sign in lookup for 15 s, so within 5 s only the lock write shows Reset. + provider.hangDiscovery = true; + const registered = page.waitForResponse((res) => res.url() === `${samOne.localUrl}/register`); + releaseRegister(); + await registered; + await page.unroute(`${samOne.localUrl}/register`); + await expect(page.locator('#welcome-reset')).toBeVisible({ timeout: 5_000 }); + await expect(page.locator('#server-input')).not.toBeEditable(); + await page.locator('#join-dialog').getByRole('button', { name: 'Join' }).click(); + await expect(page.locator('#status-text')).toHaveText(`Enrollment failed: This device belongs to the mesh at ${new URL(samOne.localUrl).host}. Reset device identity to join another mesh.`, { timeout: 10_000 }); + await pasteCode(page, 'mesh://enroll?server=https%3A%2F%2Fother.example.com&token=mesh_dev_x'); + await expect(page.locator('#offer-error')).toHaveText(`This device belongs to the mesh at ${new URL(samOne.localUrl).host}. Reset device identity to join another mesh.`); + // A failed join enters the view again, and the provider, answering now, brings Sign in back. + provider.hangDiscovery = false; + await pasteCode(page, 'mesh_not_a_token'); + await page.locator('#join-dialog').getByRole('button', { name: 'Join' }).click(); + await expect(page.locator('#status')).toContainText('Enrollment failed', { timeout: 10_000 }); + + await signInButton(provider).click(); + await expect(nodeTitle(page)).toHaveText('Node is Running', { timeout: 30_000 }); + expect(page.url(), 'the code stayed in the address bar').toBe(app.url); + const peer = await nodeId(page); + + // The saved credential joins again: a reload needs no second sign-in. + await page.reload(); + await expect(nodeTitle(page)).toHaveText('Node is Running', { timeout: 30_000 }); + expect(await nodeId(page)).toBe(peer); + + await samOne.stop(); + samOne = await startMesh(provider.issuer, samOne.port); + await bindNodeRole(); + await page.reload(); + await expect(page.locator('#welcome-title')).toHaveText('Rejoin the mesh', { timeout: 30_000 }); + await expect(signInButton(provider)).toBeVisible(); + + // Without a reload, the page follows the operator: no provider, no Sign in; the provider back, Sign in back. + const failToken = async () => { + await pasteCode(page, 'mesh_not_a_token'); + await page.locator('#join-dialog').getByRole('button', { name: 'Join' }).click(); + await expect(page.locator('#status')).toContainText('Enrollment failed', { timeout: 10_000 }); + }; + await samOne.stop(); + samOne = await stack.startSamOne({ port: samOne.port }); + await failToken(); + await expect(page.locator('#sign-in-block')).toBeHidden(); + await samOne.stop(); + samOne = await startMesh(provider.issuer, samOne.port, ...shortCredentials); + await bindNodeRole(); + await failToken(); + await expect(signInButton(provider)).toBeVisible(); + // A provider that stops answering is dropped after 15 s, not offered for as long as the view stays open. + provider.hangDiscovery = true; + await failToken(); + await expect(page.locator('#sign-in-block')).toBeHidden({ timeout: 30_000 }); + provider.hangDiscovery = false; + await failToken(); + const issued = page.waitForResponse((res) => res.url() === `${provider.issuer}/token`); + await signInButton(provider).click(); + await expect(nodeTitle(page)).toHaveText('Node is Running', { timeout: 30_000 }); + expect(await nodeId(page)).toBe(peer); + const idToken = (await (await issued).json()).id_token; + + // The credential renews by proof of possession: the page keeps no ID token to send. + const refresh = await page.waitForRequest((req) => req.url() === `${samOne.localUrl}/refresh`, { timeout: 30_000 }); + expect(refresh.postDataBuffer().includes(Buffer.from(idToken)), 'the refresh carried the ID token').toBe(false); + expect((await refresh.response()).status()).toBe(200); + + // The control plane spends the old credential when it answers /refresh, so the page saves the new one before it asks + // for /keys. Held there, a reload still joins with the saved credential. + let refreshed = false; + page.on('response', (res) => { + if (res.url() === `${samOne.localUrl}/refresh` && res.status() === 200) refreshed = true; + }); + let hold; + const held = new Promise((resolve) => (hold = resolve)); + await page.route(`${samOne.localUrl}/keys`, (route) => { + // Only the first /keys after a refresh answer, and never released: the reload drops it. + if (!refreshed || hold === undefined) return route.continue(); + hold(); + hold = undefined; + }); + await held; + await page.reload(); + await expect(nodeTitle(page)).toHaveText('Node is Running', { timeout: 30_000 }); + expect(await nodeId(page)).toBe(peer); + await noViolations(page); + } finally { + for (const stop of stops.reverse()) { + await stop(); + } + } +}); + +test('a banned browser keeps a way to reset its identity, whatever it tries first', async ({ page }) => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + const samOne = await stack.startSamOne(); + try { + await watchCSP(page); + await page.goto(linkTo(samOne)); + await joinFromDialog(page, samOne.joinToken); + const peer = await nodeId(page); + execFileSync(path.join(__dirname, '..', '..', 'bin', 'agentmesh-one'), ['admin', 'ban', peer, '--server', samOne.localUrl, '--data-dir', samOne.dataDir], { stdio: 'pipe' }); + + await page.reload(); + await expect(page.locator('#welcome-title')).toHaveText('Rejoin the mesh', { timeout: 30_000 }); + await expect(page.locator('#rejoin-unenroll')).toBeVisible(); + // The token the page asks for cannot help a banned key, and the reset stays in reach. + await pasteCode(page, samOne.joinToken); + await page.locator('#join-dialog').getByRole('button', { name: 'Join' }).click(); + await expect(page.locator('#status')).toContainText('Enrollment failed', { timeout: 30_000 }); + await expect(page.locator('#welcome-reset')).toBeVisible(); + await page.reload(); + await expect(page.locator('#welcome-reset')).toBeVisible({ timeout: 30_000 }); + + await page.locator('#welcome-reset').click(); + await expect(page.locator('#status')).toContainText('Device identity reset.'); + await expect(page.locator('#welcome-reset')).toBeHidden(); + await pasteCode(page, samOne.joinToken); + await joinFromDialog(page, samOne.joinToken); + expect(await nodeId(page)).not.toBe(peer); + await noViolations(page); + } finally { + await samOne.stop(); + } +}); + +test('Unenroll keeps the Node ID, Reset device identity replaces it', async ({ page }) => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + const samOne = await stack.startSamOne(); + try { + await watchCSP(page); + await page.goto(linkTo(samOne)); + await joinFromDialog(page, samOne.joinToken); + const peer = await nodeId(page); + + await page.getByRole('button', { name: 'Unenroll / Clear Identity' }).click(); + await page.locator('#unenroll-dialog').getByRole('button', { name: 'Unenroll', exact: true }).click(); + await expect(page.locator('#view-welcome')).toBeVisible(); + await expect(page.locator('#status')).toContainText('Node ID is kept'); + // The kept key stays with its mesh: the address is fixed, and a code for another mesh is refused. + await expect(page.locator('#server-input')).toHaveValue(samOne.localUrl); + await expect(page.locator('#server-input')).not.toBeEditable(); + await pasteCode(page, 'mesh://enroll?server=https%3A%2F%2Fother.example.com&token=mesh_dev_x'); + await expect(page.locator('#offer-error')).toHaveText(`This device belongs to the mesh at ${new URL(samOne.localUrl).host}. Reset device identity to join another mesh.`); + await pasteCode(page, linkTo(samOne)); + await joinFromDialog(page, samOne.joinToken); + expect(await nodeId(page)).toBe(peer); + + await page.getByRole('button', { name: 'Unenroll / Clear Identity' }).click(); + await page.locator('#unenroll-dialog').getByRole('button', { name: 'Reset device identity' }).click(); + await expect(page.locator('#view-welcome')).toBeVisible(); + await page.reload(); + await expect(page.locator('#view-welcome')).toBeVisible({ timeout: 30_000 }); + await expect(page.locator('#nav'), 'a device that has not enrolled has only the welcome view').toBeHidden(); + // A new identity may join any mesh, so the address is open again. + await expect(page.locator('#server-input')).toBeEditable(); + await expect(page.locator('#server-input')).toHaveValue(''); + await enterServer(page, samOne.localUrl); + await page.locator('#labels').fill('region=eu'); + await pasteCode(page, samOne.joinToken); + await joinFromDialog(page, samOne.joinToken); + const fresh = await nodeId(page); + expect(fresh).toMatch(/^12D3Koo/); + expect(fresh).not.toBe(peer); + await page.getByRole('button', { name: 'Config' }).click(); + await expect(page.locator('#labels-line')).toHaveText(/^Labels: region=eu\./); + await noViolations(page); + } finally { + await samOne.stop(); + } +}); + +test('a second window yields the identity', async ({ context }) => { + const why = stack.missing({ app: true }); + test.skip(why !== '', why); + const samOne = await stack.startSamOne(); + try { + const first = await context.newPage(); + await first.goto(linkTo(samOne)); + await joinFromDialog(first, samOne.joinToken); + const peer = await nodeId(first); + + const second = await context.newPage(); + await second.goto(app.url); + await expect(second.locator('#blocked-message')).toHaveText('Agent Mesh is open in another tab or window.'); + await second.getByRole('button', { name: 'Use here' }).click(); + await expect(nodeTitle(second)).toHaveText('Node is Running', { timeout: 30_000 }); + expect(await nodeId(second)).toBe(peer); + await expect(first.locator('#blocked-message')).toHaveText('Agent Mesh is open in another tab or window.'); + } finally { + await samOne.stop(); + } +}); + +test('a binary without the SDK bundle says so and spends no token', async ({ page }) => { + const why = stack.missing(); + test.skip(why.startsWith('bin/'), why); + const samOne = await stack.startSamOne(); + try { + const enrollments = []; + page.on('request', (req) => { + if (new URL(req.url()).pathname.startsWith('/enroll')) enrollments.push(req.url()); + }); + await page.route('**/sdk/index.js', (route) => route.fulfill({ status: 404 })); + await page.goto(linkTo(samOne)); + await expect(page.locator('#blocked-message')).toHaveText(/built without the app.*make all/); + await expect(page.locator('#join-dialog')).toBeHidden(); + expect(enrollments).toEqual([]); + } finally { + await samOne.stop(); + } +}); diff --git a/tests/ui/lib/agentmesh-one.js b/tests/ui/lib/agentmesh-one.js index 6f76c118b..2e652dcb6 100644 --- a/tests/ui/lib/agentmesh-one.js +++ b/tests/ui/lib/agentmesh-one.js @@ -12,11 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -// The pieces the browser SDK test stands up around Chromium: agentmesh-one from -// bin/, a TLS-terminating edge in front of it that routes by name the way +// The pieces the browser tests stand up around Chromium: agentmesh-one from +// bin/, agentmesh-webapp from bin/ on an origin of its own, a TLS-terminating edge in front of it that routes by name the way // `agentmesh-one --tunnel` puts one there, a static server for the page, and the -// Node example programs from sdk/js as the other members, and agentmesh-router -// from bin/ as a second router that a page reaches over WebTransport. +// Node example programs from sdk/js as the other members, agentmesh-router +// from bin/ as a second router that a page reaches over WebTransport, and the +// WebMCP local relay that gives a page's tools to an agent. const { spawn, spawnSync } = require('node:child_process'); const dgram = require('node:dgram'); @@ -33,13 +34,20 @@ const SDK_JS = path.join(REPO_ROOT, 'sdk', 'js'); const PAGE_DIR = path.join(SDK_JS, 'build', 'browser-example'); /** Why the test cannot run here, or '' when everything is in place. */ -function missing() { +function missing({ app = false } = {}) { if (!fs.existsSync(path.join(REPO_ROOT, 'bin', 'agentmesh-one'))) { return 'bin/agentmesh-one is not built (make build)'; } if (!fs.existsSync(path.join(REPO_ROOT, 'bin', 'agentmesh-router'))) { return 'bin/agentmesh-router is not built (make build)'; } + if (!fs.existsSync(path.join(REPO_ROOT, 'bin', 'agentmesh-webapp'))) { + return 'bin/agentmesh-webapp is not built (make build)'; + } + if (app) { + const built = ['index.js', 'agentmesh-relay.mjs'].every((name) => fs.existsSync(path.join(REPO_ROOT, 'internal', 'webapp', 'public', 'sdk', name))); + return built ? '' : 'the app bundle is not built (make app)'; + } if (!fs.existsSync(path.join(PAGE_DIR, 'index.html')) || !fs.existsSync(path.join(SDK_JS, 'build', 'examples', 'a2a-call.js'))) { return 'the sdk/js browser example is not built (tests/ui/run.sh builds it)'; } @@ -57,6 +65,15 @@ function freePort() { }); } +// The page under test connects to the first relay that answers from 9333 up, so a real relay there would capture it. +function assertRelayPortFree() { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.once('error', () => reject(new Error('port 9333 is in use, perhaps by a WebMCP relay; stop it before this test'))); + srv.listen(9333, '127.0.0.1', () => srv.close(resolve)); + }); +} + function freeUDPPort() { return new Promise((resolve, reject) => { const sock = dgram.createSocket('udp4'); @@ -83,15 +100,32 @@ async function waitFor(url, what, tries = 100) { throw new Error(`timed out waiting for ${what} at ${url}`); } -/** Runs bin/agentmesh-one on a free loopback port; externalUrl is what it advertises. */ -async function startSamOne({ externalUrl } = {}) { +/** Runs bin/agentmesh-webapp on a free loopback port: a page origin apart from every mesh it joins. */ +async function startWebapp() { const port = await freePort(); + const proc = spawn(path.join(REPO_ROOT, 'bin', 'agentmesh-webapp'), ['--bind-addr', `127.0.0.1:${port}`], { stdio: ['ignore', 'pipe', 'pipe'] }); + let output = ''; + proc.stdout.on('data', (d) => (output += d)); + proc.stderr.on('data', (d) => (output += d)); + const url = `http://127.0.0.1:${port}/`; + try { + await waitFor(url, 'agentmesh-webapp'); + } catch (err) { + proc.kill(); + throw new Error(`${err.message}\n${output}`); + } + return { url, stop: () => proc.kill() }; +} + +/** Runs bin/agentmesh-one on port, or a free loopback port; externalUrl is what it advertises, and args and env go to it as given. */ +async function startSamOne({ externalUrl, port, args: extra = [], env = {} } = {}) { + port ??= await freePort(); const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agentmesh-one-ui-')); - const args = ['--bind-address', '127.0.0.1', '--port', String(port), '--data-dir', dataDir, '--log-level', 'warn']; + const args = ['--bind-address', '127.0.0.1', '--port', String(port), '--data-dir', dataDir, '--log-level', 'warn', ...extra]; if (externalUrl) { args.push('--external-url', externalUrl); } - const proc = spawn(path.join(REPO_ROOT, 'bin', 'agentmesh-one'), args, { stdio: ['ignore', 'pipe', 'pipe'] }); + const proc = spawn(path.join(REPO_ROOT, 'bin', 'agentmesh-one'), args, { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } }); let output = ''; proc.stdout.on('data', (d) => (output += d)); proc.stderr.on('data', (d) => (output += d)); @@ -103,16 +137,23 @@ async function startSamOne({ externalUrl } = {}) { throw new Error(`${err.message}\n${output}`); } return { + port, localUrl, dataDir, publicUrl: externalUrl ?? localUrl, joinToken: fs.readFileSync(path.join(dataDir, 'join-token'), 'utf8').trim(), + // agentmesh-one persists a token in the data dir only when AGENTMESH_ADMIN_TOKEN is unset or blank; tests/ui/run.sh sets it. + get adminToken() { + return (env.AGENTMESH_ADMIN_TOKEN ?? process.env.AGENTMESH_ADMIN_TOKEN ?? '').trim() || fs.readFileSync(path.join(dataDir, 'admin-token'), 'utf8').trim(); + }, get output() { return output; }, stop() { + const exited = proc.exitCode !== null || proc.signalCode !== null ? Promise.resolve() : new Promise((resolve) => proc.once('exit', resolve)); proc.kill(); fs.rmSync(dataDir, { recursive: true, force: true }); + return exited; }, }; } @@ -285,6 +326,29 @@ function startExampleAgent(name, env, ready = /accepting a2a:\/\/agent as (\S+)/ }); } +/** + * Starts a relay for pages of origin, connected to an MCP client as an agent would be: the paired relay + * the app serves, run from cli as agentName with its keys under configHome, or with plain the unpaired upstream relay. + */ +async function startAgentRelay(origin, { agentName = 'UI Test Agent', configHome, plain = false, cli = path.join(REPO_ROOT, 'internal', 'webapp', 'public', 'sdk', 'agentmesh-relay.mjs') } = {}) { + const sdkRequire = require('node:module').createRequire(path.join(SDK_JS, 'package.json')); + const { Client } = sdkRequire('@modelcontextprotocol/sdk/client/index.js'); + const { StdioClientTransport } = sdkRequire('@modelcontextprotocol/sdk/client/stdio.js'); + const client = new Client({ name: 'ui-test-agent', version: '1' }); + const transport = plain + ? new StdioClientTransport({ command: path.join(SDK_JS, 'node_modules', '.bin', 'webmcp-local-relay'), args: ['--widget-origin', origin], stderr: 'pipe' }) + : new StdioClientTransport({ + command: process.execPath, + args: [cli, '--widget-origin', origin, '--agent-name', agentName], + env: { ...process.env, XDG_CONFIG_HOME: configHome }, + stderr: 'pipe', + }); + let log = ''; + transport.stderr?.on('data', (d) => (log += d)); + await client.connect(transport); + return { client, stop: () => client.close(), get output() { return log; } }; +} + /** The environment the Node examples take to join agentmesh-one at publicUrl. */ function exampleEnv({ publicUrl, joinToken, caFile }, stateName) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), `sam-${stateName}-`)); @@ -297,4 +361,4 @@ function exampleEnv({ publicUrl, joinToken, caFile }, stateName) { }; } -module.exports = { PAGE_DIR, missing, freePort, startSamOne, startWebTransportRouter, selfSignedCert, startTLSEdge, serveStatic, runExample, startExampleAgent, exampleEnv }; +module.exports = { PAGE_DIR, missing, freePort, assertRelayPortFree, startSamOne, startWebapp, startWebTransportRouter, selfSignedCert, startTLSEdge, serveStatic, runExample, startExampleAgent, startAgentRelay, exampleEnv }; diff --git a/tests/ui/lib/mock-oidc.js b/tests/ui/lib/mock-oidc.js new file mode 100644 index 000000000..78d29365b --- /dev/null +++ b/tests/ui/lib/mock-oidc.js @@ -0,0 +1,92 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +const crypto = require('node:crypto'); +const https = require('node:https'); + +const b64url = (data) => Buffer.from(data).toString('base64url'); + +/** + * An OIDC provider on https://localhost, under tls from selfSignedCert, for + * one user: its sign-in page approves at once, and its token endpoint trades a + * code only for the PKCE verifier the sign-in started with. It allows any + * origin, as a provider configured for the page does, unless cors is false. + * A test misbehaves it through the returned handle: pageDiscovery replaces + * fields of the discovery document a browser (a request with an Origin) gets, + * hangDiscovery makes the browser's discovery request never answer, and + * hangToken makes the token endpoint never answer. + */ +async function startMockOIDC({ tls, cors = true, subject = 'alice', email = 'alice@example.com' }) { + const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }); + const kid = 'ui-test'; + const codes = new Map(); + let issuer; + const idToken = (clientId) => { + const now = Math.floor(Date.now() / 1000); + const head = b64url(JSON.stringify({ alg: 'RS256', typ: 'JWT', kid })); + const body = b64url(JSON.stringify({ iss: issuer, sub: subject, aud: clientId, email, email_verified: true, iat: now, exp: now + 600 })); + return `${head}.${body}.${b64url(crypto.sign('sha256', Buffer.from(`${head}.${body}`), privateKey))}`; + }; + const handle = { issuer: '', pageDiscovery: undefined, hangDiscovery: false, hangToken: false }; + const server = https.createServer({ cert: tls.cert, key: tls.key }, async (req, res) => { + if (cors) res.setHeader('Access-Control-Allow-Origin', '*'); + const url = new URL(req.url, issuer); + const json = (status, value) => { + res.writeHead(status, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(value)); + }; + if (url.pathname === '/.well-known/openid-configuration') { + if (handle.hangDiscovery && req.headers.origin) return; + const discovery = { issuer, authorization_endpoint: `${issuer}/auth`, token_endpoint: `${issuer}/token`, jwks_uri: `${issuer}/keys`, id_token_signing_alg_values_supported: ['RS256'] }; + return json(200, req.headers.origin ? { ...discovery, ...handle.pageDiscovery } : discovery); + } + if (url.pathname === '/keys') { + return json(200, { keys: [{ ...publicKey.export({ format: 'jwk' }), kid, alg: 'RS256', use: 'sig' }] }); + } + if (url.pathname === '/auth') { + const code = b64url(crypto.randomBytes(16)); + codes.set(code, { challenge: url.searchParams.get('code_challenge'), clientId: url.searchParams.get('client_id'), redirectUri: url.searchParams.get('redirect_uri') }); + const back = new URL(url.searchParams.get('redirect_uri')); + back.searchParams.set('code', code); + back.searchParams.set('state', url.searchParams.get('state')); + res.writeHead(302, { Location: back.href }); + return res.end(); + } + if (url.pathname === '/token' && req.method === 'POST') { + if (handle.hangToken) return; + let text = ''; + for await (const chunk of req) text += chunk; + const form = new URLSearchParams(text); + const pending = codes.get(form.get('code')); + codes.delete(form.get('code')); + const verifier = form.get('code_verifier') ?? ''; + if (pending === undefined || pending.redirectUri !== form.get('redirect_uri') || pending.challenge !== b64url(crypto.createHash('sha256').update(verifier).digest())) { + return json(400, { error: 'invalid_grant' }); + } + return json(200, { access_token: 'unused', token_type: 'Bearer', expires_in: 600, id_token: idToken(pending.clientId) }); + } + res.writeHead(404); + res.end(); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + issuer = handle.issuer = `https://localhost:${server.address().port}`; + handle.stop = () => { + const closed = new Promise((resolve) => server.close(resolve)); + server.closeAllConnections(); + return closed; + }; + return handle; +} + +module.exports = { startMockOIDC };