Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86bc401545 | ||
|
|
a4fd6b1557 | ||
|
|
a5a8a79a17 | ||
|
|
9a9b1cacfe | ||
|
|
054dbd8ae8 | ||
|
|
7461549cd6 | ||
|
|
69310a0445 | ||
|
|
54375ec428 | ||
|
|
6edd326615 | ||
|
|
763e6b8eb0 | ||
|
|
bee346de71 | ||
|
|
c258e74b95 |
@@ -1,5 +1,12 @@
|
||||
name: Publish
|
||||
|
||||
# Store-publish (Chrome Web Store, Firefox AMO, VS Code, Open VSX, JetBrains) and
|
||||
# every store credential have moved to the native pipeline on Hanzo Git:
|
||||
# .gitea/workflows/publish.yml — reads creds from KMS (deploy/kms/…), NOT GitHub.
|
||||
# GitHub retains only: build + the downloadable GitHub Release (mirror
|
||||
# distribution), and the live npm publish (interim — migrates to native once the
|
||||
# KMS NPM_TOKEN is seeded and the native run is verified green).
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
@@ -17,25 +24,16 @@ permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
# ─── Check available secrets ───
|
||||
# ─── npm publish gate (the one store credential still on GitHub) ───
|
||||
secrets:
|
||||
name: Load KMS Secrets
|
||||
name: Check npm token
|
||||
runs-on: hanzo-build-linux-amd64
|
||||
outputs:
|
||||
has-chrome: ${{ steps.check.outputs.has-chrome }}
|
||||
has-firefox: ${{ steps.check.outputs.has-firefox }}
|
||||
has-vsce: ${{ steps.check.outputs.has-vsce }}
|
||||
has-npm: ${{ steps.check.outputs.has-npm }}
|
||||
has-jetbrains: ${{ steps.check.outputs.has-jetbrains }}
|
||||
steps:
|
||||
- name: Check available secrets
|
||||
- name: Check npm token
|
||||
id: check
|
||||
run: |
|
||||
echo "has-chrome=${{ secrets.CHROME_EXTENSION_ID != '' }}" >> $GITHUB_OUTPUT
|
||||
echo "has-firefox=${{ secrets.AMO_API_KEY != '' }}" >> $GITHUB_OUTPUT
|
||||
echo "has-vsce=${{ secrets.VSCE_PAT != '' }}" >> $GITHUB_OUTPUT
|
||||
echo "has-npm=${{ secrets.NPM_TOKEN != '' }}" >> $GITHUB_OUTPUT
|
||||
echo "has-jetbrains=${{ secrets.JETBRAINS_TOKEN != '' }}" >> $GITHUB_OUTPUT
|
||||
run: echo "has-npm=${{ secrets.NPM_TOKEN != '' }}" >> $GITHUB_OUTPUT
|
||||
|
||||
# ─── Chrome + Firefox ───
|
||||
browser:
|
||||
@@ -84,40 +82,6 @@ jobs:
|
||||
run: npx web-ext lint --source-dir dist/browser-extension/firefox
|
||||
continue-on-error: true
|
||||
|
||||
- name: Publish to Chrome Web Store
|
||||
if: needs.secrets.outputs.has-chrome == 'true'
|
||||
working-directory: packages/browser
|
||||
run: |
|
||||
ACCESS_TOKEN=$(curl -s -X POST "https://oauth2.googleapis.com/token" \
|
||||
-d "client_id=${{ secrets.CHROME_CLIENT_ID }}" \
|
||||
-d "client_secret=${{ secrets.CHROME_CLIENT_SECRET }}" \
|
||||
-d "refresh_token=${{ secrets.CHROME_REFRESH_TOKEN }}" \
|
||||
-d "grant_type=refresh_token" | jq -r '.access_token')
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
curl -sf -X PUT \
|
||||
"https://www.googleapis.com/upload/chromewebstore/v1.1/items/${{ secrets.CHROME_EXTENSION_ID }}" \
|
||||
-H "Authorization: Bearer $ACCESS_TOKEN" \
|
||||
-H "x-goog-api-version: 2" \
|
||||
-T dist/hanzo-ai-chrome-v${VERSION}.zip
|
||||
curl -sf -X POST \
|
||||
"https://www.googleapis.com/chromewebstore/v1.1/items/${{ secrets.CHROME_EXTENSION_ID }}/publish" \
|
||||
-H "Authorization: Bearer $ACCESS_TOKEN" \
|
||||
-H "x-goog-api-version: 2" \
|
||||
-H "Content-Length: 0"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Publish to Firefox Add-ons
|
||||
if: needs.secrets.outputs.has-firefox == 'true'
|
||||
working-directory: packages/browser
|
||||
run: |
|
||||
npx web-ext sign \
|
||||
--source-dir dist/browser-extension/firefox \
|
||||
--api-key "${{ secrets.AMO_API_KEY }}" \
|
||||
--api-secret "${{ secrets.AMO_API_SECRET }}" \
|
||||
--channel listed \
|
||||
--id "hanzo-ai@hanzo.ai"
|
||||
continue-on-error: true
|
||||
|
||||
# ─── Safari (macOS + iOS) ───
|
||||
safari:
|
||||
name: Safari (macOS + iOS)
|
||||
@@ -228,18 +192,6 @@ jobs:
|
||||
name: hanzo-ai-ide
|
||||
path: packages/vscode/release-assets/*
|
||||
|
||||
- name: Publish to VS Code Marketplace
|
||||
if: needs.secrets.outputs.has-vsce == 'true'
|
||||
working-directory: packages/vscode
|
||||
run: vsce publish -p ${{ secrets.VSCE_PAT }}
|
||||
continue-on-error: true
|
||||
|
||||
- name: Publish to Open VSX
|
||||
if: needs.secrets.outputs.has-vsce == 'true'
|
||||
working-directory: packages/vscode
|
||||
run: ovsx publish *.vsix -p ${{ secrets.OVSX_PAT }}
|
||||
continue-on-error: true
|
||||
|
||||
# ─── npm (all @hanzo/* workspace packages) ───
|
||||
npm:
|
||||
name: npm
|
||||
@@ -318,14 +270,6 @@ jobs:
|
||||
name: hanzo-ai-jetbrains
|
||||
path: /tmp/hanzo-ai-jetbrains-v*.zip
|
||||
|
||||
- name: Publish to JetBrains Marketplace
|
||||
if: needs.secrets.outputs.has-jetbrains == 'true'
|
||||
working-directory: packages/jetbrains
|
||||
run: ./gradlew publishPlugin
|
||||
env:
|
||||
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_TOKEN }}
|
||||
continue-on-error: true
|
||||
|
||||
# ─── Microsoft Office add-in (Word / Excel / PowerPoint) ───
|
||||
office:
|
||||
name: Office Add-in
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Mirror GitHub → Hanzo Git (git.hanzo.ai) — the ONLY thing GitHub does as a
|
||||
# system of record. Hanzo Git is the source forge; its act_runners fire the
|
||||
# native pipeline (.gitea/workflows/*). GitHub is a public mirror.
|
||||
#
|
||||
# Credential: HANZO_GIT_TOKEN — a low-privilege Hanzo-Git push token, the ONE
|
||||
# secret GitHub still holds. It is NOT a store/publish credential (those live in
|
||||
# KMS only). Absent the token this no-ops with a warning, so it never blocks a
|
||||
# push before the operator seeds it. Alternatively the operator enables Gitea's
|
||||
# native pull-mirror server-side and this workflow becomes unnecessary.
|
||||
name: sync
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
runs-on: hanzo-build-linux-amd64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Push to git.hanzo.ai
|
||||
env:
|
||||
HANZO_GIT_TOKEN: ${{ secrets.HANZO_GIT_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$HANZO_GIT_TOKEN" ]; then
|
||||
echo "::warning::HANZO_GIT_TOKEN unset — mirror skipped. Seed it (or enable Gitea pull-mirror) to activate the native forge."
|
||||
exit 0
|
||||
fi
|
||||
git push --prune "https://x-access-token:${HANZO_GIT_TOKEN}@git.hanzo.ai/hanzoai/extension.git" \
|
||||
"+refs/remotes/origin/main:refs/heads/main" "+refs/tags/*:refs/tags/*"
|
||||
@@ -0,0 +1,49 @@
|
||||
# Native CI — Hanzo Git act_runners (label hanzo-build-linux-amd64).
|
||||
# amd64 test + build gate; mirrors the amd64 lanes of .github/workflows/ci.yml.
|
||||
# The macOS (Safari) and cross-platform Playwright matrix stay on GitHub-hosted
|
||||
# runners until native macOS/Windows act_runners are green
|
||||
# (runners-act-migration.md Phase 2). act_runner reads this unmodified;
|
||||
# GitHub.com ignores .hanzo/workflows, so the GitHub release lanes are untouched.
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, dev]
|
||||
tags: ['v*']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: hanzo-build-linux-amd64
|
||||
container: node:22-bookworm
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: corepack enable
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
# Shared workspace lib first — consumers import its built dist/.
|
||||
- run: pnpm --filter @hanzo/cards build
|
||||
- run: pnpm --filter @hanzo/browser-extension test
|
||||
- run: pnpm --filter @hanzo/aci test
|
||||
- run: pnpm --filter @hanzo/auth test
|
||||
|
||||
build:
|
||||
runs-on: hanzo-build-linux-amd64
|
||||
container: node:22-bookworm
|
||||
needs: [test]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: corepack enable
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build browser extension
|
||||
working-directory: packages/browser
|
||||
run: node src/build.js
|
||||
|
||||
- name: Check bundle budgets
|
||||
working-directory: packages/browser
|
||||
run: |
|
||||
[ -f dist/browser-extension/background.js ] || node src/build.js
|
||||
pnpm run check:bundle-budget
|
||||
continue-on-error: true
|
||||
@@ -0,0 +1,102 @@
|
||||
# Native store-publish — Hanzo Git act_runner (label hanzo-build-linux-amd64).
|
||||
# This is the SYSTEM OF RECORD for publishing the browser extension to the
|
||||
# Chrome Web Store + Firefox AMO, and for the npm package. GitHub only mirrors.
|
||||
#
|
||||
# Secrets model — KMS ONLY. The single bootstrap credential is the KMS machine
|
||||
# identity (KMS_CLIENT_ID / KMS_CLIENT_SECRET, a git.hanzo.ai Actions secret).
|
||||
# Every store credential is pulled from KMS at publish time
|
||||
# (org `hanzo`, env `prod`, path `/extension-publish` — see
|
||||
# deploy/kms/extension-publish-kms-sync.yaml). No CWS/AMO/npm secret is ever
|
||||
# stored in GitHub or Gitea Actions secrets.
|
||||
#
|
||||
# amd64/Linux only. Safari (macOS) + Windows desktop stay on GitHub-hosted
|
||||
# runners until native macOS/Windows act_runners are green
|
||||
# (runners-act-migration.md Phase 2).
|
||||
name: publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: hanzo-build-linux-amd64
|
||||
container: node:22-bookworm
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Tools (jq, pnpm)
|
||||
run: |
|
||||
apt-get update && apt-get install -y --no-install-recommends jq curl
|
||||
corepack enable
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
# ── The ONE secret hop: KMS machine identity → store creds ──
|
||||
# Login once, read each key from hanzo:/extension-publish, mask + export.
|
||||
# A missing key exports empty; each publish step below gates on its creds,
|
||||
# so partial provisioning publishes exactly what KMS has.
|
||||
- name: Load publish secrets from KMS
|
||||
env:
|
||||
KMS_CLIENT_ID: ${{ secrets.KMS_CLIENT_ID }}
|
||||
KMS_CLIENT_SECRET: ${{ secrets.KMS_CLIENT_SECRET }}
|
||||
run: |
|
||||
if [ -z "$KMS_CLIENT_ID" ] || [ -z "$KMS_CLIENT_SECRET" ]; then
|
||||
echo "::warning::KMS machine identity absent — cannot pull publish creds. Seed KMS_CLIENT_ID/SECRET as git.hanzo.ai Actions secrets."
|
||||
exit 0
|
||||
fi
|
||||
KMS=https://kms.hanzo.ai; ORG=hanzo; ENVN=prod; P=extension-publish
|
||||
TOKEN=$(curl -sf "$KMS/v1/kms/auth/login" -H 'Content-Type: application/json' \
|
||||
-d "{\"clientId\":\"$KMS_CLIENT_ID\",\"clientSecret\":\"$KMS_CLIENT_SECRET\"}" | jq -r .accessToken)
|
||||
[ -n "$TOKEN" ] && [ "$TOKEN" != null ] || { echo "::error::KMS login failed"; exit 1; }
|
||||
for KEY in CHROME_EXTENSION_ID CHROME_CLIENT_ID CHROME_CLIENT_SECRET CHROME_REFRESH_TOKEN AMO_API_KEY AMO_API_SECRET NPM_TOKEN; do
|
||||
VAL=$(curl -sf "$KMS/v1/kms/orgs/$ORG/secrets/$P/$KEY?env=$ENVN" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq -r '.secret.value // empty')
|
||||
if [ -n "$VAL" ]; then echo "::add-mask::$VAL"; fi
|
||||
echo "$KEY=$VAL" >> "$GITHUB_ENV"
|
||||
done
|
||||
|
||||
- name: Build browser extension
|
||||
working-directory: packages/browser
|
||||
run: node src/build.js
|
||||
|
||||
- name: Package (web-ext — no zip binary on the runner)
|
||||
working-directory: packages/browser
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
npx web-ext build --source-dir dist/browser-extension/chrome --artifacts-dir dist --filename hanzo-ai-chrome-v${VERSION}.zip --overwrite-dest
|
||||
npx web-ext build --source-dir dist/browser-extension/firefox --artifacts-dir dist --filename hanzo-ai-firefox-v${VERSION}.zip --overwrite-dest
|
||||
|
||||
- name: Publish to Chrome Web Store
|
||||
if: env.CHROME_EXTENSION_ID != ''
|
||||
working-directory: packages/browser
|
||||
run: |
|
||||
ACCESS_TOKEN=$(curl -s -X POST "https://oauth2.googleapis.com/token" \
|
||||
-d "client_id=$CHROME_CLIENT_ID" -d "client_secret=$CHROME_CLIENT_SECRET" \
|
||||
-d "refresh_token=$CHROME_REFRESH_TOKEN" -d "grant_type=refresh_token" | jq -r '.access_token')
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
curl -sf -X PUT "https://www.googleapis.com/upload/chromewebstore/v1.1/items/$CHROME_EXTENSION_ID" \
|
||||
-H "Authorization: Bearer $ACCESS_TOKEN" -H "x-goog-api-version: 2" \
|
||||
-T dist/hanzo-ai-chrome-v${VERSION}.zip
|
||||
curl -sf -X POST "https://www.googleapis.com/chromewebstore/v1.1/items/$CHROME_EXTENSION_ID/publish" \
|
||||
-H "Authorization: Bearer $ACCESS_TOKEN" -H "x-goog-api-version: 2" -H "Content-Length: 0"
|
||||
|
||||
- name: Publish to Firefox Add-ons
|
||||
if: env.AMO_API_KEY != ''
|
||||
working-directory: packages/browser
|
||||
run: |
|
||||
npx web-ext sign --source-dir dist/browser-extension/firefox \
|
||||
--api-key "$AMO_API_KEY" --api-secret "$AMO_API_SECRET" \
|
||||
--channel listed --id "hanzo-ai@hanzo.ai"
|
||||
|
||||
# npm — canonical home is here. The .github npm job stays live until this
|
||||
# runs green (KMS NPM_TOKEN seeded), then it is deleted. pnpm publish skips
|
||||
# versions already on npm, so any transition overlap is idempotent.
|
||||
- name: Publish @hanzo/* to npm
|
||||
if: env.NPM_TOKEN != ''
|
||||
run: |
|
||||
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" >> .npmrc
|
||||
echo "@hanzo:registry=https://registry.npmjs.org/" >> .npmrc
|
||||
pnpm --filter @hanzo/cards build
|
||||
pnpm -r --if-present run build || true
|
||||
pnpm -r publish --access public --no-git-checks --ignore-scripts --report-summary || true
|
||||
@@ -30,6 +30,19 @@ per-browser manifests come from `zapd install-host` (`zap-proto/zapd`).
|
||||
Patch only (X.Y.Z+1), never major. `package.json` is the source of truth; `build.js`
|
||||
stamps it into every manifest (chrome/firefox/safari).
|
||||
|
||||
## CI/CD (native — Hanzo Git, KMS, act_runner)
|
||||
Git of record is `git.hanzo.ai/hanzoai/extension`; GitHub is a mirror.
|
||||
- `.gitea/workflows/*` — native pipeline on `hanzo-build-linux-amd64` act_runners:
|
||||
`ci.yml` (amd64 test + build), `publish.yml` (Chrome Web Store + Firefox AMO + npm).
|
||||
- Secrets are **KMS only**. The pipeline logs in with the KMS machine identity
|
||||
(`KMS_CLIENT_ID`/`KMS_CLIENT_SECRET`) and pulls store creds from `hanzo:/extension-publish`
|
||||
(env `prod`). CR: `deploy/kms/extension-publish-kms-sync.yaml`. No store cred in
|
||||
any Actions secret store.
|
||||
- `.github/workflows/` mirrors + degrades gracefully: `sync.yml` pushes main+tags to
|
||||
Hanzo Git; `ci.yml`/`cross-platform-e2e.yml` keep the macOS(Safari)/Windows/matrix
|
||||
lanes that still need GitHub-hosted runners; `publish.yml` keeps only the GitHub
|
||||
Release + the interim npm publish (store-publish removed → native). See PUBLISHING.md.
|
||||
|
||||
## Cross-platform — WXT migration (canonical plan, not yet executed)
|
||||
|
||||
One WebExtension codebase, every engine. **WXT** = build/SDK layer (build matrix,
|
||||
|
||||
+32
-17
@@ -1,33 +1,48 @@
|
||||
# Publishing Hanzo Extensions
|
||||
|
||||
This document describes how to publish Hanzo extensions to various marketplaces.
|
||||
Publishing is NATIVE: it runs on Hanzo Git (`git.hanzo.ai`) act_runners, and
|
||||
every store credential lives in Hanzo KMS. GitHub only mirrors the repo.
|
||||
|
||||
## Required Secrets
|
||||
## Topology (one way)
|
||||
|
||||
Add these secrets to your GitHub repository settings:
|
||||
- **Git of record:** `git.hanzo.ai/hanzoai/extension`. GitHub is a public
|
||||
mirror; `.github/workflows/sync.yml` pushes `main` + tags to Hanzo Git.
|
||||
- **CI/CD:** `.gitea/workflows/*` on `hanzo-build-linux-amd64` act_runners —
|
||||
`ci.yml` (test + build) and `publish.yml` (Chrome Web Store + Firefox AMO + npm).
|
||||
- **Secrets — KMS ONLY.** The native pipeline logs in with the KMS machine
|
||||
identity (`KMS_CLIENT_ID` / `KMS_CLIENT_SECRET`) and pulls store creds from
|
||||
org `hanzo`, env `prod`, path `/extension-publish`
|
||||
(see `deploy/kms/extension-publish-kms-sync.yaml`). No store credential is
|
||||
ever a GitHub or Gitea Actions secret.
|
||||
- **amd64/Linux publishes natively.** Safari (macOS) + desktop (Windows) stay on
|
||||
GitHub-hosted runners until native macOS/Windows act_runners are green
|
||||
(`universe/docs/architecture/runners-act-migration.md`).
|
||||
|
||||
| Secret | Description | How to Get |
|
||||
|--------|-------------|------------|
|
||||
| `VSCE_PAT` | VS Code Marketplace token | [Create PAT](https://code.visualstudio.com/api/working-with-extensions/publishing-extension#get-a-personal-access-token) |
|
||||
| `OVSX_PAT` | Open VSX Registry token | [Create token](https://open-vsx.org/user-settings/tokens) |
|
||||
| `NPM_TOKEN` | npm publish token | `npm token create` or [npm.js tokens](https://www.npmjs.com/settings/~/tokens) |
|
||||
| `JETBRAINS_TOKEN` | JetBrains Marketplace token | [Generate token](https://plugins.jetbrains.com/author/me/tokens) |
|
||||
| `CERTIFICATE_CHAIN` | JetBrains plugin signing cert | [Plugin signing](https://plugins.jetbrains.com/docs/intellij/plugin-signing.html) |
|
||||
| `PRIVATE_KEY` | JetBrains plugin signing key | See above |
|
||||
| `PRIVATE_KEY_PASSWORD` | JetBrains key password | See above |
|
||||
## KMS keys the operator seeds (path `hanzo:/extension-publish`, env `prod`)
|
||||
|
||||
| Key(s) | Store |
|
||||
|--------|-------|
|
||||
| `CHROME_EXTENSION_ID`, `CHROME_CLIENT_ID`, `CHROME_CLIENT_SECRET`, `CHROME_REFRESH_TOKEN` | Chrome Web Store |
|
||||
| `AMO_API_KEY`, `AMO_API_SECRET` | Firefox Add-ons |
|
||||
| `NPM_TOKEN` | npm (`@hanzo/*`) |
|
||||
|
||||
## Publishing Methods
|
||||
|
||||
### Automatic (GitHub Actions)
|
||||
### Automatic (native)
|
||||
|
||||
1. Create a GitHub release with a version tag (e.g., `v1.6.0`)
|
||||
2. The `publish.yml` workflow will automatically publish to all marketplaces
|
||||
Push a `vX.Y.Z` tag. GitHub mirrors it to Hanzo Git, which fires
|
||||
`.gitea/workflows/publish.yml`. Or run `workflow_dispatch` on Hanzo Git.
|
||||
|
||||
Or manually trigger:
|
||||
```bash
|
||||
gh workflow run publish.yml
|
||||
# version lives in packages/browser/package.json (patch only, never major)
|
||||
git tag v1.9.35 && git push origin v1.9.35
|
||||
```
|
||||
|
||||
> Interim: the live npm publish still also runs from `.github/workflows/publish.yml`
|
||||
> until the KMS `NPM_TOKEN` is seeded and one native `publish.yml` run is verified
|
||||
> green; then the GitHub npm job is deleted. `pnpm publish` skips versions already
|
||||
> on npm, so the overlap is idempotent.
|
||||
|
||||
### Manual Publishing
|
||||
|
||||
#### VS Code Marketplace
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# Store-publish credentials for the Hanzo browser extension — KMS is the ONLY home.
|
||||
#
|
||||
# The native publish pipeline (.gitea/workflows/publish.yml, act_runner on
|
||||
# git.hanzo.ai) reads these at publish time. No store credential lives in a
|
||||
# GitHub or Gitea Actions secret — the ONLY bootstrap credential is the KMS
|
||||
# machine identity (KMS_CLIENT_ID / KMS_CLIENT_SECRET), already provisioned.
|
||||
#
|
||||
# ── Operator steps (the VALUES are the store-account owner's; not in git) ──
|
||||
# 1. KMS (kms.hanzo.ai) → org `hanzo`, env `prod`, project path `/extension-publish`.
|
||||
# Add the keys below. These are the Chrome Web Store + Firefox AMO
|
||||
# credentials — the store-account owner drops the real values here:
|
||||
# CHROME_EXTENSION_ID Chrome Web Store item id
|
||||
# CHROME_CLIENT_ID Google OAuth client id (CWS API)
|
||||
# CHROME_CLIENT_SECRET Google OAuth client secret
|
||||
# CHROME_REFRESH_TOKEN Google OAuth refresh token
|
||||
# AMO_API_KEY addons.mozilla.org JWT issuer
|
||||
# AMO_API_SECRET addons.mozilla.org JWT secret
|
||||
# Optional (same path, if these stores are moved off GitHub too):
|
||||
# VSCE_PAT OVSX_PAT JETBRAINS_TOKEN NPM_TOKEN
|
||||
# kms secret set --project hanzo --env prod --path /extension-publish \
|
||||
# CHROME_EXTENSION_ID "<value>" # …repeat per key
|
||||
# 2. Grant the extension repo's KMS machine identity (the KMS_CLIENT_ID it
|
||||
# already uses) READ on project `hanzo`, path `/extension-publish`.
|
||||
# 3. Re-provision KMS_CLIENT_ID / KMS_CLIENT_SECRET as git.hanzo.ai Actions
|
||||
# secrets so the native runner can log in (they exist on GitHub today —
|
||||
# runners-act-migration.md Phase 1.2).
|
||||
#
|
||||
# Canonical GitOps home is universe/infra/k8s/kms-canonical-crs/hanzo/ (generated
|
||||
# by scripts/kms-canonical-v1alpha1-gen.py). This in-repo copy is the extension's
|
||||
# declared secret contract — reflect it into universe, do not diverge.
|
||||
---
|
||||
apiVersion: secrets.lux.network/v1alpha1
|
||||
kind: KMSSecret
|
||||
metadata:
|
||||
name: extension-publish-kms-sync
|
||||
namespace: hanzo
|
||||
labels:
|
||||
app.kubernetes.io/name: extension
|
||||
app.kubernetes.io/component: kms-secret
|
||||
app.kubernetes.io/part-of: hanzo-universe
|
||||
kms.hanzo.ai/org: hanzo
|
||||
kms.hanzo.ai/env: prod
|
||||
spec:
|
||||
hostAPI: http://kms.hanzo.svc
|
||||
resyncInterval: 60
|
||||
authentication:
|
||||
universalAuth:
|
||||
# Shared platform machine identity (same as the other hanzo CRs). The
|
||||
# operator scopes it to read /extension-publish.
|
||||
credentialsRef:
|
||||
secretName: hanzo-platform-iam-creds
|
||||
secretNamespace: hanzo
|
||||
secretsScope:
|
||||
projectSlug: hanzo
|
||||
envSlug: prod
|
||||
secretsPath: /extension-publish
|
||||
keys:
|
||||
- CHROME_EXTENSION_ID
|
||||
- CHROME_CLIENT_ID
|
||||
- CHROME_CLIENT_SECRET
|
||||
- CHROME_REFRESH_TOKEN
|
||||
- AMO_API_KEY
|
||||
- AMO_API_SECRET
|
||||
managedSecretReference:
|
||||
secretName: extension-publish-secrets
|
||||
secretNamespace: hanzo
|
||||
secretType: Opaque
|
||||
creationPolicy: Orphan
|
||||
+4
-4
@@ -53,9 +53,9 @@ The Hanzo agent automatically detects and uses available LLM providers in this o
|
||||
- Access to all models with credits
|
||||
- Managed API keys in Hanzo Cloud
|
||||
|
||||
## Complete Model Catalog (OpenRouter + LiteLLM Compatible)
|
||||
## Complete Model Catalog
|
||||
|
||||
Hanzo AI provides access to every model available through OpenRouter and LiteLLM, including:
|
||||
Hanzo AI provides access to every major model through one API, including:
|
||||
|
||||
- **OpenAI**: O3-Pro, O3, GPT-4o, GPT-4 Turbo, GPT-4, GPT-3.5 Turbo
|
||||
- **Anthropic**: Claude 4, Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Sonnet, Claude 3 Haiku
|
||||
@@ -159,7 +159,7 @@ export OLLAMA_BASE_URL=http://localhost:11434
|
||||
## Why AI Engineers Choose Hanzo AI
|
||||
|
||||
### 🎯 **The Complete Toolkit**
|
||||
- **Every Model**: OpenRouter + LiteLLM = access to every AI model
|
||||
- **Every Model**: one API across every major provider and our own Zen family
|
||||
- **Every Tool**: 4000+ MCP servers for specialized capabilities
|
||||
- **Every Provider**: OpenAI, Anthropic, Google, Meta, Mistral, and 50+ more
|
||||
|
||||
@@ -300,6 +300,6 @@ Error: Model xyz not available through Hanzo AI
|
||||
- **Dashboard**: [iam.hanzo.ai](https://iam.hanzo.ai)
|
||||
- **Support**: support@hanzo.ai
|
||||
|
||||
**Hanzo AI is the unified platform for building AI-powered companies.** Access 200+ LLMs (OpenRouter/LiteLLM compatible), 4000+ MCP servers, legendary programmer modes, unlimited memory with vector/graph/relational search, browser automation, and everything you need to supercharge AI development.
|
||||
**Hanzo AI is the unified platform for building AI-powered companies.** Access 200+ models through one API, 4000+ MCP servers, legendary programmer modes, unlimited memory with vector/graph/relational search, browser automation, and everything you need to supercharge AI development.
|
||||
|
||||
🚀 **[Get Started](https://iam.hanzo.ai)** | 📖 **[View Modes & Features](./HANZO_MODES.md)** | 💬 **[Join Discord](https://discord.gg/hanzoai)**
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hanzo/extension",
|
||||
"version": "1.9.32",
|
||||
"version": "1.9.36",
|
||||
"private": true,
|
||||
"description": "Hanzo AI Extension",
|
||||
"license": "MIT",
|
||||
|
||||
Executable
+95
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env bash
|
||||
# Permanent local-dev install of the Hanzo browser extension on Linux — NO snap,
|
||||
# NO web store, NO signing service. Builds from source and installs into:
|
||||
#
|
||||
# • Firefox ESR (/opt/firefox-esr) via an enterprise policy that
|
||||
# force-installs the unsigned XPI into EVERY profile (signatures disabled).
|
||||
# Truly permanent + launch-independent: any launch of that Firefox has it.
|
||||
#
|
||||
# • Brave (Chromium-family; arm64 has no Google-Chrome build) via a
|
||||
# --load-extension launcher (/usr/local/bin/hanzo-brave + a desktop entry).
|
||||
# The extension loads from the live dist dir, so a rebuild + relaunch picks
|
||||
# up new code — the correct dev loop (no re-pack per change).
|
||||
#
|
||||
# Why these two: on this box (aarch64) apt ships ONLY snap redirects for
|
||||
# firefox/chromium, and Google Chrome has no Linux arm64 build. Firefox ESR and
|
||||
# Brave are the reliable non-snap arm64 browsers. On x86_64 the same script
|
||||
# works; swap Brave for google-chrome if preferred.
|
||||
#
|
||||
# Re-run after any `node src/build.js` to redeploy. Idempotent.
|
||||
set -euo pipefail
|
||||
|
||||
REPO_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
EXT_ROOT="$(cd "$REPO_DIR/../.." && pwd)" # ~/work/hanzo/extension
|
||||
DIST="$EXT_ROOT/dist"
|
||||
STABLE=/opt/hanzo-ext # stable install location
|
||||
FF=/opt/firefox-esr
|
||||
|
||||
echo "==> building extension from source"
|
||||
( cd "$REPO_DIR" && node src/build.js )
|
||||
[ -d "$DIST/firefox" ] && [ -d "$DIST/chrome" ] || { echo "build did not produce dist/{firefox,chrome}"; exit 1; }
|
||||
|
||||
echo "==> packaging Firefox XPI"
|
||||
XPI=/tmp/hanzo-ai.xpi
|
||||
( cd "$DIST/firefox" && rm -f "$XPI" && zip -qr -X "$XPI" . )
|
||||
GECKO_ID=$(python3 -c 'import json;m=json.load(open("'"$DIST"'/firefox/manifest.json"));print((m.get("browser_specific_settings") or m.get("applications") or {}).get("gecko",{}).get("id",""))')
|
||||
[ -n "$GECKO_ID" ] || { echo "firefox manifest has no gecko id"; exit 1; }
|
||||
|
||||
echo "==> staging stable copies under $STABLE (needs sudo)"
|
||||
sudo mkdir -p "$STABLE"
|
||||
sudo cp "$XPI" "$STABLE/hanzo-ai.xpi"
|
||||
sudo rm -rf "$STABLE/chrome" && sudo cp -r "$DIST/chrome" "$STABLE/chrome"
|
||||
|
||||
if [ -x "$FF/firefox" ]; then
|
||||
echo "==> Firefox ESR enterprise policy (force-install + signatures off)"
|
||||
sudo mkdir -p "$FF/distribution"
|
||||
sudo tee "$FF/distribution/policies.json" >/dev/null <<JSON
|
||||
{
|
||||
"policies": {
|
||||
"ExtensionSettings": {
|
||||
"$GECKO_ID": { "installation_mode": "force_installed", "install_url": "file://$STABLE/hanzo-ai.xpi" }
|
||||
},
|
||||
"Preferences": { "xpinstall.signatures.required": { "Value": false, "Status": "locked" } },
|
||||
"DisableAppUpdate": true
|
||||
}
|
||||
}
|
||||
JSON
|
||||
else
|
||||
echo "!! Firefox ESR not at $FF — install it (Mozilla arm64 ESR tarball) then re-run"
|
||||
fi
|
||||
|
||||
if command -v brave-browser >/dev/null 2>&1; then
|
||||
echo "==> Brave --load-extension launcher + desktop entry"
|
||||
sudo tee /usr/local/bin/hanzo-brave >/dev/null <<'SH'
|
||||
#!/bin/bash
|
||||
exec /usr/bin/brave-browser --load-extension=/opt/hanzo-ext/chrome "$@"
|
||||
SH
|
||||
sudo chmod +x /usr/local/bin/hanzo-brave
|
||||
sudo tee /usr/share/applications/brave-hanzo-dev.desktop >/dev/null <<'DESK'
|
||||
[Desktop Entry]
|
||||
Version=1.0
|
||||
Name=Brave (Hanzo Dev)
|
||||
Comment=Brave with the local Hanzo browser extension
|
||||
Exec=/usr/local/bin/hanzo-brave %U
|
||||
Terminal=false
|
||||
Type=Application
|
||||
Icon=brave-browser
|
||||
Categories=Network;WebBrowser;
|
||||
DESK
|
||||
else
|
||||
echo "!! brave-browser not found — install it, then re-run"
|
||||
fi
|
||||
|
||||
CHROME_ID=$(python3 - <<PY
|
||||
import json,base64,hashlib
|
||||
m=json.load(open("$DIST/chrome/manifest.json")); k=m.get("key")
|
||||
if k:
|
||||
h=hashlib.sha256(base64.b64decode(k)).hexdigest()[:32]
|
||||
print(''.join(chr(ord('a')+int(c,16)) for c in h))
|
||||
PY
|
||||
)
|
||||
echo
|
||||
echo "DONE."
|
||||
echo " Firefox: launch $FF/firefox (extension $GECKO_ID force-installed, every profile)"
|
||||
echo " Brave: launch hanzo-brave (extension ${CHROME_ID:-<key-derived>} via --load-extension)"
|
||||
echo " Rebuild loop: node src/build.js && ./install-linux.sh (then relaunch the browser)"
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hanzo/browser-extension",
|
||||
"version": "1.9.33",
|
||||
"version": "1.9.36",
|
||||
"description": "Hanzo AI Browser Extension",
|
||||
"main": "dist/background.js",
|
||||
"scripts": {
|
||||
@@ -13,6 +13,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@hanzo/ai": "^0.2.3",
|
||||
"@hanzo/usage": "^0.1.6",
|
||||
"@supabase/supabase-js": "^2.50.3",
|
||||
"axios": "^1.10.0",
|
||||
"chalk": "^4.1.2",
|
||||
|
||||
@@ -3,6 +3,7 @@ import { createAiClient, type SearchEvent, type SearchMode, type SearchSource }
|
||||
import { fetchNews, type NewsItem } from './news.js';
|
||||
import { AUTO_MODEL, fetchModelCatalog, type ChatModel, type ModelGroup } from './model-catalog.js';
|
||||
import { renderMarkdown } from './markdown.js';
|
||||
import { capture, contributeTrainingSample } from '../shared/consent.js';
|
||||
|
||||
/**
|
||||
* Hanzo Answer Engine — the shared AI-answer surface (query → streamed answer +
|
||||
@@ -321,6 +322,8 @@ export function AnswerEngine({ apiBase, getToken, signIn, initialQuery }: Answer
|
||||
setFollowUps([]);
|
||||
setError('');
|
||||
setNeedAuth(false);
|
||||
void capture('answer_search', { mode, model: model.id });
|
||||
let fullAnswer = '';
|
||||
|
||||
const opts = {
|
||||
mode,
|
||||
@@ -346,6 +349,7 @@ export function AnswerEngine({ apiBase, getToken, signIn, initialQuery }: Answer
|
||||
setAnswerSources(ev.sources);
|
||||
break;
|
||||
case 'text':
|
||||
fullAnswer += ev.delta;
|
||||
setAnswer((a) => a + ev.delta);
|
||||
break;
|
||||
case 'follow_ups':
|
||||
@@ -353,6 +357,10 @@ export function AnswerEngine({ apiBase, getToken, signIn, initialQuery }: Answer
|
||||
break;
|
||||
case 'done':
|
||||
setPhase('done');
|
||||
void capture('answer_shown', { mode, model: model.id });
|
||||
// Opt-in only: no-ops unless the user turned on training
|
||||
// contribution (the consent module gates the send).
|
||||
void contributeTrainingSample({ query: question, answer: fullAnswer, model: model.id });
|
||||
break;
|
||||
case 'error':
|
||||
if (ev.error.includes('__NO_TOKEN__') || /401|invalid api key/i.test(ev.error)) {
|
||||
|
||||
@@ -110,7 +110,11 @@ class HanzoFirefoxExtension {
|
||||
|
||||
constructor() {
|
||||
console.log('[Hanzo] Firefox extension initializing...');
|
||||
this.connect();
|
||||
// Legacy ws://:9223 CDP bridge is OPT-IN (globalThis.HANZO_LEGACY_CDP). The
|
||||
// default (and only) transport is the ZAP native host — see
|
||||
// discoverZapServers() at EOF — matching Chrome. Without a bridge server the
|
||||
// WS just error-looped, so it no longer runs unless explicitly enabled.
|
||||
if ((globalThis as { HANZO_LEGACY_CDP?: boolean }).HANZO_LEGACY_CDP) this.connect();
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
|
||||
@@ -283,9 +283,18 @@ async function stopControlSession(): Promise<void> {
|
||||
void loadDebugFlagFromStorage();
|
||||
|
||||
// Initialize WebGPU, Ollama, and CDP on install
|
||||
chrome.runtime.onInstalled.addListener(async () => {
|
||||
chrome.runtime.onInstalled.addListener(async (details) => {
|
||||
debugLog('[Hanzo] Extension installed, initializing...');
|
||||
|
||||
// First install → open the consent onboarding once (insights + opt-in training).
|
||||
if (details?.reason === 'install') {
|
||||
try {
|
||||
await chrome.tabs.create({ url: chrome.runtime.getURL('onboarding.html') });
|
||||
} catch {
|
||||
/* non-fatal — settings still reachable from the popup */
|
||||
}
|
||||
}
|
||||
|
||||
// WebGPU init
|
||||
const gpuAvailable = await webgpuAI.initialize();
|
||||
if (gpuAvailable) {
|
||||
|
||||
@@ -5,8 +5,18 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
// ONE output root: the extension repo root's `dist/` (NOT packages/browser/dist),
|
||||
// so every build lands at a short, stable path — `<extension-root>/dist/chrome`
|
||||
// is the Load-unpacked / native-messaging target, regardless of where `node
|
||||
// src/build.js` (or `pnpm build`) is invoked from. Derived from __dirname
|
||||
// (packages/browser/src → ../../../) so it's cwd-independent. Per-browser bundles
|
||||
// sit directly under OUT; the shared staging bundles + npm files sit at OUT root.
|
||||
const OUT = path.resolve(__dirname, '..', '..', '..', 'dist');
|
||||
const out = (...p) => path.join(OUT, ...p);
|
||||
|
||||
async function build() {
|
||||
console.log('Building browser extension...');
|
||||
console.log('Output root:', OUT);
|
||||
|
||||
// The extension does NOT depend on `@hanzo/ui`. Primitives are served by
|
||||
// a small local shim aliased as `@hanzo/gui` so call-sites read like the
|
||||
@@ -17,12 +27,9 @@ async function build() {
|
||||
console.log('Using @hanzo/gui local primitives shim:', hanzoGuiShim);
|
||||
|
||||
// The Usage panel runs the headless @hanzo/usage engine in the background
|
||||
// context. The package lives in the sibling repo (hanzoai/usage); alias its
|
||||
// built ESM entry so esbuild bundles it into the background scripts. Same
|
||||
// pattern as the @hanzo/gui shim above — one specifier, one source of truth.
|
||||
const hanzoUsage = path.join(__dirname, '..', '..', '..', '..', 'usage', 'packages', 'core', 'dist', 'index.js');
|
||||
const backgroundAliases = { '@hanzo/usage': hanzoUsage };
|
||||
console.log('Using @hanzo/usage engine:', hanzoUsage);
|
||||
// context. It's a published npm dependency (^0.1.6) — esbuild resolves it
|
||||
// from node_modules like any package, so the build works identically locally
|
||||
// and on CI (no sibling-repo path assumption).
|
||||
|
||||
// The answer engine (new-tab landing) consumes the @hanzo/ai SDK's `search`
|
||||
// primitive — the ONE place the search/deep-research capability is defined.
|
||||
@@ -31,16 +38,15 @@ async function build() {
|
||||
// (no sibling-repo path assumption).
|
||||
|
||||
// Ensure dist directories exist
|
||||
fs.mkdirSync('dist/browser-extension', { recursive: true });
|
||||
fs.mkdirSync('dist/browser-extension/chrome', { recursive: true });
|
||||
fs.mkdirSync('dist/browser-extension/firefox', { recursive: true });
|
||||
fs.mkdirSync('dist/browser-extension/safari', { recursive: true });
|
||||
for (const d of ['', 'chrome', 'firefox', 'safari']) {
|
||||
fs.mkdirSync(out(d), { recursive: true });
|
||||
}
|
||||
|
||||
// Build content script
|
||||
await esbuild.build({
|
||||
entryPoints: ['src/content-script.ts'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/content-script.js',
|
||||
outfile: out('content-script.js'),
|
||||
platform: 'browser',
|
||||
target: ['chrome90', 'firefox91', 'safari14'],
|
||||
sourcemap: 'inline'
|
||||
@@ -50,31 +56,29 @@ async function build() {
|
||||
await esbuild.build({
|
||||
entryPoints: ['src/background.ts'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/background.js',
|
||||
outfile: out('background.js'),
|
||||
platform: 'browser',
|
||||
target: ['chrome90', 'safari14'],
|
||||
format: 'esm',
|
||||
external: ['chrome', 'browser'],
|
||||
alias: backgroundAliases
|
||||
});
|
||||
|
||||
// Build Firefox-specific background script (no ESM export, uses browser.* APIs)
|
||||
await esbuild.build({
|
||||
entryPoints: ['src/background-firefox.ts'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/background-firefox.js',
|
||||
outfile: out('background-firefox.js'),
|
||||
platform: 'browser',
|
||||
target: ['firefox91'],
|
||||
format: 'iife', // Immediately-invoked function expression (no exports)
|
||||
external: ['browser'],
|
||||
alias: backgroundAliases
|
||||
});
|
||||
|
||||
// Build WebGPU AI module
|
||||
await esbuild.build({
|
||||
entryPoints: ['src/webgpu-ai.ts'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/webgpu-ai.js',
|
||||
outfile: out('webgpu-ai.js'),
|
||||
platform: 'browser',
|
||||
target: 'es2020',
|
||||
format: 'esm'
|
||||
@@ -89,7 +93,7 @@ async function build() {
|
||||
await esbuild.build({
|
||||
entryPoints: [fs.existsSync('src/sidebar.ts') ? 'src/sidebar.ts' : 'src/sidebar.js'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/sidebar.js',
|
||||
outfile: out('sidebar.js'),
|
||||
platform: 'browser',
|
||||
target: ['chrome90', 'firefox91', 'safari14'],
|
||||
sourcemap: 'inline',
|
||||
@@ -99,7 +103,7 @@ async function build() {
|
||||
await esbuild.build({
|
||||
entryPoints: [fs.existsSync('src/popup.ts') ? 'src/popup.ts' : 'src/popup.js'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/popup.js',
|
||||
outfile: out('popup.js'),
|
||||
platform: 'browser',
|
||||
target: ['chrome90', 'firefox91', 'safari14'],
|
||||
sourcemap: 'inline',
|
||||
@@ -110,7 +114,7 @@ async function build() {
|
||||
await esbuild.build({
|
||||
entryPoints: ['src/newtab.ts'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/newtab.js',
|
||||
outfile: out('newtab.js'),
|
||||
platform: 'browser',
|
||||
target: ['chrome90', 'firefox91', 'safari14'],
|
||||
// New-tab page loads on every tab — ship it lean (minified, no inline map).
|
||||
@@ -118,11 +122,22 @@ async function build() {
|
||||
sourcemap: false,
|
||||
});
|
||||
|
||||
// Onboarding (new-install consent ask: insights + opt-in training).
|
||||
await esbuild.build({
|
||||
entryPoints: ['src/onboarding.ts'],
|
||||
bundle: true,
|
||||
outfile: out('onboarding.js'),
|
||||
platform: 'browser',
|
||||
target: ['chrome90', 'firefox91', 'safari14'],
|
||||
minify: true,
|
||||
sourcemap: false,
|
||||
});
|
||||
|
||||
// Build browser control module
|
||||
await esbuild.build({
|
||||
entryPoints: ['src/browser-control.ts'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/browser-control.js',
|
||||
outfile: out('browser-control.js'),
|
||||
platform: 'browser',
|
||||
target: 'es2020',
|
||||
format: 'esm'
|
||||
@@ -132,7 +147,7 @@ async function build() {
|
||||
await esbuild.build({
|
||||
entryPoints: ['src/cli.ts'],
|
||||
bundle: true,
|
||||
outfile: 'dist/browser-extension/cli.js',
|
||||
outfile: out('cli.js'),
|
||||
platform: 'node',
|
||||
target: 'node16',
|
||||
packages: 'external'
|
||||
@@ -140,16 +155,9 @@ async function build() {
|
||||
|
||||
// Make CLI executable
|
||||
if (process.platform !== 'win32') {
|
||||
execSync('chmod +x dist/browser-extension/cli.js');
|
||||
fs.chmodSync(out('cli.js'), 0o755);
|
||||
}
|
||||
|
||||
// Build TypeScript declarations
|
||||
console.log('Building TypeScript declarations...');
|
||||
// Check if we should run tsc in root or src, based on where tsconfig is.
|
||||
// Assuming root tsconfig covers src, or src has one.
|
||||
// There is a tsconfig in src.
|
||||
// execSync('cd src && npx tsc --noEmit', { stdio: 'inherit' });
|
||||
|
||||
// Copy manifests for different browsers. package.json is the SINGLE source of
|
||||
// truth for the version — stamp it into every manifest so the three can never
|
||||
// drift apart (the "must agree" rule, enforced by the build instead of by hand).
|
||||
@@ -159,12 +167,12 @@ async function build() {
|
||||
m.version = pkgVersion;
|
||||
fs.writeFileSync(destPath, JSON.stringify(m, null, 2));
|
||||
};
|
||||
writeManifest('src/manifest.json', 'dist/browser-extension/manifest.json');
|
||||
writeManifest('src/manifest.json', 'dist/browser-extension/chrome/manifest.json');
|
||||
writeManifest('src/manifest-firefox.json', 'dist/browser-extension/firefox/manifest.json');
|
||||
writeManifest('src/manifest.json', out('manifest.json'));
|
||||
writeManifest('src/manifest.json', out('chrome', 'manifest.json'));
|
||||
writeManifest('src/manifest-firefox.json', out('firefox', 'manifest.json'));
|
||||
|
||||
// Safari needs special handling — write Info.plist for Xcode project
|
||||
fs.writeFileSync('dist/browser-extension/safari/Info.plist', `<?xml version="1.0" encoding="UTF-8"?>
|
||||
fs.writeFileSync(out('safari', 'Info.plist'), `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
@@ -188,27 +196,18 @@ async function build() {
|
||||
|
||||
// Copy common files to each browser directory
|
||||
['chrome', 'firefox', 'safari'].forEach(browserName => {
|
||||
const dir = `dist/browser-extension/${browserName}`;
|
||||
const dir = out(browserName);
|
||||
|
||||
fs.copyFileSync(
|
||||
'dist/browser-extension/content-script.js',
|
||||
`${dir}/content-script.js`
|
||||
);
|
||||
fs.copyFileSync(out('content-script.js'), path.join(dir, 'content-script.js'));
|
||||
// Firefox uses IIFE background (no ESM service workers); Chrome/Safari use ESM
|
||||
if (browserName === 'firefox') {
|
||||
fs.copyFileSync(
|
||||
'dist/browser-extension/background-firefox.js',
|
||||
`${dir}/background.js`
|
||||
);
|
||||
fs.copyFileSync(out('background-firefox.js'), path.join(dir, 'background.js'));
|
||||
} else {
|
||||
fs.copyFileSync(
|
||||
'dist/browser-extension/background.js',
|
||||
`${dir}/background.js`
|
||||
);
|
||||
fs.copyFileSync(out('background.js'), path.join(dir, 'background.js'));
|
||||
}
|
||||
|
||||
// Copy popup + sidebar + answer-engine HTML/CSS
|
||||
for (const f of ['popup.html', 'popup.css', 'sidebar.html', 'sidebar.css', 'newtab.html', 'newtab.css', 'callback.html', 'ai-worker.js']) {
|
||||
for (const f of ['popup.html', 'popup.css', 'sidebar.html', 'sidebar.css', 'newtab.html', 'newtab.css', 'onboarding.html', 'onboarding.css', 'callback.html', 'ai-worker.js']) {
|
||||
const src = path.join('src', f);
|
||||
if (fs.existsSync(src)) {
|
||||
fs.copyFileSync(src, path.join(dir, f));
|
||||
@@ -216,9 +215,10 @@ async function build() {
|
||||
}
|
||||
|
||||
// Copy compiled popup/sidebar/newtab scripts
|
||||
fs.copyFileSync('dist/browser-extension/popup.js', path.join(dir, 'popup.js'));
|
||||
fs.copyFileSync('dist/browser-extension/sidebar.js', path.join(dir, 'sidebar.js'));
|
||||
fs.copyFileSync('dist/browser-extension/newtab.js', path.join(dir, 'newtab.js'));
|
||||
fs.copyFileSync(out('popup.js'), path.join(dir, 'popup.js'));
|
||||
fs.copyFileSync(out('sidebar.js'), path.join(dir, 'sidebar.js'));
|
||||
fs.copyFileSync(out('newtab.js'), path.join(dir, 'newtab.js'));
|
||||
fs.copyFileSync(out('onboarding.js'), path.join(dir, 'onboarding.js'));
|
||||
|
||||
// Copy icons into each browser directory
|
||||
for (const icon of ['icon16.png', 'icon48.png', 'icon128.png']) {
|
||||
@@ -232,13 +232,10 @@ async function build() {
|
||||
// Copy package.json for npm
|
||||
const pkg = JSON.parse(fs.readFileSync('src/package.json', 'utf8'));
|
||||
pkg.main = 'cli.js';
|
||||
fs.writeFileSync(
|
||||
'dist/browser-extension/package.json',
|
||||
JSON.stringify(pkg, null, 2)
|
||||
);
|
||||
fs.writeFileSync(out('package.json'), JSON.stringify(pkg, null, 2));
|
||||
|
||||
// Create README for npm package
|
||||
fs.writeFileSync('dist/browser-extension/README.md', `# Hanzo Browser DevTools
|
||||
fs.writeFileSync(out('README.md'), `# Hanzo Browser DevTools
|
||||
|
||||
Click-to-code navigation for web developers with MCP integration.
|
||||
|
||||
@@ -287,32 +284,33 @@ server.on('elementSelected', (data) => {
|
||||
['icon16.png', 'icon48.png', 'icon128.png'].forEach(icon => {
|
||||
const iconPath = path.join('images', icon);
|
||||
if (fs.existsSync(iconPath)) {
|
||||
fs.copyFileSync(iconPath, path.join('dist/browser-extension', icon));
|
||||
fs.copyFileSync(iconPath, out(icon));
|
||||
}
|
||||
});
|
||||
|
||||
// Generate Safari Xcode project (macOS + iOS) if safari-web-extension-converter exists
|
||||
// Generate Safari Xcode project (macOS + iOS) if safari-web-extension-converter exists.
|
||||
// Project goes to dist/safari-xcode/ so it never collides with the dist/safari/ web-ext dir.
|
||||
try {
|
||||
execSync('xcrun --find safari-web-extension-converter', { stdio: 'ignore' });
|
||||
console.log('Generating Safari Xcode project (macOS + iOS)...');
|
||||
execSync(
|
||||
`xcrun safari-web-extension-converter dist/browser-extension/chrome/ ` +
|
||||
`--project-location dist/safari ` +
|
||||
`xcrun safari-web-extension-converter ${out('chrome')}/ ` +
|
||||
`--project-location ${out('safari-xcode')} ` +
|
||||
`--app-name "Hanzo AI" ` +
|
||||
`--bundle-identifier ai.hanzo.browser-extension ` +
|
||||
`--no-prompt --no-open --force`,
|
||||
{ stdio: 'inherit' }
|
||||
);
|
||||
console.log('📦 Safari: dist/safari/ (macOS + iOS Xcode project)');
|
||||
console.log(`📦 Safari: ${out('safari-xcode')} (macOS + iOS Xcode project)`);
|
||||
} catch {
|
||||
console.log('⚠️ Safari: skipped (Xcode not available)');
|
||||
}
|
||||
|
||||
console.log('✅ Browser extension built successfully!');
|
||||
console.log('📦 Chrome: dist/browser-extension/chrome/');
|
||||
console.log('📦 Firefox: dist/browser-extension/firefox/');
|
||||
console.log('📦 NPM package ready in: dist/browser-extension/');
|
||||
console.log('\nTo publish to npm: cd dist/browser-extension && npm publish');
|
||||
console.log(`📦 Chrome: ${out('chrome')}/`);
|
||||
console.log(`📦 Firefox: ${out('firefox')}/`);
|
||||
console.log(`📦 NPM package ready in: ${OUT}/`);
|
||||
console.log(`\nTo publish to npm: cd ${OUT} && npm publish`);
|
||||
}
|
||||
|
||||
build().catch((error) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Hanzo AI",
|
||||
"version": "1.9.33",
|
||||
"version": "1.9.34",
|
||||
"description": "AI answer engine, search, and dev assistant — Hanzo AI in a new tab, address-bar search, source-cited answers, realtime news, WebGPU AI, and MCP.",
|
||||
"permissions": [
|
||||
"activeTab",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Hanzo AI",
|
||||
"version": "1.9.33",
|
||||
"version": "1.9.34",
|
||||
"description": "AI answer engine, search, and dev assistant — Hanzo AI in a new tab, address-bar search, source-cited answers, realtime news, WebGPU AI, and MCP.",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxfXGh0lPUT5m04GKfjUwrLsV6pLaK3VcZuFRPogqAir2tzyLYnQPRtHynue9yvDyguIVnlkwvcwfDOYZrvH76zbw4s6onPBG8HqTKO6LQ9K3kdO1qBBkMMjdOgULQ1MrWThEbpU7NSTiwLYpEta/jAvrKRCAeKIlQE8p6htZmPy9aRUZuae66JgLcAlzD2vviX9sVB1asFABJVswL1RgZ55/8IzZaUrFjzOo9OHK4hmEOtudzkML+5silsAYdC+1BZugph2x94ai17YmZTCL1XyUa5Ke4q80cj+i9rOTgzhZs+mruyhL/AvNVOXilsgqCdNqSz77naWzC3pVGbxOewIDAQAB",
|
||||
"permissions": [
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
:root {
|
||||
--bg: #0b0b0c;
|
||||
--card: #131315;
|
||||
--line: #26262a;
|
||||
--text: #f4f4f5;
|
||||
--muted: #9a9aa2;
|
||||
--accent: #f4f4f5;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
body { display: grid; place-items: center; padding: 32px; }
|
||||
.card {
|
||||
width: 100%;
|
||||
max-width: 520px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
padding: 32px;
|
||||
}
|
||||
.brand { font-weight: 700; letter-spacing: 0.02em; opacity: 0.7; margin-bottom: 20px; }
|
||||
h1 { font-size: 24px; margin: 0 0 8px; }
|
||||
.lede { color: var(--muted); margin: 0 0 24px; }
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 14px 0;
|
||||
border-top: 1px solid var(--line);
|
||||
cursor: pointer;
|
||||
}
|
||||
.row input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.switch {
|
||||
flex: 0 0 auto;
|
||||
width: 38px;
|
||||
height: 22px;
|
||||
border-radius: 999px;
|
||||
background: #3a3a40;
|
||||
position: relative;
|
||||
transition: background 0.15s;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.switch::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.row input:checked + .switch { background: var(--accent); }
|
||||
.row input:checked + .switch::after { transform: translateX(16px); background: #0b0b0c; }
|
||||
.text { display: flex; flex-direction: column; gap: 2px; }
|
||||
.text strong { font-weight: 600; }
|
||||
.text small { color: var(--muted); }
|
||||
.cta {
|
||||
width: 100%;
|
||||
margin-top: 24px;
|
||||
padding: 12px;
|
||||
border: 0;
|
||||
border-radius: 10px;
|
||||
background: var(--accent);
|
||||
color: #0b0b0c;
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.cta:active { transform: translateY(1px); }
|
||||
.fine { color: var(--muted); font-size: 12px; text-align: center; margin: 16px 0 0; }
|
||||
.fine a { color: var(--text); }
|
||||
@@ -0,0 +1,45 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Welcome to Hanzo</title>
|
||||
<link rel="stylesheet" href="onboarding.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<div class="brand">Hanzo</div>
|
||||
<h1>Welcome to Hanzo AI</h1>
|
||||
<p class="lede">
|
||||
Search, research and browse with Hanzo's own models. Before you start,
|
||||
choose what you'd like to share — you can change this anytime in settings
|
||||
or on your Hanzo account.
|
||||
</p>
|
||||
|
||||
<label class="row">
|
||||
<input type="checkbox" id="ob-insights" checked />
|
||||
<span class="switch"></span>
|
||||
<span class="text">
|
||||
<strong>Anonymous usage insights</strong>
|
||||
<small>Helps us improve Hanzo. No search text, no personal data — just a random per-install id.</small>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label class="row">
|
||||
<input type="checkbox" id="ob-training" />
|
||||
<span class="switch"></span>
|
||||
<span class="text">
|
||||
<strong>Contribute to training Hanzo's open models</strong>
|
||||
<small>Share your own searches & answers so Hanzo's open models get better. Opt in — off unless you turn it on.</small>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<button id="ob-continue" class="cta">Get started</button>
|
||||
<p class="fine">
|
||||
Signed in? These choices save to your Hanzo account and stay in sync
|
||||
everywhere. <a href="https://hanzo.ai/privacy" target="_blank" rel="noopener">Privacy</a>
|
||||
</p>
|
||||
</main>
|
||||
<script src="onboarding.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,29 @@
|
||||
// onboarding.ts — the new-install consent ask. Opened once by the background on
|
||||
// install. Records the user's choice as their consent (account-canonical when
|
||||
// signed in — setConsent write-throughs to /v1/iam/consent), marks onboarding
|
||||
// done so it never reopens, and closes.
|
||||
import 'webextension-polyfill';
|
||||
import { setConsent, markOnboarded, capture } from './shared/consent.js';
|
||||
|
||||
const runtime: typeof chrome = (globalThis as any).browser ?? (globalThis as any).chrome;
|
||||
|
||||
const insights = document.getElementById('ob-insights') as HTMLInputElement | null;
|
||||
const training = document.getElementById('ob-training') as HTMLInputElement | null;
|
||||
const cta = document.getElementById('ob-continue') as HTMLButtonElement | null;
|
||||
|
||||
cta?.addEventListener('click', async () => {
|
||||
const consent = {
|
||||
insights: insights?.checked ?? true,
|
||||
shareTraining: training?.checked ?? false,
|
||||
};
|
||||
await setConsent(consent);
|
||||
await markOnboarded();
|
||||
await capture('onboarding_complete', { shareTraining: consent.shareTraining });
|
||||
try {
|
||||
const tab = await runtime.tabs.getCurrent();
|
||||
if (tab?.id) await runtime.tabs.remove(tab.id);
|
||||
else window.close();
|
||||
} catch {
|
||||
window.close();
|
||||
}
|
||||
});
|
||||
@@ -222,6 +222,34 @@
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- Privacy & data -->
|
||||
<h3>Privacy & data</h3>
|
||||
<div class="features">
|
||||
<div class="feature-toggle">
|
||||
<label>
|
||||
<input type="checkbox" id="insights-enabled" checked>
|
||||
<span class="toggle"></span>
|
||||
<div class="feature-info">
|
||||
<strong>Usage insights</strong>
|
||||
<small>Anonymous, helps improve Hanzo. Never your search text.</small>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="feature-toggle">
|
||||
<label>
|
||||
<input type="checkbox" id="share-training">
|
||||
<span class="toggle"></span>
|
||||
<div class="feature-info">
|
||||
<strong>Contribute to training</strong>
|
||||
<small>Opt in to share your searches & answers to train Hanzo's open models. Off by default.</small>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- Browser Backend -->
|
||||
<div class="setting-group backend-picker">
|
||||
<h3>Backend</h3>
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
shortcutFromEvent,
|
||||
type Shortcut,
|
||||
} from './shared/shortcut.js';
|
||||
import { getConsent, setConsent, capture } from './shared/consent.js';
|
||||
|
||||
declare const browser: typeof chrome & {
|
||||
sidebarAction?: {
|
||||
@@ -229,6 +230,21 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
syncSettingsUi(enabled, side, width);
|
||||
});
|
||||
|
||||
// Privacy & data toggles — reflect stored consent, persist on change.
|
||||
const insightsCheckbox = document.getElementById('insights-enabled') as HTMLInputElement | null;
|
||||
const shareTrainingCheckbox = document.getElementById('share-training') as HTMLInputElement | null;
|
||||
getConsent().then((c) => {
|
||||
if (insightsCheckbox) insightsCheckbox.checked = c.insights;
|
||||
if (shareTrainingCheckbox) shareTrainingCheckbox.checked = c.shareTraining;
|
||||
});
|
||||
insightsCheckbox?.addEventListener('change', (e) => {
|
||||
void setConsent({ insights: (e.target as HTMLInputElement).checked });
|
||||
});
|
||||
shareTrainingCheckbox?.addEventListener('change', (e) => {
|
||||
void setConsent({ shareTraining: (e.target as HTMLInputElement).checked });
|
||||
});
|
||||
void capture('popup_opened');
|
||||
|
||||
function isInjectableTab(tab: chrome.tabs.Tab | undefined): boolean {
|
||||
if (!tab || !tab.id) return false;
|
||||
const url = tab.url || '';
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// consent.ts — ONE data-consent value, one source of truth.
|
||||
//
|
||||
// The user's data-sharing consent lives on their Hanzo ACCOUNT (asked at
|
||||
// hanzo.id signup, editable in the extension + on hanzo.ai). This module keeps
|
||||
// the extension in lockstep with that one value:
|
||||
// • Signed in → the account is canonical. getConsent() reads it from
|
||||
// GET /v1/iam/consent; setConsent() writes it with PUT /v1/iam/consent.
|
||||
// The local copy is just a cache so the UI paints instantly.
|
||||
// • Signed out → the local copy (from onboarding) is used, and is pushed to
|
||||
// the account on next sign-in so nothing is lost or duplicated.
|
||||
//
|
||||
// TWO switches:
|
||||
// • insights (default ON) — anonymous product events. No query/answer
|
||||
// text, no PII: only which surface fired, under a random per-install id.
|
||||
// • shareTraining (OPT-IN) — contribute the user's OWN searches + answers
|
||||
// to train Hanzo's open models. Asked explicitly at signup/onboarding.
|
||||
//
|
||||
// Everything is fail-soft: a network error NEVER breaks a user action, and
|
||||
// nothing is sent for a switch that is off.
|
||||
import { API_BASE_URL } from './config.js';
|
||||
|
||||
const KEYS = {
|
||||
insights: 'hanzo_insights_enabled',
|
||||
training: 'hanzo_share_training',
|
||||
onboarded: 'hanzo_onboarded',
|
||||
anonId: 'hanzo_anon_id',
|
||||
} as const;
|
||||
|
||||
export interface Consent {
|
||||
insights: boolean;
|
||||
shareTraining: boolean;
|
||||
}
|
||||
|
||||
const runtime: typeof chrome | undefined =
|
||||
(globalThis as any).browser ?? (globalThis as any).chrome;
|
||||
|
||||
function area(): chrome.storage.StorageArea | undefined {
|
||||
return (globalThis as any).chrome?.storage?.local ?? (globalThis as any).browser?.storage?.local;
|
||||
}
|
||||
|
||||
function getLocal(keys: string[]): Promise<Record<string, any>> {
|
||||
return new Promise((resolve) => {
|
||||
const s = area();
|
||||
if (!s) return resolve({});
|
||||
try {
|
||||
s.get(keys, (v) => resolve(v || {}));
|
||||
} catch {
|
||||
resolve({});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setLocal(obj: Record<string, any>): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const s = area();
|
||||
if (!s) return resolve();
|
||||
try {
|
||||
s.set(obj, () => resolve());
|
||||
} catch {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Bearer for the signed-in user, brokered by the background (null when out). */
|
||||
async function token(): Promise<string | null> {
|
||||
try {
|
||||
const resp: any = await runtime?.runtime?.sendMessage?.({ action: 'auth.getToken' });
|
||||
return resp?.token ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function localConsent(v: Record<string, any>): Consent {
|
||||
return { insights: v[KEYS.insights] !== false, shareTraining: v[KEYS.training] === true };
|
||||
}
|
||||
|
||||
/** Read consent: the account is canonical when signed in; local otherwise. */
|
||||
export async function getConsent(): Promise<Consent> {
|
||||
const local = localConsent(await getLocal([KEYS.insights, KEYS.training]));
|
||||
const tok = await token();
|
||||
if (!tok) return local;
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/v1/iam/consent`, {
|
||||
headers: { authorization: `Bearer ${tok}` },
|
||||
});
|
||||
if (res.ok) {
|
||||
const a = await res.json();
|
||||
const acct: Consent = { insights: a.insights !== false, shareTraining: a.shareTraining === true };
|
||||
// Cache so the UI paints instantly next time, keeping one value in sync.
|
||||
await setLocal({ [KEYS.insights]: acct.insights, [KEYS.training]: acct.shareTraining });
|
||||
return acct;
|
||||
}
|
||||
} catch {
|
||||
/* fall through to local */
|
||||
}
|
||||
return local;
|
||||
}
|
||||
|
||||
/** Write consent: local cache + the account (when signed in) — one value. */
|
||||
export async function setConsent(c: Partial<Consent>): Promise<void> {
|
||||
const cur = localConsent(await getLocal([KEYS.insights, KEYS.training]));
|
||||
const next: Consent = {
|
||||
insights: c.insights ?? cur.insights,
|
||||
shareTraining: c.shareTraining ?? cur.shareTraining,
|
||||
};
|
||||
await setLocal({ [KEYS.insights]: next.insights, [KEYS.training]: next.shareTraining });
|
||||
const tok = await token();
|
||||
if (!tok) return;
|
||||
try {
|
||||
await fetch(`${API_BASE_URL}/v1/iam/consent`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json', authorization: `Bearer ${tok}` },
|
||||
body: JSON.stringify(next),
|
||||
keepalive: true,
|
||||
}).catch(() => {});
|
||||
} catch {
|
||||
/* fail-soft */
|
||||
}
|
||||
}
|
||||
|
||||
export async function isOnboarded(): Promise<boolean> {
|
||||
const v = await getLocal([KEYS.onboarded]);
|
||||
return v[KEYS.onboarded] === true;
|
||||
}
|
||||
export async function markOnboarded(): Promise<void> {
|
||||
await setLocal({ [KEYS.onboarded]: true });
|
||||
}
|
||||
|
||||
async function anonId(): Promise<string> {
|
||||
const v = await getLocal([KEYS.anonId]);
|
||||
if (typeof v[KEYS.anonId] === 'string') return v[KEYS.anonId];
|
||||
const id =
|
||||
globalThis.crypto?.randomUUID?.() ??
|
||||
`a-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
||||
await setLocal({ [KEYS.anonId]: id });
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Anonymous product-usage event. No query/answer text, no PII. No-op when
|
||||
* insights is off. Never throws. */
|
||||
export async function capture(event: string, props?: Record<string, unknown>): Promise<void> {
|
||||
try {
|
||||
const c = await getConsent();
|
||||
if (!c.insights) return;
|
||||
const anon_id = await anonId();
|
||||
await fetch(`${API_BASE_URL}/v1/insights`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ event, props: props ?? {}, anon_id, ts: Date.now(), source: 'extension' }),
|
||||
keepalive: true,
|
||||
}).catch(() => {});
|
||||
} catch {
|
||||
/* fail-soft */
|
||||
}
|
||||
}
|
||||
|
||||
/** Contribute one search+answer sample to train Hanzo's open models. No-op
|
||||
* unless the user opted in. Sent with the IAM bearer so it's the user's own,
|
||||
* attributable data. Never throws. */
|
||||
export async function contributeTrainingSample(sample: {
|
||||
query: string;
|
||||
answer: string;
|
||||
model?: string;
|
||||
sources?: string[];
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const c = await getConsent();
|
||||
if (!c.shareTraining) return;
|
||||
if (!sample.query || !sample.answer) return;
|
||||
const tok = await token();
|
||||
await fetch(`${API_BASE_URL}/v1/training/contributions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(tok ? { authorization: `Bearer ${tok}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({ ...sample, source: 'extension:answer-engine', ts: Date.now() }),
|
||||
keepalive: true,
|
||||
}).catch(() => {});
|
||||
} catch {
|
||||
/* fail-soft */
|
||||
}
|
||||
}
|
||||
@@ -1,47 +1,49 @@
|
||||
/**
|
||||
* KMS (Key Management / Secrets) client — shared across all browser targets.
|
||||
*
|
||||
* Lightweight fetch-based client for Hanzo KMS (kms.hanzo.ai).
|
||||
* Uses IAM bearer tokens for auth — no separate KMS credentials needed.
|
||||
* Lightweight fetch-based client for Hanzo KMS. Uses IAM bearer tokens for
|
||||
* auth — no separate KMS credentials needed.
|
||||
*
|
||||
* API path. Hanzo convention is `/v1/<service>/<endpoint>` — but the KMS
|
||||
* upstream publishes its v3 API under the root
|
||||
* `${KMS_PATH_PREFIX}/secrets/raw`. The kms.hanzo.ai gateway currently passes that
|
||||
* through unchanged (verified: `kms.hanzo.ai/api/v3/secrets/raw` → 401 JSON,
|
||||
* `/v1/kms/...` → SPA HTML). We centralise the path in `KMS_PATH_PREFIX`
|
||||
* so the day the gateway adds the rewrite we update one constant.
|
||||
* Every path is `/v1/kms/...`, which is the Hanzo `/v1/<service>/<endpoint>`
|
||||
* convention and, more importantly, what the server actually serves:
|
||||
*
|
||||
* GET {KMS_PATH_PREFIX}/secrets/raw → list
|
||||
* GET {KMS_PATH_PREFIX}/secrets/raw/:name → get
|
||||
* POST {KMS_PATH_PREFIX}/secrets/raw/:name → create
|
||||
* PATCH {KMS_PATH_PREFIX}/secrets/raw/:name → update
|
||||
* DELETE {KMS_PATH_PREFIX}/secrets/raw/:name → delete
|
||||
* GET /v1/kms/orgs/{org}/secrets?path=&env= → list names
|
||||
* GET /v1/kms/orgs/{org}/secrets/{path}/{name}?env= → read one value
|
||||
* POST /v1/kms/orgs/{org}/secrets → create or replace
|
||||
* DELETE /v1/kms/orgs/{org}/secrets/{path}/{name}?env= → delete
|
||||
*
|
||||
* This file used to speak Infisical's shape under an `/api/v3` prefix, with a
|
||||
* header comment reporting that `/v1/kms/...` had been *verified* to return SPA
|
||||
* HTML while `/api/v3/secrets/raw` returned JSON — so `/api/v3` was pinned as
|
||||
* the working path and a rewrite was awaited. The observation was real and the
|
||||
* conclusion was backwards: the KMS binary embedded a console SPA under a root
|
||||
* catch-all, so it answered EVERY unmatched path with 200 text/html. The HTML
|
||||
* was the 404. luxfi/kms 1.12.8 removed the catch-all, and the same probe now
|
||||
* reads the other way round — `/v1/kms/...` answers JSON, `/api/v3/...` is a
|
||||
* JSON 404. There is no gateway rewrite to wait for.
|
||||
*
|
||||
* Create and update are ONE call because the server has one upsert, not two
|
||||
* endpoints. Listing arrived in luxfi/kms 1.12.9; before that the HTTP surface
|
||||
* had no list at all, which is what made the Infisical prefix look necessary.
|
||||
*/
|
||||
|
||||
import { KMS_API_URL } from './config.js';
|
||||
|
||||
/** Prefix for every KMS request. See file header. */
|
||||
const KMS_PATH_PREFIX = '/api/v3';
|
||||
|
||||
// ── Types ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface KmsSecret {
|
||||
secretKey: string;
|
||||
secretValue?: string;
|
||||
version?: number;
|
||||
type?: string;
|
||||
environment?: string;
|
||||
secretPath?: string;
|
||||
/** Where a secret lives. `path` groups secrets; `name` identifies one. */
|
||||
export interface KmsRef {
|
||||
/** Org scope — also the scope of the bearer token that reads it. */
|
||||
org: string;
|
||||
/** Environment slug (`dev` / `test` / `main`). Defaults to `default`. */
|
||||
env?: string;
|
||||
/** Grouping path, e.g. `gateway`. Omit to address the org root. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export interface KmsListParams {
|
||||
workspaceId: string;
|
||||
environment: string;
|
||||
secretPath?: string;
|
||||
}
|
||||
|
||||
export interface KmsSecretParams extends KmsListParams {
|
||||
secretName: string;
|
||||
/** A ref plus the name of a single secret. */
|
||||
export interface KmsSecretRef extends KmsRef {
|
||||
name: string;
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
@@ -57,121 +59,94 @@ function kmsUrl(path: string, baseUrl?: string): string {
|
||||
return `${baseUrl || KMS_API_URL}${path}`;
|
||||
}
|
||||
|
||||
function buildQuery(params: Record<string, string | undefined>): string {
|
||||
const entries = Object.entries(params).filter(([, v]) => v !== undefined) as [string, string][];
|
||||
if (!entries.length) return '';
|
||||
return '?' + new URLSearchParams(entries).toString();
|
||||
/** The collection URL for an org, with `path`/`env` as query. */
|
||||
function collectionUrl(ref: KmsRef, baseUrl?: string): string {
|
||||
const q = new URLSearchParams();
|
||||
if (ref.path) q.set('path', ref.path);
|
||||
q.set('env', ref.env || 'default');
|
||||
return kmsUrl(`/v1/kms/orgs/${encodeURIComponent(ref.org)}/secrets?${q}`, baseUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL of one secret. The server splits the trailing `{rest...}` at its LAST
|
||||
* slash into (path, name), so each segment is escaped on its own — escaping the
|
||||
* joined string would encode the separators and the server would read one long
|
||||
* name.
|
||||
*/
|
||||
function secretUrl(ref: KmsSecretRef, baseUrl?: string): string {
|
||||
const segs = [...(ref.path ? ref.path.split('/') : []), ref.name]
|
||||
.filter((s) => s.length > 0)
|
||||
.map(encodeURIComponent)
|
||||
.join('/');
|
||||
const q = new URLSearchParams({ env: ref.env || 'default' });
|
||||
return kmsUrl(`/v1/kms/orgs/${encodeURIComponent(ref.org)}/secrets/${segs}?${q}`, baseUrl);
|
||||
}
|
||||
|
||||
async function fail(op: string, resp: Response): Promise<never> {
|
||||
throw new Error(`KMS ${op} failed: ${resp.status} ${await resp.text()}`);
|
||||
}
|
||||
|
||||
// ── API Functions ───────────────────────────────────────────────────────
|
||||
|
||||
/** List secrets in a workspace/environment */
|
||||
/** List the names of the secrets under a path. */
|
||||
export async function kmsListSecrets(
|
||||
token: string,
|
||||
params: KmsListParams,
|
||||
ref: KmsRef,
|
||||
baseUrl?: string,
|
||||
): Promise<KmsSecret[]> {
|
||||
const query = buildQuery({
|
||||
workspaceId: params.workspaceId,
|
||||
environment: params.environment,
|
||||
secretPath: params.secretPath,
|
||||
});
|
||||
const resp = await fetch(kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw${query}`, baseUrl), {
|
||||
headers: kmsHeaders(token),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`KMS list failed: ${resp.status} ${await resp.text()}`);
|
||||
): Promise<string[]> {
|
||||
const resp = await fetch(collectionUrl(ref, baseUrl), { headers: kmsHeaders(token) });
|
||||
if (!resp.ok) return fail('list', resp);
|
||||
const data = await resp.json();
|
||||
return data.secrets || data;
|
||||
return data.names ?? [];
|
||||
}
|
||||
|
||||
/** Get a single secret by name */
|
||||
/** Read one secret's value. */
|
||||
export async function kmsGetSecret(
|
||||
token: string,
|
||||
params: KmsSecretParams,
|
||||
ref: KmsSecretRef,
|
||||
baseUrl?: string,
|
||||
): Promise<KmsSecret> {
|
||||
const query = buildQuery({
|
||||
workspaceId: params.workspaceId,
|
||||
environment: params.environment,
|
||||
secretPath: params.secretPath,
|
||||
});
|
||||
const resp = await fetch(
|
||||
kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw/${encodeURIComponent(params.secretName)}${query}`, baseUrl),
|
||||
{ headers: kmsHeaders(token) },
|
||||
);
|
||||
if (!resp.ok) throw new Error(`KMS get failed: ${resp.status} ${await resp.text()}`);
|
||||
): Promise<string> {
|
||||
const resp = await fetch(secretUrl(ref, baseUrl), { headers: kmsHeaders(token) });
|
||||
if (!resp.ok) return fail('get', resp);
|
||||
const data = await resp.json();
|
||||
return data.secret || data;
|
||||
return data.secret?.value ?? '';
|
||||
}
|
||||
|
||||
/** Create a new secret */
|
||||
export async function kmsCreateSecret(
|
||||
/**
|
||||
* Create a secret, or replace it if the name already exists. One call, because
|
||||
* the server has one upsert — there is no separate create and update.
|
||||
*/
|
||||
export async function kmsPutSecret(
|
||||
token: string,
|
||||
params: KmsSecretParams,
|
||||
ref: KmsSecretRef,
|
||||
value: string,
|
||||
baseUrl?: string,
|
||||
): Promise<KmsSecret> {
|
||||
): Promise<void> {
|
||||
const resp = await fetch(
|
||||
kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw/${encodeURIComponent(params.secretName)}`, baseUrl),
|
||||
kmsUrl(`/v1/kms/orgs/${encodeURIComponent(ref.org)}/secrets`, baseUrl),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: kmsHeaders(token),
|
||||
body: JSON.stringify({
|
||||
workspaceId: params.workspaceId,
|
||||
environment: params.environment,
|
||||
secretPath: params.secretPath,
|
||||
secretValue: value,
|
||||
type: 'shared',
|
||||
path: ref.path ?? '',
|
||||
name: ref.name,
|
||||
env: ref.env || 'default',
|
||||
value,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!resp.ok) throw new Error(`KMS create failed: ${resp.status} ${await resp.text()}`);
|
||||
const data = await resp.json();
|
||||
return data.secret || data;
|
||||
if (!resp.ok) return fail('put', resp);
|
||||
}
|
||||
|
||||
/** Update an existing secret */
|
||||
export async function kmsUpdateSecret(
|
||||
token: string,
|
||||
params: KmsSecretParams,
|
||||
value: string,
|
||||
baseUrl?: string,
|
||||
): Promise<KmsSecret> {
|
||||
const resp = await fetch(
|
||||
kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw/${encodeURIComponent(params.secretName)}`, baseUrl),
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: kmsHeaders(token),
|
||||
body: JSON.stringify({
|
||||
workspaceId: params.workspaceId,
|
||||
environment: params.environment,
|
||||
secretPath: params.secretPath,
|
||||
secretValue: value,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!resp.ok) throw new Error(`KMS update failed: ${resp.status} ${await resp.text()}`);
|
||||
const data = await resp.json();
|
||||
return data.secret || data;
|
||||
}
|
||||
|
||||
/** Delete a secret */
|
||||
/** Delete a secret. */
|
||||
export async function kmsDeleteSecret(
|
||||
token: string,
|
||||
params: KmsSecretParams,
|
||||
ref: KmsSecretRef,
|
||||
baseUrl?: string,
|
||||
): Promise<void> {
|
||||
const resp = await fetch(
|
||||
kmsUrl(`${KMS_PATH_PREFIX}/secrets/raw/${encodeURIComponent(params.secretName)}`, baseUrl),
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers: kmsHeaders(token),
|
||||
body: JSON.stringify({
|
||||
workspaceId: params.workspaceId,
|
||||
environment: params.environment,
|
||||
secretPath: params.secretPath,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!resp.ok) throw new Error(`KMS delete failed: ${resp.status} ${await resp.text()}`);
|
||||
const resp = await fetch(secretUrl(ref, baseUrl), {
|
||||
method: 'DELETE',
|
||||
headers: kmsHeaders(token),
|
||||
});
|
||||
if (!resp.ok) return fail('delete', resp);
|
||||
}
|
||||
|
||||
@@ -63,7 +63,11 @@ export interface NativeZapState {
|
||||
|
||||
export type Dispatch = (method: string, params: any) => Promise<any> | any;
|
||||
|
||||
const RECONNECT_MS = 3000;
|
||||
// Gentle safe poll: with no MCP client running there is no router to reach, so
|
||||
// the host connects-then-exits; probe every 30s instead of hammering (and
|
||||
// re-launching the native host) every 3s. A live consumer is picked up within
|
||||
// one interval.
|
||||
const RECONNECT_MS = 30_000;
|
||||
|
||||
/** Connect to zapd via the native host, register as a browser provider, and
|
||||
* dispatch inbound ROUTE commands to the browser. Self-heals on disconnect. */
|
||||
|
||||
@@ -2,8 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import {
|
||||
kmsListSecrets,
|
||||
kmsGetSecret,
|
||||
kmsCreateSecret,
|
||||
kmsUpdateSecret,
|
||||
kmsPutSecret,
|
||||
kmsDeleteSecret,
|
||||
} from '../src/shared/kms';
|
||||
|
||||
@@ -24,49 +23,95 @@ function mockResponse(data: any, ok = true, status = 200) {
|
||||
}
|
||||
|
||||
const TOKEN = 'test-bearer-token';
|
||||
const PARAMS = {
|
||||
workspaceId: 'ws-123',
|
||||
environment: 'production',
|
||||
secretPath: '/app',
|
||||
};
|
||||
const REF = { org: 'hanzo', env: 'production', path: 'app' };
|
||||
const SECRET = { ...REF, name: 'API_KEY' };
|
||||
|
||||
function calledUrl(): string {
|
||||
return mockFetch.mock.calls[0][0] as string;
|
||||
}
|
||||
|
||||
function calledInit(): any {
|
||||
return mockFetch.mock.calls[0][1];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch.mockReset();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Path shape — the regression that actually happened
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('KMS paths', () => {
|
||||
it('never emits an /api/ prefix', async () => {
|
||||
// This client used to speak /api/v3/secrets/raw, because the KMS binary
|
||||
// embedded a console SPA under a root catch-all and answered every
|
||||
// unmatched path with 200 text/html — so the wrong path looked alive and
|
||||
// the right one looked broken. Nothing may drift back to it.
|
||||
mockFetch.mockResolvedValue(mockResponse({ names: [] }));
|
||||
await kmsListSecrets(TOKEN, REF);
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: { value: 'v' } }));
|
||||
await kmsGetSecret(TOKEN, SECRET);
|
||||
mockFetch.mockResolvedValue(mockResponse({}));
|
||||
await kmsPutSecret(TOKEN, SECRET, 'v');
|
||||
mockFetch.mockResolvedValue(mockResponse({}));
|
||||
await kmsDeleteSecret(TOKEN, SECRET);
|
||||
|
||||
expect(mockFetch.mock.calls).toHaveLength(4);
|
||||
for (const [url] of mockFetch.mock.calls) {
|
||||
expect(url).not.toContain('/api/');
|
||||
expect(url).toContain('/v1/kms/');
|
||||
}
|
||||
});
|
||||
|
||||
it('escapes path segments individually so separators survive', async () => {
|
||||
// The server splits {rest...} at its LAST slash into (path, name). Escaping
|
||||
// the joined string would encode the separators into one long name.
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: { value: 'v' } }));
|
||||
await kmsGetSecret(TOKEN, { org: 'hanzo', env: 'main', path: 'a/b', name: 'C D' });
|
||||
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets/a/b/C%20D');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// kmsListSecrets
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('kmsListSecrets', () => {
|
||||
it('sends GET with correct URL and query params', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secrets: [{ secretKey: 'API_KEY' }] }));
|
||||
|
||||
const result = await kmsListSecrets(TOKEN, PARAMS);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, opts] = mockFetch.mock.calls[0];
|
||||
expect(url).toContain('kms.hanzo.ai/api/v3/secrets/raw?');
|
||||
expect(url).toContain('workspaceId=ws-123');
|
||||
expect(url).toContain('environment=production');
|
||||
expect(url).toContain('secretPath=%2Fapp');
|
||||
expect(opts.headers.Authorization).toBe(`Bearer ${TOKEN}`);
|
||||
expect(result).toEqual([{ secretKey: 'API_KEY' }]);
|
||||
it('returns the names array', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ names: ['API_KEY', 'DB_URL'] }));
|
||||
await expect(kmsListSecrets(TOKEN, REF)).resolves.toEqual(['API_KEY', 'DB_URL']);
|
||||
});
|
||||
|
||||
it('uses custom baseUrl when provided', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secrets: [] }));
|
||||
|
||||
await kmsListSecrets(TOKEN, PARAMS, 'https://custom-kms.example.com');
|
||||
|
||||
const [url] = mockFetch.mock.calls[0];
|
||||
expect(url).toContain('custom-kms.example.com/api/v3/secrets/raw');
|
||||
it('addresses the collection with path and env as query, and sends the bearer', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ names: [] }));
|
||||
await kmsListSecrets(TOKEN, REF);
|
||||
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets?');
|
||||
expect(calledUrl()).toContain('path=app');
|
||||
expect(calledUrl()).toContain('env=production');
|
||||
expect(calledInit().headers.Authorization).toBe(`Bearer ${TOKEN}`);
|
||||
});
|
||||
|
||||
it('throws on non-ok response', async () => {
|
||||
it('defaults env when the ref omits it', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ names: [] }));
|
||||
await kmsListSecrets(TOKEN, { org: 'hanzo' });
|
||||
expect(calledUrl()).toContain('env=default');
|
||||
});
|
||||
|
||||
it('yields an empty array when the server omits names', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({}));
|
||||
await expect(kmsListSecrets(TOKEN, REF)).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it('uses a custom baseUrl when provided', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ names: [] }));
|
||||
await kmsListSecrets(TOKEN, REF, 'https://custom-kms.example.com');
|
||||
expect(calledUrl()).toContain('custom-kms.example.com/v1/kms/orgs/hanzo/secrets');
|
||||
});
|
||||
|
||||
it('throws with the status on failure', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse('Not found', false, 404));
|
||||
|
||||
await expect(kmsListSecrets(TOKEN, PARAMS)).rejects.toThrow('KMS list failed: 404');
|
||||
await expect(kmsListSecrets(TOKEN, REF)).rejects.toThrow('KMS list failed: 404');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -75,78 +120,47 @@ describe('kmsListSecrets', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('kmsGetSecret', () => {
|
||||
it('sends GET with encoded secret name', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: { secretKey: 'DB_URL', secretValue: 'postgres://...' } }));
|
||||
|
||||
const result = await kmsGetSecret(TOKEN, { ...PARAMS, secretName: 'DB_URL' });
|
||||
|
||||
const [url] = mockFetch.mock.calls[0];
|
||||
expect(url).toContain('/api/v3/secrets/raw/DB_URL');
|
||||
expect(result.secretKey).toBe('DB_URL');
|
||||
it('unwraps secret.value', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: { value: 'postgres://...' } }));
|
||||
await expect(kmsGetSecret(TOKEN, SECRET)).resolves.toBe('postgres://...');
|
||||
});
|
||||
|
||||
it('URL-encodes special characters in secret name', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: { secretKey: 'app/key' } }));
|
||||
|
||||
await kmsGetSecret(TOKEN, { ...PARAMS, secretName: 'app/key' });
|
||||
|
||||
const [url] = mockFetch.mock.calls[0];
|
||||
expect(url).toContain('app%2Fkey');
|
||||
it('addresses the secret and carries env', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: { value: 'v' } }));
|
||||
await kmsGetSecret(TOKEN, SECRET);
|
||||
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets/app/API_KEY');
|
||||
expect(calledUrl()).toContain('env=production');
|
||||
});
|
||||
|
||||
it('throws on non-ok response', async () => {
|
||||
it('throws with the status on failure', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse('Not found', false, 404));
|
||||
await expect(kmsGetSecret(TOKEN, SECRET)).rejects.toThrow('KMS get failed: 404');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// kmsPutSecret — create and replace are one call, because the server has one
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('kmsPutSecret', () => {
|
||||
it('POSTs to the collection with the flat body the server takes', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({}));
|
||||
await kmsPutSecret(TOKEN, SECRET, 'sk-live-123');
|
||||
|
||||
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets');
|
||||
expect(calledUrl()).not.toContain('API_KEY'); // name is in the body, not the URL
|
||||
expect(calledInit().method).toBe('POST');
|
||||
expect(JSON.parse(calledInit().body)).toEqual({
|
||||
path: 'app',
|
||||
name: 'API_KEY',
|
||||
env: 'production',
|
||||
value: 'sk-live-123',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws with the status on failure', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse('Forbidden', false, 403));
|
||||
|
||||
await expect(kmsGetSecret(TOKEN, { ...PARAMS, secretName: 'X' })).rejects.toThrow('KMS get failed: 403');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// kmsCreateSecret
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('kmsCreateSecret', () => {
|
||||
it('sends POST with correct body', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: { secretKey: 'NEW_KEY' } }));
|
||||
|
||||
await kmsCreateSecret(TOKEN, { ...PARAMS, secretName: 'NEW_KEY' }, 'secret-value');
|
||||
|
||||
const [url, opts] = mockFetch.mock.calls[0];
|
||||
expect(url).toContain('/api/v3/secrets/raw/NEW_KEY');
|
||||
expect(opts.method).toBe('POST');
|
||||
const body = JSON.parse(opts.body);
|
||||
expect(body.secretValue).toBe('secret-value');
|
||||
expect(body.workspaceId).toBe('ws-123');
|
||||
expect(body.environment).toBe('production');
|
||||
expect(body.type).toBe('shared');
|
||||
});
|
||||
|
||||
it('includes Authorization header', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: {} }));
|
||||
|
||||
await kmsCreateSecret(TOKEN, { ...PARAMS, secretName: 'X' }, 'val');
|
||||
|
||||
const [, opts] = mockFetch.mock.calls[0];
|
||||
expect(opts.headers.Authorization).toBe(`Bearer ${TOKEN}`);
|
||||
expect(opts.headers['Content-Type']).toBe('application/json');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// kmsUpdateSecret
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('kmsUpdateSecret', () => {
|
||||
it('sends PATCH with correct body', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({ secret: { secretKey: 'KEY' } }));
|
||||
|
||||
await kmsUpdateSecret(TOKEN, { ...PARAMS, secretName: 'KEY' }, 'new-value');
|
||||
|
||||
const [url, opts] = mockFetch.mock.calls[0];
|
||||
expect(url).toContain('/api/v3/secrets/raw/KEY');
|
||||
expect(opts.method).toBe('PATCH');
|
||||
const body = JSON.parse(opts.body);
|
||||
expect(body.secretValue).toBe('new-value');
|
||||
await expect(kmsPutSecret(TOKEN, SECRET, 'v')).rejects.toThrow('KMS put failed: 403');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -155,21 +169,16 @@ describe('kmsUpdateSecret', () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('kmsDeleteSecret', () => {
|
||||
it('sends DELETE with correct body', async () => {
|
||||
it('DELETEs the secret URL', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse({}));
|
||||
|
||||
await kmsDeleteSecret(TOKEN, { ...PARAMS, secretName: 'OLD_KEY' });
|
||||
|
||||
const [url, opts] = mockFetch.mock.calls[0];
|
||||
expect(url).toContain('/api/v3/secrets/raw/OLD_KEY');
|
||||
expect(opts.method).toBe('DELETE');
|
||||
const body = JSON.parse(opts.body);
|
||||
expect(body.workspaceId).toBe('ws-123');
|
||||
await kmsDeleteSecret(TOKEN, SECRET);
|
||||
expect(calledInit().method).toBe('DELETE');
|
||||
expect(calledUrl()).toContain('/v1/kms/orgs/hanzo/secrets/app/API_KEY');
|
||||
expect(calledUrl()).toContain('env=production');
|
||||
});
|
||||
|
||||
it('throws on non-ok response', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse('Server Error', false, 500));
|
||||
|
||||
await expect(kmsDeleteSecret(TOKEN, { ...PARAMS, secretName: 'X' })).rejects.toThrow('KMS delete failed: 500');
|
||||
it('throws with the status on failure', async () => {
|
||||
mockFetch.mockResolvedValue(mockResponse('Forbidden', false, 403));
|
||||
await expect(kmsDeleteSecret(TOKEN, SECRET)).rejects.toThrow('KMS delete failed: 403');
|
||||
});
|
||||
});
|
||||
|
||||
Generated
+21
@@ -150,6 +150,9 @@ importers:
|
||||
'@hanzo/ai':
|
||||
specifier: ^0.2.3
|
||||
version: 0.2.3
|
||||
'@hanzo/usage':
|
||||
specifier: ^0.1.6
|
||||
version: 0.1.6(react@18.3.1)
|
||||
'@supabase/supabase-js':
|
||||
specifier: ^2.50.3
|
||||
version: 2.50.3
|
||||
@@ -2892,6 +2895,20 @@ packages:
|
||||
react:
|
||||
optional: true
|
||||
|
||||
'@hanzo/usage@0.1.6':
|
||||
resolution: {integrity: sha512-0gr4ZJ5qTH1hRt706uMciAevFPXG/08Xd5zbyZBlAi1o4k4EdKHTqLm/pRnbhv6jZbWTIOUtRQSysGyeJfOQMQ==}
|
||||
peerDependencies:
|
||||
'@hanzo/gui': '>=7.2.2'
|
||||
'@hanzogui/lucide-icons-2': '>=7.2.2'
|
||||
react: '>=18'
|
||||
peerDependenciesMeta:
|
||||
'@hanzo/gui':
|
||||
optional: true
|
||||
'@hanzogui/lucide-icons-2':
|
||||
optional: true
|
||||
react:
|
||||
optional: true
|
||||
|
||||
'@hono/node-server@1.19.14':
|
||||
resolution: {integrity: sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==}
|
||||
engines: {node: '>=18.14.1'}
|
||||
@@ -13450,6 +13467,10 @@ snapshots:
|
||||
optionalDependencies:
|
||||
react: 19.2.7
|
||||
|
||||
'@hanzo/usage@0.1.6(react@18.3.1)':
|
||||
optionalDependencies:
|
||||
react: 18.3.1
|
||||
|
||||
'@hono/node-server@1.19.14(hono@4.12.27)':
|
||||
dependencies:
|
||||
hono: 4.12.27
|
||||
|
||||
Reference in New Issue
Block a user